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 );
Related
I want to implement the copy and paste feature in my web page.
I would like to use document.execcommand("copy") to implement the feature,so that user can use Ctrl-Z to roll back the copy action.
The following code working prorperly in firefox browser, it can add more than 1 range to window.selection object.
However, it can add only 1 range to window.selection in Chrome browser.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Copy event to clipboard</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$( document ).ready(function() {
$("body").on("copy",copy);
});
function copy(event)
{
var cell1,cell2;
var endCol=getValue("endCol");
var endRow=getValue("endRow");
var range;
var startCol=getValue("startCol"),startRow=getValue("startRow");
var selection = window.getSelection();
selection.removeAllRanges();
for (var i=startRow;i<=endRow;i++)
{
range = document.createRange();
cell1=getCell(i,startCol);
cell2=getCell(i,endCol);
range.setStart(cell1,0);
range.setEnd(cell2,cell2.childNodes.length);
selection.addRange(range);
}
}
function copyContent()
{
document.execCommand("copy");
}
function getCell(rowIndex,cellIndex)
{
var table=document.getElementById("dataTable");
var row=table.rows[rowIndex];
var cell=row.cells[cellIndex];
return cell;
}
function getValue(id)
{
var element=document.getElementById(id);
var index=element.selectedIndex;
return element.options[index].value;
}
</script>
</head>
<body>
<table border="1" id="dataTable">
<tr>
<td id="c11" contenteditable="true">1_1</td>
<td id="c12" contenteditable="true">1_2</td>
<td id="c13" contenteditable="true">1_3</td>
</tr>
<tr>
<td id="c21" contenteditable="true">2_1</td>
<td id="c22" contenteditable="true">2_2</td>
<td id="c23" contenteditable="true">2_3</td>
</tr>
<tr>
<td id="c31" contenteditable="true">3_1</td>
<td id="c32" contenteditable="true">3_2</td>
<td id="c33" contenteditable="true">3_3</td>
</tr>
</table><br>
start column:
<select id="startCol">
<option value=0>1</option>
<option value=1>2</option>
<option value=2>3</option>
</select>
end column:
<select id="endCol">
<option value=0>1</option>
<option value=1>2</option>
<option value=2>3</option>
</select>
<br>
start row:
<select id="startRow">
<option value=0>1</option>
<option value=1>2</option>
<option value=2>3</option>
</select>
end row:
<select id="endRow">
<option value=0>1</option>
<option value=1>2</option>
<option value=2>3</option>
</select>
<br>
<button onclick="copyContent()">Copy</button>
<textarea id=copiedContent>
</textarea>
</body>
</html>
Is there any work around so that I can add more than 1 range to window.selection object in Chrome browser?
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>
I am trying to validate the DONM using jquery Please look into the fiddle.
My objective is not to select the same country to same room number .
I have two scenarions
scenario 1 (before saving into DB)
The example is working fine
scenario 2 (After saving the data into db )
saved data coming from DB
Available Country RooNumber SelectedPerson
droipdown1 1
dropdown2 2 chennai
WRONG SELECTION
Available Country RooNumber SelectedPerson
chennai 1 chennai
chennai 2 chennai
JSFiddle:
http://jsfiddle.net/bharatgillala/9o1gxa1h/10/
code:
<table id="gridviewInfo" runatr="server">
<TBODY><TR>
<TH scope=col>Available Country</TH>
<TH scope=col>RooNumber</TH>
<TH scope=col>Selected</TH>
</TR>
<OPTION selected value=>
</OPTION>
<OPTION value=maxico>maxico
</OPTION> <OPTION value=chennai>chennai</OPTION> <OPTION value=newdelhi>newdelhi</OPTION> <OPTION value=hongkong>hongkong</OPTION></SELECT> </TD>
<TD style="WIDTH: 100px">1</TD>
<td>
<label id='lbl2'> maxico </label>
</td>
</TR>
<TR>
<TD style="WHITE-SPACE: nowrap" align=left>
<SELECT class="judges" id='ddlAvailableJudges2' name=ctl00$contentBody$gvwRoomInformation$ctl03$ddlAvailableJudges>
<OPTION selected value=>
</OPTION>
<OPTION value=maxico>maxico</OPTION> <OPTION value=chennai>chennai</OPTION> <OPTION value=newdelhi>newdelhi</OPTION> <OPTION value=hongkong>hongkong</OPTION></SELECT> </TD>
2
<td>
<label id='lbl2'>chennai</label>
</td>
</tr>
</table>
First of all, you're creating n label tags with the id lbl2.
This is happening, because you're developing with ASP.NET and you didn't create your label with the runat=server attribute, so it won't generate different label IDs for each label created.
Second, your code was too ugly / verbose, so I decided to make a complete new code to achieve what you want, and the snippet is below, full commented:
(function(d) {
// when all the DOMElements are already loaded into the document
d.addEventListener('DOMContentLoaded', function() {
// gets the generated table, and get all the dropdownlists inside it
var table = document.getElementById('gridviewInfo'),
ddls = [].slice.call(table.querySelectorAll('select'));
// loop through the dropdownlists
ddls.forEach(function(ddl, i) {
// get the label inside the last td
var lbl = ddl.parentNode.parentNode.lastElementChild.firstElementChild;
// initially, we want to change the dropdownlist selectedvalue to the label text
ddl.value = lbl.textContent.trim();
// then, we must disable this option in all the other dropdownlists
updateDisabled(ddl);
// so, we add a change event handler
ddl.addEventListener('change', function(e) {
// when the ddl value is changed, we update the label text
lbl.textContent = ddl.value;
// and we disable the option selected in all the other dropdownlists
updateDisabled(ddl);
});
});
function updateDisabled(ddl) {
// to disable all the other dropdownlists
// we loop through all the HTMLOptionElements inside the table
[].forEach.call(table.querySelectorAll('option'), function (opt, j) {
// we look if the current option inside the loop is not the selected one
if (opt.parentNode !== ddl) {
// then, if the option has the same selected value, we disable it, else we enable
opt.disabled = opt.value && opt.value === ddl.value;
}
});
}
});
})(document);
#gridviewInfo td:nth-child(1) {
white-space: nowrap;
text-align: left;
}
<table id="gridviewInfo" runatr="server">
<thead>
<tr>
<th>Available Person</th>
<th>RooNumber</th>
<th>SelectedPerson</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="judges" id="ddlAvailableJudges1" name=ctl00$contentBody$gvwRoomInformation$ctl02$ddlAvailableJudges>
<option selected value=''></option>
<option value="maxico">maxico</option>
<option value="chennai">chennai</option>
<option value="newdelhi">newdelhi</option>
<option value="hongkong">hongkong</option>
</select>
</td>
<td>1</td>
<td>
<label>maxico</label>
</td>
</tr>
<tr>
<td>
<select class="judges" id="ddlAvailableJudges2" name=ctl00$contentBody$gvwRoomInformation$ctl03$ddlAvailableJudges>
<option selected value=''></option>
<option value="maxico">maxico</option>
<option value="chennai">chennai</option>
<option value="newdelhi">newdelhi</option>
<option value="hongkong">hongkong</option>
</select>
</td>
<td>2</td>
<td>
<label>hongkong</label>
</td>
</tr>
</tbody>
</table>
Update
Since the OP asked, I've created a fiddle for him: http://jsfiddle.net/h1b6e8zm/
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.
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