How to pull value while looping thru a table row? - javascript

I have a table that I am looping thru and would like to pull the value from a column in each row. How do I do that?
$('#buildingList tr').each(function () {
//check each column in the row and get value from column 3 which is a drop down
});
<table id="buildingList">
<tr>
<td class="ms-vb2"/>
<td class="ms-vb2"/>
<td class="ms-vb2">
<select id="ddl">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</td>
</tr>
<tr>
<td class="ms-vb2"/>
<td class="ms-vb2"/>
<td class="ms-vb2">
<select id="ddl">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</td>
</tr>
<tr>
<td class="ms-vb2"/>
<td class="ms-vb2"/>
<td class="ms-vb2">
<select id="ddl">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</td>
</tr>
</table>

Use the :selected option and work with the element's value in your each loop:
$('#buildingList td select option:selected').each(function(i, el) {
// Do something with $(el).val() or el.value
});

Depends what you want to do with the values. If you want to store them in an array you can do it by:
var values = [];
$('#buildingList tr select').each(function (index, elem) {
values.push(elem.value);
});
Also on a side note. You have multiple <select> element's with the same ID. An id-attribute should be unique.

You can directly get the drop downs in the 3rd column of each row using:
$('#buildingList tr td:eq(2) select').each(function () {
var dropDown = $(this); //this refers to the DOM Select
});

$('#buildingList tr td:nth-child(3) select option:selected').each(function () {
var myValue = $(this).text();
});
edited for consolidated version

Related

Iterating over checkboxes in jQuery

I have a table with check-boxes, a dropdown, and other accompanying data.
I'd like to iterate over the rows that have been checked, and pull it's data, add that data into a dictionary, then into a master array.
It seems to be finding the correct rows with check boxes, but my for loop is not pulling each row properly. Here is my js code:
$("#thechecked").click(function(){
var send_list = []
$('#mytable').find(':checkbox:checked').each(function () {
var dict = {};
var value = $("#presetChoosen").val();
var filename = $("#filename").text();
dict['filename'] = filename
dict['value'] = value
send_list.push(dict)
});
console.log(send_list)
});
FULL EXAMPLE IN JSFIDDLE
What am I doing wrong?
You should not use the same ids everywhere like you did on the select element. Id's elements are meant to be unique.
I've used some jQuery methods(parent(), find(), next()) to target the specific values:
var value = $(this).parent().parent().find("select option:checked").val();
var filename = $(this).parent().next("td").text();
Below is a working snippet of what you're trying to achieve:
$("#thechecked").click(function() {
var send_list = []
$('#mytable').find(':checkbox:checked').each(function() {
var dict = {};
var value = $(this).parent().parent().find("select option:checked").val();
var filename = $(this).parent().next("td").text();
dict['filename'] = filename
dict['value'] = value
send_list.push(dict)
});
console.log(send_list)
});
tr,
td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
<thead>
<tr id="mq">
<td><input type="checkbox" /></td>
<td>What</td>
<td>Meta</td>
<td>Preset</td>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox" /></td>
<td id="filename_1">Underthesea</td>
<td>1920x1080</td>
<td> <select id="presetChoosen_1">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="2">
<td><input type="checkbox" /></td>
<td id="filename_2">Overthehill</td>
<td>1280x720</td>
<td> <select id="presetChoosen_2" value="asd">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="3">
<td><input type="checkbox" /></td>
<td id="filename">Mocking</td>
<td>1280x720</td>
<td> <select id="presetChoosen" value="asd">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
</tbody>
</table>
<button id="thechecked">Get Checked</button>
You're re-using id attributes. IDs are supposed to be unique - and I believe it's actually a WC3 validation error to re-use the same ID in HTML.
You're also not scoping your selector to your checkbox at all.
Change your id="" to name="" and then try the following code concept:
$('#mytable').find('input[type="checkbox"]:checked').each(function () {
var tr = $(this).closest('tr'),
filename = tr.find('[name="filename"]').val();
// [...]
});
Once you get the checkbox (inside the loop), then you need to get the row for that checkbox, eg:
$("#thechecked").click(function(){
var send_list = []
$('#mytable :checkbox:checked').each(function () {
var row = $(this).closest("tr");
var value = row.find("#presetChoosen").val();
var filename = row.find("#filename").text();
var dict = {};
dict['filename'] = filename
dict['value'] = value
send_list.push(dict)
});
console.log(send_list)
});
bit hard to be 100% without your HTML (in the question) and it looks like you have elements with the same id, eg id='presetChoosen' on every row, which is advised against.
Like the accepted answer said, ids should be unique. What I would do is change filename and presetChoosen to classes instead, since they are a type of thing (class), not a particular thing (id). That way you could traverse the DOM in a more readable and easier to understand way:
$("#thechecked").click(function(){
var send_list = [];
$('#mytable').find(':checkbox:checked').each(function (index, checkbox) {
// Find the row this checkbox is in
var row = $(checkbox).closest('tr'),
value = row.find('.presetChoosen').val(),
filename = row.find('.filename').text();
send_list.push({
filename: filename,
value: value
});
});
console.log(send_list);
});
tr,td{border:1px solid black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
<thead>
<tr id="mq">
<td></td>
<td>What</td>
<td>Meta</td>
<td>Preset</td>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox" /></td>
<td class="filename" >Underthesea</td>
<td>1920x1080</td>
<td> <select class="presetChoosen">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="2">
<td><input type="checkbox" /></td>
<td class="filename" >Overthehill</td>
<td>1280x720</td>
<td> <select class="presetChoosen">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
<tr id="3">
<td><input type="checkbox" /></td>
<td class="filename" >Mocking</td>
<td>1280x720</td>
<td> <select class="presetChoosen">
<option value="Watch">Watch</option>
<option value="Delete">Delete</option>
<option value="None">None</option>
<option value="Other">Other</option>
</select></td>
</tr>
</tbody>
</table>
<button id="thechecked">Get Checked</button>

How to get a select element embedded in a table?

The code below shows a table with 2 rows and 3 columns.
A select list is in the last column of the first row.
I am able to get info from ID's: sn2 & car3( ID of one of the cars in the list).
This code is modified from w3schools:
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h3>A demonstration of how to access a TR element</h3>
<table>
<tr id="myRow1">
<td>First cell</td>
<td id ="rr2">Second cell</td>
<td id="car2">
<select id="carlist">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option id ="car3" value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</td>
</tr>
<tr id="myRow">
<td>First cell</td>
<td id = "sn2">XYZ999 </td>
<td>Third cell</td>
</tr>
</table>
<p>Click the button to delete the first cell from the table row.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
obj = document.getElementById("sn2");
alert( obj.lastChild.data );
obj = document.getElementById("car3");
alert( obj.lastChild.data );
}
</script>
</body>
</html>
I cannot get a value from the carlist of an item that is selected.
I created a JSfiddle that shows you how to get the selected value.
I comes down to this:
// Get the SelectElement
obj = document.getElementById("carlist");
// show the Selected Value
alert(obj.value);
To get the value of the selected item in the carlist use:
document.getElementById('carlist').value;
It is .value, not .data for the form elements, .innerHTML or textContent for table cells
It is not common practice to put ID on options. The selected value is exposed as document.getElementById("idOfYourSelect").value in your case
document.getElementById("carlist").value
To get the text of a selected option, the most compatible version in plain JS is var sel = document.getElementById("carlist"), opt=sel.options[sel.selectedIndex].text; as you yourself found.
In jQuery you can use $("#carlist option:selected").text(); and a somewhat longer and unintuitive alternative in JS is
document.getElementsByTagName("select")[0].querySelectorAll("option:checked")[0].text
window.onload=function() {
document.getElementById("bt1").onclick=function() {
var sel = document.getElementById("carlist"),
optText=sel.options[sel.selectedIndex].text,
optValue=sel.options[sel.selectedIndex].value;
alert(optText+":"+optValue);
}
document.getElementById("bt2").onclick=function() {
alert(document.getElementById("sn2").innerHTML);
}
}
table, th, td {
border: 1px solid black;
}
<h3>A demonstration of how to access a TR element</h3>
<table>
<tr id="myRow1">
<td>First cell</td>
<td id="rr2">Second cell</td>
<td id="car2">
<select id="carlist">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</td>
</tr>
<tr id="myRow">
<td>First cell</td>
<td id="sn2">XYZ999</td>
<td>Third cell</td>
</tr>
</table><hr/>
<button id="bt1">Selected option of row 1, cell 3</button>
<button id="bt2">Content of second row second cell</button><br/>
Change your code from
obj = document.getElementById("car3");
alert( obj.lastChild.data );
to
obj = document.getElementById("car3");
alert( obj.value );

jquery find function not working

I have html with 2
<select> ... </select>
elements inside a span with class spanClass. Now i am trying to select those selects with jQuery with this code:
jQuery(document).ready(function() {
spans = jQuery('.spanClass');
spans.each(function() {
var inputs = jQuery(this).find('select');
console.log(inputs);// This is working
inputs.each(function() {
alert('test'); //This not
});
});
});
HTML:
<table>
<tr>
<td>
<select name="een">
<option> test </option>
</select>
</td>
</tr>
<select name="twee">
<option> test </option>
</select>
</td>
</tr>
</table>
However, this is not working, can anybody tell me why?
First> Put Table inside Div instead of Span (it's the correct way to do this)
Second> Correct your table tags as the following image and codes (some of them are incorrect!)
Now> Use these codes
HTML:
<div class="divClass">
<table>
<tr>
<td>
<select name="een">
<option> test </option>
</select>
</td>
</tr>
<tr>
<td>
<select name="twee">
<option> test </option>
</select>
</td>
</tr>
</table>
</div>
jQuery:
jQuery(document).ready(function() {
spans = jQuery('.divClass');
spans.each(function() {
var inputs = jQuery(this).find('select');
console.log(inputs);
inputs.each(function() {
console.log(jQuery(this).prop("name"));
});
});
});
Result:
var inputs = jQuery(this).find('select'); // Isn't inputs empty jQueryObject? length 0?
if inputs is empty jQueryObject, the callback function passed by .each() is never called.

Add disabled to form option that are on the table list

I have a table and a form with a dropdown:
<table>
<tr>
<td class="text">Apple</td>
<td class="name">John</td>
</tr>
<tr>
<td class="text">Orange</td>
<td class="name">Smith</td>
</tr>
</table>
<form>
<select>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Orange">Orange</option>
<option value="Grape">Grape</option>
</select>
</form>
and I want to add a disabled attribute to every option on the dropdown that is already on the table resulting in this:
<table>
<tr>
<td class="text">Apple</td>
<td class="name">John</td>
</tr>
<tr>
<td class="text">Orange</td>
<td class="name">Smith</td>
</tr>
</table>
<form>
<select>
<option value="Apple" disabled>Apple</option>
<option value="Banana">Banana</option>
<option value="Orange" disabled>Orange</option>
<option value="Grape">Grape</option>
</select>
</form>
Is there any way to achieve using jQuery?
$("td.text").text(function(i, txt) {
$("select option[value='" + $.trim(txt) + "']").prop("disabled", true);
});
DEMO: http://jsfiddle.net/322PA/
Get each item value from the select option and compare it with the data inside table row. If both matches then disable the data/option in dropdownlist/select element.
$(document).ready(function(){
//loop through the select option
$("form > select").children().each(function(){
//store each option to check later
var item = $(this).val();
//loop through table row
$("table").children().each(function(){
//loop through table data
$("tr").children().each(function(){
//compare previously stored item with table data value
if(item == $(this).text()){
//disable option
$("form > select > option:contains(" + item + ")").attr("disabled", "disabled");
}
});
});
});
});
jsFiddle Demo
I am guessing you will be dynamically changing the content of the table and want the select element to update when the table changes. You must therefore make sure it updates each time it's used.
$("#theSelector").bind("mouseenter", disableOptions);
function disableOptions() {
var tableData = [];
$("#theTable tr").each(function() {
tableData.push($(this).children(":first").text());
});
$("#theSelector option").each(
function() {
if(jQuery.inArray(this.text, tableData) > -1) {
$(this).prop('disabled', true);
}
}
);
}

How to get the data from a row jQuery

I have this problem about retrieving row data in jQuery. this is not really a simple problem for me since my table cells contains a select tag, and a input box. To be clear enough, here's my html code of my table:
<tr>
<td>
<select style="width:5em;" class="field">
<option></option>
<option>name</option>
<option>age</option>
<option>sex</option>
</select>
</td>
<td>
<select style="width:5em;" class = "comp">
<option></option>
<option>equals</option>
<option>starts with</option>
<option>not equal to</option>
</select>
</td>
<td><input type="text" class = 'value'></td>
</tr>
<tr>
<td>
<select style="width:5em;" class="field">
<option></option>
<option>name</option>
<option>age</option>
<option>sex</option>
</select>
</td>
<td>
<select style="width:5em;" class = "comp">
<option></option>
<option>equals</option>
<option>starts with</option>
<option>not equal to</option>
</select>
</td>
<td><input type="text" class = 'value'></td>
</tr>
<tr>
<td>
<select style="width:5em;" class="field">
<option></option>
<option>name</option>
<option>age</option>
<option>sex</option>
</select>
</td>
<td>
<select style="width:5em;" class = "comp">
<option></option>
<option>equals</option>
<option>starts with</option>
<option>not equal to</option>
</select>
</td>
<td><input type="text" class = 'value'></td>
</tr>
</table>
<input type="button" value = "go" id="out">
Here's my Javascript code:
$('#out').click(function(){
var tr = 1;
$('table tr').each(function(){
var td = 1;
$(this).find('td').each(function(){
alert(JSON.stringify($(this).text()));
td++;
});
tr++;
});
})
What I am trying to do is that i want to get all the row data in the table, but everytime I click the button, it won't display the correct output.
I also tried this:
$(this).children($(".field option:selected").text())
to get the value of selected option, but it still no good.
DEMO here. Please help....
Does this help you?
http://jsfiddle.net/KzXjb/3/
$('#out').click(function(){
var data = new Array();
$("table select, table input").each(function(){
data.push($(this).val());
});
alert(data.toString());
})
Here is what I think you meant
http://jsfiddle.net/mplungjan/8xFFH/12/
$('#out').click(function(){
var tr = 1;
$('table tr').each(function(){
var td = 1;
$(this).find('td').each(function(){
var fld = $(this).find('select, input');
alert(fld.val());
td++;
});
tr++;
});
})
You can try something like this :
$('#out').click(function(){
$('table tr').each(function(){
var td = '';
$(this).find('option:selected').each(function(){
td = td + ' ' + $(this).text();
});
td = td + ' ' + $(this).find('input').val();
alert(td);
});
})
If i correctly understand what you need ^^

Categories