Values from dynamicly generated select are 'undefined' - javascript

I have a table that dynamicly generates new rows and I need to get values from dynamicly generated selectbox. But all I get is 'undefined'. If I try to get values from dynamic <input> then everything works fine. Problem is just with selectbox.
Here is my code that gets values from user
$("#myTable tr").each(function(index, element){
if(index === 0){ // skip the table head
return true;
}
var option = $(element).find("#course option:selected");
if(option.val() == "-1"){ // should skip empty row but doesn't work either
return true;
}
$(element).children().each(function(index, element){
if(index === 0){
activities[activities.length] = $(element).find("input").val();
}else if(index === 1){
activityIds[activityIds.length] = option.val();
activityType[activityType.length] = option.attr("type");
}
});
});
JSFiddle http://jsfiddle.net/8rrmr/
Thanks for any help

In your addNewActivityRow function, you are not giving your select box the #course id. Actually, you should not use ids in this case but classes since an id must be unique for a page. Change the following line:
var option = $(element).find("#course option:selected");
to:
var option = $(element).find("select option:selected");
and it will work, but it would be best to remove all ids from your elements if you are going to have multiple instances of them

try something like this,FIDDLE
CHANGE THIS
// can't find #course
var option = $(element).find("#course option:selected");
TO
var option = $(element).find("select option:selected");

Try this,
activityIds[activityIds.length] = $(element).find('select').val();
activityType[activityType.length] = $(element).find('input').attr("type");

Related

Storing Key and Value using Javascript in array

I have a jsp page on which table is coming dynamically and have checkboxes on that page when you click on that box it should save in array and when it uncheck the box it should remove value from array.
I have tried this by creating a method but it is not working perfectly can you please help me..
function addCheckboxVAlues(checked){
var split = checked.value.split("|");
var key =split[0];
var value=split[1];
var chks = $("input[name='"+key+"']:checked");
if (chks.length > 0) {
uninvoiced.push(value);
} else {
uninvoiced.pop(key);
}
console.log(uninvoiced);
}
You need to use splice to remove the element from the array
function addCheckboxVAlues(checked){
var split = checked.value.split("|");
var key =split[0];
var value=split[1];
var chks = $("input[name='"+key+"']:checked");
var index = uninvoiced.indexOf(key);
if (chks.length > 0) {
uninvoiced.push(value);
} else if(index > -1){
uninvoiced.splice(index, 1);
}
console.log(uninvoiced);
}
This code looks way more complex than it needs to be. Presumably the checkbox has a click listener on it, so it should be called with the checkbox as this. All you have to do is add the value if the checkbox is checked, or remove it if it's unchecked.
That will be hugely more efficient than running a checked selector every time.
The following uses an inline listener for convenience, likey you're attaching them dynamically but it seems to be called the same way.
var uninvoiced = [];
function addCheckbox(el) {
var value = el.value.split('|')[1];
if (el.checked) {
uninvoiced.push(value);
} else {
uninvoiced.splice(uninvoiced.indexOf(value), 1);
}
console.log(uninvoiced);
}
foo|bar: <input type="checkbox" value="foo|bar" onclick="addCheckbox(this)">
fee|fum: <input type="checkbox" value="fee|fum" onclick="addCheckbox(this)">
There is a polyfill for indexOf on MDN.

How do I get the value of each ListItem in a ListBox using JavaScript

I have a ListBox that's dynamically populated. I'd like to mark each selected ListItem as "selected" if the value of the ListItem matches a specific string of characters.
ASP.NET:
<asp:ListBox ID="lstComputers" runat="server"></asp:ListBox>
C#:
//code that populates lstComputers.
//I got this part working properly already
Javascript:
//I'm really bad at javascript, so here's the sudo code of what I'd like done
For each ListItem in lstComputers{
If ListItem.value like 'HP%' then{ //assuming % is like a wild card in SQL
ListItem.selected = true;
}
}
Please help me out with the JavaScript.
Thanks
Try this:-
function SelectListBox() {
var lstComputers = document.getElementById("<%= lstComputers.ClientID %>");
for (var i = 0; i < lstComputers.options.length; i++) {
if (lstComputers.options[i].text.indexOf("HP") > -1) {
lstComputers.options[i].selected = true;
}
}
}
Also, Please make sure you have SelectionMode property set to Multiple if you want multiple selection in ListBox control.
The Asp.net ListBox will generate the html of Select Tag and we can access that select element and its option in javascript using jQuery easily.
Following is the Javascript code that will do your work.
<script>
$("#lstComputers option").each(function(){
var option = $(this);
if(option.text().indexOf('HP') == 0)
{
option.attr('selected','selected');
}
});
</script>

How to add a value to the JavaScript variable?

var options = $('#mobility-table').find('select.MobilityCountry[data="'+selectionId+'"]').data('options').filter('[data="' + id + '"]');
options.sort(function(a,b) {
if (a.innerHTML > b.innerHTML) return 1;
else if (a.innerHTML < b.innerHTML) return -1;
else return 0;
The above code will give me all the list of cities upon selecting a country. I would like to add a default value 'All' at the first place in the variable 'options'. Can any one suggest me how to add this. Any help greatly appreciated. Thankyou.
Ex: options should have 'All,London,Scotland,Stanmore, Watford'.
You can use unshift() to add an element to the beginning of the sorted array:
If you're just trying to add text to the first element, it would be like this:
options.sort(function(a,b) {
if (a.innerHTML > b.innerHTML) return 1;
else if (a.innerHTML < b.innerHTML) return -1;
else return 0;
}
options.unshift("All");
If you want to add an option element to the array, it would be like this:
var item = document.createElement("option");
item.value = "all";
item.innerHTML = "All";
options.unshift(item);
It isn't clear to me whether you're also trying to change your HTML. If so, then please show what your HTML looks like so we can advise how to add that element to the DOM. It's not clear to me what HTML item is the select item.
In jQuery, you could add the option to be the first item in the drop-down like this
// you have to fill in the appropriate selector for your select object
$("#selector for select object").prepend("<option value='all'>All</option>");
unshift() a new <option>:
var option = document.createElement("option");
option.value = "all";
option.appendChild(document.createTextNode("All"));
options.unshift(option);
jQuery:
options.unshift($("<option>", {text: "All", value: "all"}).get(0));

JQuery DataTables How to get selected rows from table when we using paging?

For example I selected (checked) 2 rows from second page than go to first page and select 3 rows. I want get information from 5 selected rows when I stay at first page.
$('tr.row_selected') - not working
Thanks.
Upd.
I created handler somthing like this:
$('#example').find('tr td.sel-checkbox').live("click", function () {
/*code here*/
});
But right now when click event is hadle the row from table is hidding. I think it may be sorting or grouping operation of DataTables. Any idea what I must do with this?
When a checkbox gets selected, store the row information you want in a global object as a Key-Value pair
I don't remember specifically how i did it before but the syntax was something like
$('input[type=checkbox]').click(function()
{
var row = $(this).parent(); //this or something like it, you want the TR element, it's just a matter of how far up you need to go
var columns = row.children(); //these are the td elements
var id = columns[0].val(); //since these are TDs, you may need to go down another element to get to the actual value
if (!this.checked) //becomes checked (not sure may be the other way around, don't remember when this event will get fired)
{
var val1 = columns[1].val();
var val2 = columns[2].val();
myCheckValues[id] =[val1,val2]; //Add the data to your global object which should be declared on document ready
}
else delete myCheckValues[id];
});
When you submit, get the selected rows from your object:
for (var i = 0; i < myCheckValues.length; i++)
...
Sorry, haven't done JS in a long time so code as is might not work but you get the idea.
$('#example').find('tr td.sel-checkbox').live("click", function () {
var data = oTable.fnGetData(this);
// get key and data value from data object
var isSelected = $(this).hasClass('row_selected');
if(isSelected) {
myCheckValues[key] = value;
checkedCount++;
} else {
delete myCheckValues[key];
checkedCount--;
}
});
.....
On submit
if(checkedCount > 0) {
for(var ArrVal in myCheckValues) {
var values = myCheckValues[ArrVal]; // manipulate with checked rows values data
}
}

Having jQuery string comparison issues

I've got a fiddle going here to show what I'm trying to do.
I have a table that is generated dynamically, so the columns could appear in whatever order the user chooses. So, I'm trying to get the index of two specific headers so that I can add a CSS class to those two columns for use later.
You should use .filter() here instead (and whenever you need to restrict the element set), since your .each() return is getting thrown away, like this:
//Loop thru the headers and get the Supp elem
var suppCol = $("#my_table th").filter(function() {
return $(this).html() == "Supp";
});
//Loop thru the headers and get the Report elem
var reportCol = $("#my_table th").filter(function() {
return $(this).html() == "Report";
});
You can test the updated/working fiddle here. The alternative using .each() would look like tis:
var suppCol, reportCol;
$("#my_table th").each(function() {
var $this = $(this), html = $this.html();
if(html == "Supp") suppCol = $this;
if(html == "Report") reportCol= $this;
});
You can test that version here.

Categories

Resources