Step 1:- Put SCRIPT in the HTML Head tag
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//Data to bind in html table
var tableData = [
{
"Column1": "1A", "Column2": "1B"
},
{
"Column1": "2A", "Column2": "2B"
},
{
"Column1": "3A", "Column2": "3B"
},
{
"Column1": "4A", "Column2": "4B"
}
];
//Looping tableData & appending
each rows to html table
$.each(tableData, function (i, k) {
var tRows = "<tr> <td>" + k.Column1 + "</td><td>" + k.Column2 + "</td><td><select
class='FirstDDId'><option
value=''>Select</option></select></td><td><select
class='SecondDDId'><option value=''>Select</option></select></td></tr>";
$("#table1").append(tRows);
});
//Data to bind in First dropdown
var firstDDData = [
{
"Column1": "Fruit", "Column2": "Fruit"
},
{
"Column1": "Veggie", "Column2": "Veggie"
}
];
//Looping firstDDData &
appending option to dropdown
$.each(firstDDData, function (i, k) {
$(".FirstDDId").append($('<option></option>').val(k.Column1).text(k.Column2));
});
//Create Change event for First
dropdown
$(".FirstDDId").change(function () {
//Get First DropDown selected value
var strVal = $(this).val();
//Data to bind in Second dropdown
var secondDDData = [
{
"Column1": "Fruit", "Column2": "Red Apples"
},
{
"Column1": "Fruit", "Column2": "Cherries"
},
{
"Column1": "Fruit", "Column2": "Bananas"
},
{
"Column1": "Veggie", "Column2": "Cauliflower"
},
{
"Column1": "Veggie", "Column2": "Garlic"
},
{
"Column1": "Veggie", "Column2": "Ginger"
}
];
//Get First DropDown closest 'tr'
var row = $(this).closest('tr');
//Find second DropDown from row
var secondDD = row.find('.SecondDDId');
//Call SecondDD function to bind
Second dropdown
SecondDD(secondDDData, strVal, secondDD);
});
function SecondDD(SecondDDData, strVal,
ctr) {
var tRows;
if (strVal != "") {
ctr.empty();
ctr.append($('<option></option>').val("").text("Select"));
$.each(SecondDDData, function (i, k) {
if (k.Column1 == strVal) {
//tRows += "<option
value=" + k.Column1 + ">" + k.Column2 +
"</option>";
ctr.append($('<option></option>').val(k.Column1).text(k.Column2));
}
});
//$(ctr).append(tRows);
}
}
});
</script>
Step 2:- Put TABLE in the HTML Body tag
<table id="table1" border="1" style="border-collapse: collapse">
<tr>
<th>
Column1
</th>
<th>
Column2
</th>
<th>
Column3
</th>
<th>
Column4
</th>
</tr>
</table>
No comments:
Post a Comment