Getting Relative Values in Each Loop jQuery - javascript

I'm having an issue pulling the relative values in .each() loop in jQuery. I have a series of table rows that have an text input and a radio button next to them. I want to loop through each row, and if the radio button is selected, save the value for the text input.
However, so far whenever I run my loop, it seems to recognize that one of the radio values is selected, and then it automatically saves the first input, regardless of which row. I thought that by running through each row, the code would only be executed in that particular rows HTML -- I believe it's touching all the rows instead. Can anyone help?
Here's my jQuery:
$('#valueTable tbody tr').each( function() {
//$(this).css('background', 'blue');
if($('td input[name=DefaultVal]:checked').size() > 0){
$('td input[name=DefaultVal]:checked').parent().css('background', 'red')
selectedDefVal = $('td:first-child input[name=valueTextField]').val();
//alert(selectedDefVal)
} else {
alert('not checked')
}
});
Here's my HTML:
<table border="0" id="valueTable">
<tr>
<td width="70%" style="white-space: nowrap;"><input size="80" type="text" name="valueTextField" placeholder="Enter Value" value="" ></td>
<td width="70%" class="default_container">Default
<input type="radio" name="DefaultVal" checked="true" class="defaultValFind" />
</td>
</tr>
<tr>
<td width="70%" style="white-space: nowrap;"><input size="80" type="text" name="valueTextField" placeholder="Enter Value" value="2" ></td>
<td width="70%" class="default_container">Default
<input type="radio" name="DefaultVal" class="defaultValFind" />
</td>
</tr>
<tr>
<td width="70%" style="white-space: nowrap;"><input size="80" type="text" name="valueTextField" placeholder="Enter Value" value="fffffff" ></td>
<td width="70%" class="default_container">Default
<input type="radio" name="DefaultVal" class="defaultValFind" />
</td>
</tr>
</table>

You need to use something like $(this):
$('#valueTable tbody tr').each(function() {
if($(this).find('td input[name=DefaultVal]:checked').length){
$(this).find('td input[name=DefaultVal]:checked').parent().css('background', 'red');
selectedDefVal = $(this).find('td:first-child input[name=valueTextField]').val();
} else {
alert('not checked')
}
});

$('#valueTable tbody tr').each( function() {
//$(this).css('background', 'blue');
if($('td input[name=DefaultVal]:checked', this).size() > 0){
$('td input[name=DefaultVal]:checked', this).parent().css('background', 'red')
selectedDefVal = $('td:first-child input[name=valueTextField]', this).val();
//alert(selectedDefVal)
} else {
alert('not checked')
}
});
I thinks when using $ to select children elments, you forget to specify the parent scope. if omitted, it will be window by default. In this .each case, this will point to the tr element in every loop.

Related

Getting next element in a table javascript

https://jsfiddle.net/en6jh7pa/1/
I am having issues grabbing the next element, it is returning null for the next element.
I am passing "this? as onclick and I assumed that you could use this to grab the next element but it seems that it instead returns null
Thanks for your help
function assignnames(checkboxelement){
checkboxelement.setAttribute("name", "checkbox");
var value1box = checkboxelement.nextSibling;
value1box.setAttribute("name", "notnull");
var value2box = checkboxelement.nextElementSibling;
value2box.setAttribute("name", "notnull");
alert("done");
}
<table border="1">
<tr>
<th>
Checkbox
</th>
<th>
value1
</th>
<th>
value2
</th>
</tr>
<tr>
<td>
<input type="checkbox" onclick="assignnames(this)" id="checkbox1"/>
</td>
<td>
<input type="text" name="" id="fname1">
</td>
<td>
<input type="text" name="" id="lname1">
</td>
</tr>
</table>
If you want to get the text inputs in the same row, you can go up to the row, then use a selector to get the inputs, e.g.
function getParent(node, tag) {
var tag = tag.toLowerCase();
do {
if (node.tagName.toLowerCase() == tag) {
return node;
}
node = node.parentNode;
} while (node && node.tagName && node.parentNode)
return null;
}
function getInputs(evt) {
var row = getParent(this, 'tr');
var inputs;
if (row) {
inputs = row.querySelectorAll('input[type="text"]');
}
console.log(`Found ${inputs.length} text inputs, node is ${this.checked? '':'not '}checked.`);
}
window.onload = function(){
document.getElementById('checkbox1').addEventListener('click', getInputs, false);
};
<table border="1">
<tr><th>Checkbox
<th>value1
<th>value2
<tr><td><input type="checkbox" id="checkbox1">
<td><input type="text" name="" id="fname1">
<td><input type="text" name="" id="lname1">
</table>
For the inputs to be siblings, they would all have to be within the same <td>, sharing a singular parent. With them spread out across multiple table cells, they would be considered cousins instead (keeping with the family tree metaphor), which doesn't have a similar shortcut property.
You can still use nextElementSibling along the way between inputs, but you'll also have to move up and back down between generations.
function assignnames(checkboxelement){
checkboxelement.setAttribute("name", "checkbox");
var value1box = checkboxelement
.parentElement // up a generation the checkbox' parent <td>
.nextElementSibling // then to the next <td> in the row
.firstElementChild; // and back down a generation to the next input
// the last step could also be: .querySelector('input')
value1box.setAttribute("name", "notnull");
var value2box = value1box
.parentElement
.nextElementSibling
.firstElementChild;
value2box.setAttribute("name", "notnull");
alert("done");
}
<table border="1">
<tr>
<th>
Checkbox
</th>
<th>
value1
</th>
<th>
value2
</th>
</tr>
<tr>
<td>
<input type="checkbox" onclick="assignnames(this)" id="checkbox1"/>
</td>
<td>
<input type="text" name="" id="fname1">
</td>
<td>
<input type="text" name="" id="lname1">
</td>
</tr>
</table>

Finding the next td element using j query?

How can i find the next td element using jquery.
I am trying to append a text or a div to the td element inside a particular tr.
my tr is a server side control with tag runat=server
here is my query it is not working
var cssdisable= function testcss(rowid) {
if ($('#testcss').width() != 3) {
var id = $(rowid).find('td');
id.append('The following is not valid');
}
}
this is how i am calling the function with in a click event
cssdisable('<%=tr_myrow.ClientID %>');
It doesn't does anything, neither gives any error. i am trying to add a text after the td elemnent next to the row id passed.
Any ideas
here is the HTML
there is a row named tr_myrow
<table id="tblstudysub_animal" class="bond_qbs_table" width="100%">
<tr>
<td valign="top">
<h3>
Select the study subject.<span class="red">*</span></h3>
<fieldset>
<legend class="hide">Select the study subject.</legend>
<table id="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_studysubj" border="0">
<tr>
<td><input id="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_studysubj_0" type="radio" name="ctl00$m$g_c09fd465_0ae4_479b_8fc6_21a7de645003$ctl00$rdb_studysubj" value="Humans" /><label for="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_studysubj_0">Humans</label></td>
</tr><tr>
<td><input id="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_studysubj_1" type="radio" name="ctl00$m$g_c09fd465_0ae4_479b_8fc6_21a7de645003$ctl00$rdb_studysubj" value="Non-Human primates" /><label for="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_studysubj_1">Non-Human primates</label></td>
</tr><tr>
<td><input id="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_studysubj_2" type="radio" name="ctl00$m$g_c09fd465_0ae4_479b_8fc6_21a7de645003$ctl00$rdb_studysubj" value="Rodents" /><label for="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_studysubj_2">Rodents</label></td>
</tr><tr>
<td><input id="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_studysubj_3" type="radio" name="ctl00$m$g_c09fd465_0ae4_479b_8fc6_21a7de645003$ctl00$rdb_studysubj" value="Others" /><label for="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_studysubj_3">Others</label></td>
</tr>
</table>
</fieldset>
</td>
</tr>
<tr id="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_tr_myrow">
<td valign="top">
<div id="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_studysub_popul">
<h3>
Select your study subject.<span class="red">*</span></h3>
<fieldset>
<legend class="hide">Select your study subject.</legend>
<table id="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_study_popul" border="0">
<tr>
<td><input id="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_study_popul_0" type="radio" name="ctl00$m$g_c09fd465_0ae4_479b_8fc6_21a7de645003$ctl00$rdb_study_popul" value="Individuals" /><label for="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_study_popul_0">Individuals</label></td>
</tr><tr>
<td><input id="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_study_popul_1" type="radio" name="ctl00$m$g_c09fd465_0ae4_479b_8fc6_21a7de645003$ctl00$rdb_study_popul" value="Population" /><label for="ctl00_m_g_c09fd465_0ae4_479b_8fc6_21a7de645003_ctl00_rdb_study_popul_1">Population</label></td>
</tr>
</table>
<div id="testcss">
</div>
I ma trying to add that text to the td in that row...
i hope this makes more clear...
One issue is that you are trying to query for the td by its id but are not using the # at the start of the selector..
try cssdisable('#<%=tr_myrow.ClientID %>');
Also in order to stick to just the td child of the tr use .children() instead of .find('td') (which will find all descendant td elements)
so
var cssdisable = function testcss(rowid) {
if ($('#testcss').width() != 3) {
var id = $(rowid).children().first();
id.append('The following is not valid');
}
}
Demo at http://jsfiddle.net/D4z9b/ (using your example HTML)
Give your <td>..</td> elements meaningful ids during the table build phase (if you don't build it, just assign them before starting any processing using a separate call) and then generate the id. Something like tableName + '_' + row + '_' will probably should do you fine.

jquery / javascript to sum field only if checkbox on same row is checked

I have a jquery / javascript function that totals the number of cubes in my order. this works 100% and is below.
function calculateTotalVolume() {
var grandTotalCubes = 0;
$("table.authors-list").find('input[name^="cubicvolume"]').each(function () {
grandTotalCubes += +$(this).val();
});
$("#grandtotalcubes").text(grandTotalCubes.toFixed(2));
}
as mentioned the above works great. I need a second function to total the same field but only if an checkbox named treated is checked. each row has the checkbox named treated but as the table is dynamically generated, a counter is appended to the name each time hence my use of name^="treated"
I am after something like below but this doesn't work:
function calculateTotalTreatedVolume() {
var grandTotaltreatedCubes = 0;
$("table.authors-list").find('input[name^="cubicvolume"]').each(function () {
if($("table.authors-list").find('checkbox[name^="treated"]').checked){
alert('10');
grandTotaltreatedCubes += +$(this).val();
}
});
$("#grandtotaltreatedcubes").text(grandTotaltreatedCubes.toFixed(2));
}
help appreciated as always.
UPDATE
Rendered HTML output [1 dynamic row added]: (Still in development so very rough, please excuse it)
<table class="authors-list" border=1>
<thead>
<tr>
<td></td><td>Product</td><td>Price/Cube</td><td>Qty</td><td>line total cost</td><td>Discount</td><td>Cubes per bundle</td><td>pcs per bundle</td><td>cubic vol</td><td>Bundles</td><td><input type="checkbox" class="checkall"> Treated</td>
</tr>
</thead>
<tbody>
<tr>
<td><a class="deleteRow"> <img src="http://devryan.tekwani.co.za/application/assets/images/delete2.png" /></a></td>
<td><input type="text" id="product" name="product" />
<input type="hidden" id="price" name="price" readonly="readonly"/></td>
<td><input type="text" id="adjustedprice" name="adjustedprice" /></td>
<td><input type="text" id="qty" name="qty" /></td>
<td><input type="text" id="linetotal" name="linetotal" readonly="readonly"/></td>
<td><input type="text" id="discount" name="discount" /></td>
<td>
<input type="text" id="cubesperbundle" name="cubesperbundle" >
</td>
<td>
<input type="text" id="pcsperbundle" name="pcsperbundle" >
</td>
<td>
<input type="text" id="cubicvolume" name="cubicvolume" size='5' disabled>
</td>
<td><input type="text" id="totalbundles" name="totalbundles" size='5' disabled ></td>
<td valign="top" ><input type="checkbox" id="treated" name="treated" ></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="15"><input type="button" id="addrow" value="Add Product" /></td>
</tr>
<tr>
<td colspan="3">Grand Total: R<span id="grandtotal"></span></td>
<td colspan="2">Ave Discount: <span id="avediscount"></span>%</td>
<td colspan="1">Total Cubes: <span id="grandtotalcubes"></span></td>
<td colspan="15">Treated Cubes: <span id="grandtotaltreatedcubes"></span></td>
</tr>
<tr>
<td colspan="15"><textarea rows="1" cols="50" placeholder="Specific Comments"></textarea><textarea rows="1" cols="20" placeholder="Customer Reference"></textarea>
</td>
</tr>
</tfoot>
</table>
First go the parent tr and then using find to find the checkbox in current row and also use checked with DOM object not jQuery object, you can use indexer to convert jQuery object to DOM object.
Change
if($("table.authors-list").find('checkbox[name^="treated"]').checked){
To
if($(this).closest('tr').find('checkbox[name^="treated"]')[0].checked){
checked is a property of the actual DOM element, and what you have is a jQuery element. You need to change this:
$("table.authors-list").find('checkbox[name^="treated"]').checked
To this:
$("table.authors-list").find('checkbox[name^="treated"]')[0].checked
-^- // get DOM element
Or more jQuery-ish:
$("table.authors-list").find('checkbox[name^="treated"]').is(':checked')
You can iterate through the "checked" checkboxes using $("table.authors-list").find('checkbox[name^="treated"]:checked') and use the value of the input nearest to it (assumed to be in the same row).
Assuming your table has many rows each having a checkbox and an input, you can use:
function calculateTotalTreatedVolume() {
var grandTotaltreatedCubes = 0;
// iterate through the "checked" checkboxes
$("table.authors-list").find('input[type="checkbox"][name^="treated"]:checked').each(function () {
// use the value of the input in the same row
grandTotaltreatedCubes += +$(this).closest('tr').find('input[name^="cubicvolume"]').val();
});
$("#grandtotaltreatedcubes").text(grandTotaltreatedCubes.toFixed(2));
}
Try this:
var grandTotaltreatedCubes = 0;
// Cache the table object here for faster processing of your code..
var $table = $("table.authors-list");
$table.find('input[name^="cubicvolume"]').each(function () {
// Check if checkbox is checked or not here using is(':checked')
if ($table.find('checkbox[name^="treated"]').is(':checked')) {
grandTotaltreatedCubes += $(this).val();
}
});
$("#grandtotaltreatedcubes").text(grandTotaltreatedCubes.toFixed(2));
Change the following line
if($("table.authors-list").find('input[name^="treated"]').checked){
To this
if($("table.authors-list").find('input[name^="treated"]').is(':checked')){

How to add row in html table on top of specific row?

I have a table, and each row has a button to add a new row on top of it. Each row has new inputs.
I know how to add a row on top of the table, but not on top of each row that I'm clicking on the button. Would anyone have a tip on how to solve it? I might be able to do it, but the solution I see is very complicated, and I'm sure there must be a smarter solution.
Oh, also I don't know how to update the parameter sent in the insertNewRow(id) function.
So far this is what I have:
<script type="text/javascript">
function insertNewRow(id){
var row = document.getElementById("bottomRow");
var newrow = row.cloneNode(true);
console.log(newrow);
var newInputs = newrow.getElementsByTagName('input');
var allRows = row.parentNode.getElementsByTagName('tr');
row.parentNode.insertBefore(newrow, row);
var i=row.rowIndex;
console.log(i);
}
</script>
<table id="myTable">
<tr>
<td>Title1:</td>
<td></td>
<td>Title2:</td>
<td></td>
<td>Title3:</td>
<td></td>
<td></td>
</tr>
<tr>
<td><input class="c1" readonly maxlength="9" size="7" id="gTop" type="text" value ="11"></td>
<td> <-></td>
<td id="l1"><input class="c2" style="width:35px;" maxlength="9" size="7" type="text" id="lTop" value="33"></td>
<td>=</td>
<td id="rv1"><input id="rvTop" input class="c2" style="width:105px;" maxlength="100" size="37" type="text" value="blahblahblah"></td>
<td></td>
<td>x</td>
</tr>
<tr id="bottomRow">
<td><input class="c1" readonly maxlength="9" size="7" id="gBottom" type="text" value =""></td>
<td> </td>
<td id="l1"><input class="c2" style="width:35px;" maxlength="9" size="7" type="text" id="lBottom" value="11"></td>
<td>=</td>
<td id="rv1"><input id="rvBottom" input class="c2" style="width:105px;" maxlength="100" size="37" type="text" value="blahblahblah"></td>
<td><button type="button" onclick="insertNewRow(1)">+</button></td>
<td>x</td>
</tr>
</table>
In the onclick attribute, instead of just calling insertNewRow(), do something like
insertNewRow.apply(this);
The this keyword inside the onclick attribute is a reference of the clicked element. With insertNewRow.apply(this), we'll be calling insertNewRow() and at the same time, assign the this keyword inside that function call to the clicked element or in this case, the button (if we don't do that, this inside insertNewRow() will be a reference to the Window object instead). Then in, your insertNewRow() function, check if the current element being clicked on is a tr element. If not, go up by one level and see if that element is a tr element. Keep doing that until you get to the first tr element. So, basically you'll be searching for the closest tr element.
<button type="button" onclick="insertNewRow.apply(this);">+</button>
function insertNewRow(){
var row = null,
el = this;
// Get the closest tr element
while (row === null)
{
if (el.tagName.toLowerCase() === 'tr')
{
row = el; // row is now the closest tr element
break;
}
el = el.parentNode;
}
// Rest of the code here
}​
JsFiddle
If you're still not sure what Function.apply() is, take a look at the documentation here.

Add or remove input field, depending on checkbox, using JavaScript

I have <form> element with some textfields and selections, so I want several new <input type="text"> to be added, when a checkbox is checked and delete them, when it's unchecked.
What is best way to do so?
Is it possible to assign new element to variable or object and then use this variable or object as a reference to delete new elements, because it's supposed several elements to be added at the same time (e.g. <br><inpit type="text">), and I think, that adding them separately is not the best way, so deleting too.
I'm using JQuery as a framework.
<form name="add_subject">
<table cellspacing="1">
<tr>
<td class="key">Day</td>
<td class="value">
<select size="7" name="day">
<option value="1">...</option>
<option value="2">...</option>
</select>
</td>
</tr>
<tr>
<td class="key">Groups</td>
<td class="value">
<input type="checkbox" name="sg">
</td>
</tr>
<tr>
<td class="key">Lecture</td>
<td class="value">
<input type="text" size="50" maxlength="50" name="lec1"> /***/
</td>
</tr>
<tr>
<td class="key">Auditory</td>
<td class="value">
<input type="text" size="4" maxlength="4" name="aud1"> /***/
</td>
</tr>
</table>
I want to add <br><input type="text"> : <input type="text"> after existing <input> field, where /***/ is given, when the checkbox is cheked and remove, when it's not.
What is the best way?
Thanks!
I would already put the input fields in the markup, for example:
<td class="value">
<input type="text" size="50" maxlength="50" name="lec1">
<div class="some-class">
<input type="text"> : <input type="text">
</div>
</td>
etc. Then make them hidden by default with this CSS rule:
div.some-class {
display: none;
}
Now add an event handler to your checkbox, that simply toggles the visibility of your some-class divs whenever the checkbox is clicked:
$(document).ready(function() {
var visible = false;
$('input[name="sg"]').click(function() {
var divs = $('div.some-class');
if (visible) {
divs.each(function() {
this.style.display = 'none';
});
visible = false;
}
else {
divs.each(function() {
this.style.display = 'block';
});
visible = true;
}
});
});
Try to debug the next please if does not work properly (there is an idea):
$( '.value>[type=checkbox]' ).click(
function()
{
if( $( this ).is(':checked') )
{
$( 'td.value' ).append( '<br id="myinput"><input type="text"> : <input type="text">' );
}
else
{
$( '#myinput' ).remove();
}
}
)

Categories