Reputation: 371
I have a code that reads values from two columns (Members, Description) in the table dynamically on button click.
JQuery that reads the values from the table:
$(function() {
$('#myButton').on('click', function() {
var myCollection = [];
$('div#body').find('tr:gt(0)').each(function() {
var row = this;
var myObj = {
label: valuefromType($(row).find($(row).find('td:eq(1)').children())),
opis: valuefromType($(row).find($(row).find('td:eq(2)').children()))
};
myCollection[myCollection.length] = myObj;
});
console.log(myCollection)
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
break;
case "span":
return $(control).text();
break;
case "select":
return $(control).val();
break;
}
}
});
});
On button click result stored in array is:
0: Object { label: "1", opis: null }
1: Object { label: "2", opis: "test2" }
2: Object { label: "3", opis: "test3" }
3: Object { label: "5", opis: "3" }
4: Object { label: "9", opis: "test5" }
5: Object { label: "15", opis: "test88" }
Now I need to get the selected value (1,2,3,4,5 ...) from the dropdown list (House Center) that's located above the table and store it in the array on button click.
Can some one help me with that ?
Upvotes: 0
Views: 521
Reputation: 3834
You need to declare array out of click
event, and then add new event binded to your select like this:
$('#MainContent_ddlBusinessCenter').on('change', function () {
myCollection.push($(this).val());
});
If you want to stroe it the same way as are the previous values do it like this:
$('#MainContent_ddlBusinessCenter').on('change', function () {
var dropdown = $(this);
myCollection.push({label: dropdown.val(), opis: dropdown.find("option:selected").text()});
});
EDIT
You can change this myCollection[myCollection.length] = myObj;
to this myCollection.push(myObj)
. It is less memory consuming.
And try to minimize the use of $()
.
$(function() {
$('#myButton').on('click', function() {
var myCollection = [];
$('div#body').find('tr:gt(0)').each(function(i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(2)').children())),
ddl: $('#MainContent_ddlBusinessCenter').val()
});
});
console.log(myCollection);
});
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
return $(control).val();
}
}
});
Upvotes: 1
Reputation: 1405
Like that : Fiddle link
JS:
$('#MainContent_ddlBusinessCenter').on('change', function () {
var value = $('#MainContent_ddlBusinessCenter').val();
alert(value);
});
Upvotes: 1