I have the table with following structure . I am generating a dynamic table on the basis of input provided by user which will repeat this row .
I want to get the value of this text box and trying to use the code below
if (row.getAttribute('val') === 'answer') {
var Cell = table.rows[i].cells[0];
alert(Cell.innerHTML);
}
<tr val='answer'>
<td>
<input type='checkbox' />
<input style='width:483px' type='text' />
</td>
</tr>
I am putting alert to check if i am getting the correct value .I can see the two inputs in the alert message I want to get the value of text box using javascript not jquery
You can use querySelectorAll to select all rows and then use loop to get only rows with val='answer' and then use querySelector to get input with type="text"
var rows = document.querySelectorAll('tr');
for (var i = 0; i < rows.length; i++) {
if (rows[i].getAttribute('val') == 'answer') {
var input = rows[i].querySelector('input[type="text"]');
console.log(input.value);
}
}
<table>
<tr val='answer'>
<td>
<input type='checkbox' />
<input value="Some value" style='width:483px' type='text' />
</td>
</tr>
</table>
Related
I need to get the input value if the radio beside it is checked. The Inputs and radios are in a table.
store all possible options inside an options array
$('#table tr').each(function(index) {
console.log("index" + index);
if ($(this).has("input:radio")) {
$(this).find('input:text').each(function() {
options.push($(this).val());
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
<tr class="cell">
<td>
<input type="radio">
<input type="text">
</td>
</tr>
</table>
get the correct answers with a combination of the two indexes (index and i)
To get the value of the text input next to the clicked radio input, you could listen for the change event:
$('input[type="radio"]').on('change', function() {...});
In the attached event handler you could get the index of the associated table row with the parents() function, which accepts a selector:
const cell_index = $(this).parents('tr').index();
and get the value of the desired text input with the siblings() function, which also accepts a selector:
const text_value = $(this).siblings('input[type="text"]').val();
Then you can store the value in your options array with the index as key:
options[cell_index] = text_value;
and get the right answer with the array data...
Working example:
let options = [];
$('input[type="radio"]').on('change', function() {
const cell_index = $(this).parents('tr').index();
const text_value = $(this).siblings('input[type="text"]').val();
options[cell_index] = text_value;
console.log('index: ' + cell_index + ' / value: ' + options[cell_index]);
//your code to get the right answer from the array
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
<tr class="cell">
<td>
<input type="radio" name="answer">
<input type="text" value="Miau">
</td>
</tr>
<tr class="cell">
<td>
<input type="radio" name="answer">
<input type="text" value="Bark">
</td>
</tr>
</table>
I made a listener to attatch an id "selectedRow" to the row a user has clicked on. The intent from there is be able to manipulate the data in that row; Previously i was using content editable however I'm trying to make it more obvious to the user that they are editing a row (this is for a project) so i've created an editing panel to do so. I've however ran in to some problems with a lot of data being returned as undefined when using .innerHTML when sending the TD to the input boxes.
I've tried using .HTML instead
$('tr').click(function() {
if(document.getElementById("SELECTEDROW")) {
var oldRow = document.getElementById("SELECTEDROW");
oldRow.classList.remove("selected");
$("#SELECTEDROW").removeAttr('id');
}
$(this).attr('id', 'SELECTEDROW');
selectedRow = document.getElementById("SELECTEDROW");
table = selectedRow.parentNode;
console.log("Row " + selectedRow.childNodes[1].innerHTML + " Selected");
selectedRow.classList.add("selected");
editRow();
});
function editRow() {
var currentTD = selectedRow.childNodes;
var inputs = document.getElementById("inputs").childNodes;
var i = 0;
for (i = 0; i < currentTD.length; i++) {
inputs[i].innerHTML = currentTD.html;
}
console.log('Now Editing:' + currentTD[1].innerHTML);
document.getElementById("editingPanel").style.display = "block";
document.getElementById("content").style.height = "49%";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Role</th>
<th>Address</th>
<th>Phone</th>
<th>Email</th>
<th>Password</th>
</tr>
<tr>
<td>1</td>
<td>Bill Robbins</td>
<td>Conductor</td>
<td>12, Caldrow Ave, Plymouth, Pl21XE</td>
<td>01921202384</td>
<td>XxbillyboyxX#bossman.com</td>
<td>CaTsRbAe1967</td>
</tr>
<tr>
<td>2</td>
<td>Kat Robbins</td>
<td>Admin</td>
<td>12, Caldrow Ave, Plymouth, Pl21XE</td>
<td>019232042454</td>
<td>katrobs#gmail.com</td>
<td>thR33mel0ns</td>
</tr>
</table>
</div>
<div id="editingPanel">
<div id="inputFields">
<form id="inputs">
<input id="input1" type="text" name=""/>
<input id="input2" type="text" name="">
<input id="input3" type="text" name="">
<input id="input4" type="text" name="">
<input id="input5" type="text" name="">
<input id="input6" type="text" name="">
<input id="input7" type="text" name="">
<input id="input8" type="text" name="">
</form>
</div>
<div id="editButtons">
<button onclick="addRow()">New Row</button>
<button onclick="editRow()">Save Row</button>
<button onclick="removeRow()">Delete Row</button>
</div>
</div>
The expected output would be for each td's text to be copied into the input boxes.
You need to get the children properly. You also need to assign the text to the value property of the input, not its innerHTML
function editRow() {
// You need to get elements by tag name, not childNodes
var currentTD = selectedRow.getElementsByTagName("td");
// You need to get elements by tag name, not childNodes
var inputs = document.getElementById("inputs").getElementsByTagName("input");
var i = 0;
for (i = 0; i < currentTD.length; i++) {
console.log(inputs[i]);
console.log(currentTD[i]);
// set the "Value" of an input box, not its "innerHTML"
// also you need to apply the [i] to the currentTD because it is a list
inputs[i].value = currentTD[i].innerHTML;
}
You can try this:
$("body").on("click","tr",function(){ //Just in case you are going to use dynamic content, because the click method doesn't work on dynamically created/added elements
for(let i=0;i<7;i++){
$("#input"+(i+1)).val($(this).children()[i].innerHTML); //You are using jQuery for a reason, to simplify code, so avoid using unnecessary JS where you can by using simplified jQuery
}
});
How can I iterate over the following HTML using Javascript in order to add a 1 to all the name fields. For example, "account" would become "account1", etc. I cloned this row from a table, and would like to be able to distinguish between the fields of the two.
<td>
<select name="account">…</select>
</td>
<td>
<span>
"$ "<input type="text" name="debit" placeholder="100">
</span>
</td>
<td>
<span>
"$ "<input type="text" name="credit" placeholder="100">
</span>
</td>
<td>
<input type="text" name="reference">
</td>
<td>
<input type="text" name="notes">
</td>
<td>
<select name="account">...</select>
</td>
One way you can do this is use querySelectorAll to get your elements inside your table, then use a loop and change their names:
var inputs = document.querySelectorAll("#myTable [name]")
inputs.forEach(function(input){
input.name += + "1";
});
JSFiddle Demo
var all =document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++){
if(all[i].name){
all[i].name+=1;
}
}
Try this.* will give you all elements in the page.
my table looks like this.
<body>
<table class="tblTest">
<tr>
<td>
<label>wer</label></td>
<td>
<label>ur4</label></td>
<td>
<label>ksdj</label></td>
</tr>
<tr>
<td>
<label>eiejr</label></td>
<td>
<label>ur4</label></td>
<td>
<label>yutu56</label></td>
</tr>
<tr>
<td>
<input type="text" /></td>
<td>
<input type="text" /></td>
<td>
<input type="text" />
</td>
</tr>
<tr>
<td>
<label>jweee</label>
</td>
<td>
<label>male</label>
</td>
<td>
<label>ur4</label>
</td>
</tr>
<tr>
<td>
<label>ssssss</label>
</td>
<td>
<label>male</label>
</td>
<td>
<label>ur4s</label></td>
</tr>
<tr>
<td>
<input type="text" /></td>
<td>
<input type="radio" name="gender" value="male" />Male
<br />
<input type="radio" name="gender" value="female" />Female
</td>
<td>
<select name="cars" style="width: 128px">
<option selected="selected" value="Select">Select</option>
<option value="saab">BMW</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</td>
</tr>
</table> <br />
<button type="button" onclick="function1()">Submit</button>
I want a Java script/jQuery which will check the two labels and if there is a mismatch then it will make the Text Box Red and if not then green. I can't use getElementById for the labels only I have to traverse through it and get the td index and do the task. I Don't know how to get prev and closest elements. Please help me with this.
The function which I'm trying is
function function1() {
var inputcontrols = document.getElementsByTagName('input');
for (var i = 0; i < inputcontrols.length; ++i)
{
var element = inputcontrols[i];
//element.style.background = "#90EE90"; by default making it green
var ind = $(this).closest('td').prev('td').text();
alert(ind);
}
Trying to get the td text in "ind", but its returning empty.
First get all the inputs, and use the each loop to iterate these. And by using the index to get the appropriate label texts.
The reason text() did not work for you, is because you are trying to get the text from the td element. This is empty, because it only contains a HTMLElement label. Look at the jQuery specs to see the difference between text() and html()
function function1() {
$('table').each(function(n, table) {
$(table).find('tr').each(function(n, tr) {
tr = $(tr);
var td = undefined;
var c = 0;
tr.find('input,select').each(function(i, input) {
if(!td || !td.is($(input).closest('td'))) {
td = $(input).closest('td');
c++;
}
var lbl1 = $(tr.prev().prev().find('td')[c]).find('label').text();
var lbl2 = $(tr.prev().find('td')[c]).find('label').text();
if(lbl1 === lbl2) {
$(input).css('backgroundColor', 'green');
} else {
$(input).css('backgroundColor', 'red');
}
});
});
});
}
The first problem I see is that you're using $(this) which is what how you chain the function scope in jQuery. For example:
$('a').each(function() {
// 'this' scopes to the current 'a' element inside the 'each' loop
$(this).css('color', '#FF0000');
});
Since you've already found your input controls and stored them in var element you need to pass that element into jQuery so it knows what you're looking for.
var element = inputcontrols[i];
$(element).closest('td').prev('td').text();
Next, if you're trying to compare the text field to the previous label you need to fix your traversal steps to be:
From the text field
Find its parent tr not td (go up to the row)
Find its the previous tr (go back a row)
Find its child label (drill down into the previous row)
Get the text from the label
assuming that you only have two table rows, you can try this-
function function1() {
var inputs = $('.tblTest input');
var tr1 = $('.tblTest tr:nth(0)');
var tr2 = $('.tblTest tr:nth(1)');
for (var i = 0; i < inputs.length; ++i)
{
var element = inputcontrols[i];
if(tr1.find('td:nth('+ i +') label').html().trim() == tr2.find('td:nth('+ i +') label').html().trim()) {
element.style.background = "green";
}
else {
element.style.background = "red";
}
}
}
<table id="tableID">
<tr>
<th>Attr</th>
<th>Val</th>
</tr>
<td>
<input type="checkbox" name="firstChk" />
</td>
<td>
<input type="text" name="firstAttr" />
</td>
<td>
<input type="text" name="firstVal" />
</td>
</table>
<input type="button" value="Add A Row" onclick="javascript: addARow('tableID')" />
<input type="button" value="Delete" onclick="javascript: deleteARow('tableID')" />
This separate js file gets called:
function deleteARow(tID) {
try {
var tableObj = document.getElementById(tID);
var numRows = tableObj.rows.length;
// starts at 1 because never delete row that holds table headers
for(var index=1; index < numRows; index++) {
var rowObj = tableObj.rows[index];
// rowObj.cells[0] gives the td, then childNodes[0] gives checkbox element
var chkboxObj = rowObj.cells[0].childNodes[0];
if(null != chkboxObj && true == chkboxObj.checked) {
tableObj.deleteRow(index);
/* next 2 lines are necessary because DOM's tr indices shift back
* with a deletion
*/
numRows--;
index--;
}
} // end for
} // end try
catch(e) {
alert(e);
}
} // end function
This code can delete any row and any number of rows after clicking the "Delete" button EXCEPT for the first row that has a checkbox(the one whose xpath is //table/tr[1]). I've traced through the code by hand multple times and have been unable to debug it, so I've posted the code with my comments.
What's wrong with the code? I wish I could figure out how to use the js debugger in firebug :(
There were a few issues with your code.
First, the markup for your table was malformed. You have td's without parent tr's.
Second, the logic that you used to get the checkbox object was not returning the checkbox. So, when you hit your if statement, chkboxObj.checked returned undefined.
Here's the updated/working code:
HTML
<table id="tableID">
<tr>
<th>Attr</th>
<th>Val</th>
</tr>
<tr>
<td>
<input type="checkbox" name="firstChk" />
</td>
<td>
<input type="text" name="firstAttr" />
</td>
<td>
<input type="text" name="firstVal" />
</td>
</tr>
</table>
<input type="button" value="Add A Row" onclick="addARow('tableID')" />
<input type="button" value="Delete" onclick="deleteARow('tableID')" />
JavaScript
function deleteARow(tID) {
try {
var tableObj = document.getElementById(tID);
var numRows = tableObj.rows.length;
// starts at 1 because never delete row that holds table headers
for (var index = 1; index < numRows; index++) {
var rowObj = tableObj.rows[index];
// rowObj.cells[0] gives the td, then childNodes[0] gives checkbox element
// This was not returning the checkbox element. See updated code:
// Get first input in row - this will be the checkbox
var chkboxObj = rowObj.cells[0].getElementsByTagName("input")[0];
if (chkboxObj != null && chkboxObj.checked == true) {
tableObj.deleteRow(index);
/* next 2 lines are necessary because DOM's tr indices shift back
* with a deletion
*/
numRows--;
index--;
}
} // end for
} // end try
catch (e) {
alert(e);
}
} // end function
Also, here's a working fiddle.