jQuery get value closest input field - javascript

I have HTML code like this:
<tr>
<td class='qty'><input class='narrow' value='1' /><i class='fa fa-trash' aria-hidden='true'></i></td>
<td class='comm'><input class='narrow' value='' size='5'/></td>
</tr>
This code will be auto generated by a JS function, so it happens more often.
to get the Value from the first input I use this function:
jQuery('#tbl_order .qty input').bind('change', function() {
Within this function I want to get the next input value. I have tried this what does not work
jQuery(this).closest(".comm input").val()

.closest()
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
You can use find() on the closest tr element. I will also prefer using on() and input event instead of bind() and change respectively.
Demo:
jQuery('#tbl_order .qty input').on('input', function() {
var nextVal = jQuery(this).closest("tr").find(".comm input").val();
console.log(nextVal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr id="tbl_order">
<td class='qty'><input class='narrow' value='1' /><i class='fa fa-trash' aria-hidden='true'></i></td>
<td class='comm'><input class='narrow' value='1234' size='5'/></td>
</tr>
</table>

You can use next() combines with closest()
$('#tbl_order .qty input').bind('change', function() {
var $currentTd = $(this).closest("td");
var $nextTd = $currentTd.next();
var value = $nextTd.find("input").val();
console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl_order">
<tr>
<td class='qty'><input class='narrow' value='1' /><i class='fa fa-trash' aria-hidden='true'></i></td>
<td class='comm'><input class='narrow' value='' size='5'/></td>
</tr>
</table>

$('.fa fa-trash').on('click', function () {
$tr = $(this).closest('tr');
var data = $tr.children('td').map(function () {
return $(this).text();
}).get();
console.log(data);
<table id="tbl_order">
<tr>
<td><input class='narrow' value='1' /><i class='fa fa-trash' aria-
hidden='true'></i></td>
<td><input class='narrow' value='' size='5'/></td>
</tr>
</table>
this may give you some idea about mapping function. here I give jquery onclick class to fa fa-trash. so whenever the event is fired the particular row get selected. (i hope in the table your getting data from backend code)

Related

Iterating through table and get the value of a button in each tablerow jQuery

I have buttons in a table which are created dynamically. I want to iterate through a table, get the tablerows which contain a checked checkbox and get the value of a button inside the tablerow. I want to push the values in an array after. The buttons don't have a unique ID so I cannot get their values by id.
I tried to get the values through giving the buttons a class and itering works fine but the array is filled with empty entries.
$("#bt_multiple_deletion").off().on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).find(".filefolder-button").text());
});
})
I really don't know what Im doing wrong. I tried to get the values with .text(), .val() etc.
My table row looks like this:
<tr class="select">
<td>
<span class="countEntries"><input id="lv_fifo_ctrl7_cb_delete_file" type="checkbox" name="lv_fifo$ctrl7$cb_delete_file" /></span>
</td>
<td>
<img src="images/icons/013_document_02_rgb.png" alt="document" />
</td>
<td class="name">//the button i want to get the value from
<input type="submit" name="lv_fifo$ctrl7$bt_file" value="013_document_png.zip" id="lv_fifo_ctrl7_bt_file" class="filefolder-button download file del" style="vertical-align: central" />
</td>
<td>
<span id="lv_fifo_ctrl7_lb_length">33.14 KB</span>
</td>
<td>
<span id="lv_fifo_ctrl7_lb_CreationTime">21.10.2014 07:34:46</span>
</td>
<td></td>
<td>
<input type="submit" name="lv_fifo$ctrl7$bt_del_file" value="delete" id="lv_fifo_ctrl7_bt_del_file" class="delete-button delete-file" />
</td>
</tr>
The problem is rows is the input elements not the tr elements so in the loop you need to find the tr which contains the input then find the target element inside it
$("#bt_multiple_deletion").off().on("click", function () {
var checked = $(".select").find("input[type=checkbox]:checked");
var files = checked.map(function () {
return $(this).closest('tr').find(".filefolder-button").val();
}).get();
})
Another option is
$("#bt_multiple_deletion").off().on("click", function () {
var rows = $(".select").find("tr").has('input[type=checkbox]:checked');
//var rows = $(".select").find('input[type=checkbox]:checked').closest('tr');
var files = rows.map(function () {
return $(this).find(".filefolder-button").val();
}).get();
})
#Timo Jokinen Do you need this
$("#bt_multiple_deletion").on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).parents("tr").find("td.filefolder-button").text());
});
console.log(files);
})
<table class="select">
<tr>
<td class="filefolder-button">test1</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test2</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test3</td>
<td><input type="checkbox" /></td>
</tr>
</table>
<button id="bt_multiple_deletion">delete</button>
Checkout example link here

How to use closest() in jQuery

I am trying to get value of a text box by using closest().
My form contains dynamically created table with one text box and button in each row . I want to show the value of text box in button click event.
Table format is given below
<table id="dataarea" class="table">
<tbody>
<tr>
<td>jaison<td>
<td class="amountclm">
<input id="txtamt" class="amtcls" type="text" value="100">
</td>
<td>
<button id="schedule" class="schbtn btn btn-primary" type="button" onclick="UpdateSchedule()">Confirm</button>
</td>
</tr>
<tr>
<td>ARUN<td>
<td class="amountclm">
<input id="txtamt" class="amtcls" type="text" value="500">
</td>
<td>
<button id="schedule" class="schbtn btn btn-primary" type="button" onclick="UpdateSchedule()">Confirm</button>
</td>
</tr>
</tbody>
</table>
I have written one javascript code (given below) . when the code will execute, it return a null value.
Function
function UpdateSchedule() {
var amt2 = $(this).closest('td.amountclm').find('.amtcls').val();
alert( amt2);
}
Please let me know why am not getting the null value.
jQuery .closest() goes up from the current element until it finds what you give it to find. jQuery .find() goes down until it finds what you give it to find.
This does the trick:
http://jsfiddle.net/6T3ET/
id must be unique, you need to use class instead:
<button class="schedule schbtn btn btn-primary" type="button">
<input class="amtcls txtamt" type="text" value="500">
an use .click() instead of inline onClick handler since you're using jQuery. So you can do:
$('.schedule').click(function() {
var amt2 = $(this).closest('td').prev('td.amountclm').find('.amtcls').val();
alert( amt2);
});
Please note that the .amountclm input is the child of a td whose is the immediate previous sibling of parent td of your clicked .schedule button.
Try this
replace 'this' with the 'schedule_' class attribute
function UpdateSchedule() {
var amt2 = $(".schedule_").closest('td.amountclm').find('.amtcls').val();
alert( amt2);
}
HTML :
<table id="dataarea" class="table">
<tbody>
<tr>
<td>jaison<td>
<td class="amountclm">
<input id="txtamt" class="amtcls" type="text" value="100">
</td>
<td>
<button id="schedule" class="schbtn btn btn-primary schedule_" type="button" onclick="UpdateSchedule()">Confirm</button>
</td>
</tr>
<tr>
<td>ARUN<td>
<td class="amountclm">
<input id="txtamt" class="amtcls" type="text" value="500">
</td>
<td>
<button id="schedule" class="schbtn btn btn-primary schedule_" type="button" onclick="UpdateSchedule()">Confirm</button>
</td>
</tr>
</tbody>
</table>
or try with Jquery as
$(document).on('click', '.schedule_',function(){
var amt2 = $(this).closest('td.amountclm').find('.amtcls').val();
alert( amt2);
} );
Use .parent() and .prev() in jquery for this contradiction
$(".schbtn").click(function() {
var amt2 = $(this).parent().prev("td.amountclm").find('.amtcls').val();
alert( amt2);
});
Fiddle
First of all .closest() is not plain JavaScript. It's a function from jQuery.
http://api.jquery.com/closest/
and it traverses up in the element hierachy. And td.amountclm is not in the element hierachy of the button#schedule.
Therefore .closest wont find it.

Get values of one column and pass it to another

I have a table and if I click a button i want to take the value from charge_outstanding_NUM and set charge_receipt_NUM to it. I need a reusable script because I will not know how many rows will get posted through.
<table>
<thead>
<tr>
<th>ID</th>
<th>Value</th>
<th>Outstanding</th>
<th>Reciept</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>150.00</td>
<td id="charge_outstanding_1">150.00</td>
<td><input type="text" name="charge_receipt_1" id="charge_receipt_1" value=""></td>
</tr>
<tr>
<td>002</td>
<td>10.00</td>
<td id="charge_outstanding_2">10.00</td>
<td><input type="text" name="charge_receipt_2" id="charge_receipt_2" value=""></td>
</tr>
<tr>
<td>003</td>
<td>250.00</td>
<td id="charge_outstanding_3">250.00</td>
<td><input type="text" name="charge_receipt_3" id="charge_receipt_3" value=""></td>
</tr>
</tbody>
</table>
My jquery isn't working and I am not sure why. I click the button then loop through each col that starts with 'charge_outstanding_' then take the value and assign it to the closest input which is within the same row.
$('#pay_in_full').click(function(){
$("[id^=charge_outstanding_]").each(function(){
charge = $(this).val();
$(this).closest('input').val(charge);
});
});
working JSfiddle: http://jsfiddle.net/F5NvW/2/
Issue with your code: charge = $(this).val(); you are finding td which has no value, you need .html() for this
$(document).on("click", "#pay_in_full", function() {
$("[id^=charge_outstanding_]").each(function(){
var charge = $(this).html();
$(this).next().find('input').val(charge);
});
});
Suggestion: use class name with each <td> like this
Jsfiddle: http://jsfiddle.net/F5NvW/
Note: less error prone..
$(document).on("click", "#pay_in_full", function() {
$(".outstanding").each(function(){
var charge = $(this).html();
$(this).next().find('.paidAmount').val(charge);
});
});
.Closest will search for the ancestor elements, In your case the target input is the children of the next sibling of the selected element. So you have to use .find() or .children() to select that.
Try,
$('#pay_in_full').click(function(){
$("[id^='charge_outstanding_']").each(function(){
charge = parseInt($(this).text());
$(this).next().find('input').val(charge);
});
});
Additionally, You are selecting a td element, so you have to use .text() to get its text not .val()
DEMO

jQuery Multiple Dynamic Forms + Foreach Loop

Okay, i'm completetly stuck. I tried every answer on here but I just can't get it to work.
My Aim: Updating dynamic forms with jQuery & AJAX
What's the problem: When clicking one of the "save" buttons it only saves the first value, I tried to do it with different ID's but as a newbie to jQuery I don't think I'm doing this right.
jQuery
$(document).ready(function() {
$("textarea").keyup(function(){
var txtArea = $('.txta').val();
var scriptString = $('.button').attr("url");
$(".button").click(function(){
$.ajax({
method: 'get',
url: '../wp-content/plugins/custom-text-editor/writefile.php',
data: {
'myString': scriptString,
'txt': txtArea,
'ajax': true
},
success: function(data) {
$('#'+myString).text(data);
return false;
}
});
});
});
});
writefile.php
$file = fopen("files/tab1.txt","w");
$txt = $_GET['txt'];
fwrite($file,$txt);
fclose($file);
echo "OK!";
Generated HTML
<table class=bordered>
<tr>
<th>Filename</th>
<th></th>
<th></th>
</tr>
<tr class=header>
<td class='plus'>+</td>
<td><p>tab1.txt</p></td>
<td><span id='ss' class='data'></span></td>
</tr>
<tr>
<td colspan="3" class="nopad">
<p><textarea cols="80" class="txta" rows="12" id="tab1.txt">asdasd</textarea>
<span id='tab1.txt' class='button' rel='qyz' url=tab1.txt>Save</span></p>
</td>
</tr>
<tr class=header>
<td class='plus'>+</td>
<td><p>tab2.txt</p></td>
<td><span id='ss' class='data'></span></td>
</tr>
<tr>
<td colspan="3" class="nopad">
<p><textarea cols="80" class="txta" rows="12" id="tab2.txt">This is file 2</textarea>
<span id='tab2.txt' class='button' rel='qyz' url=tab2.txt>Save</span></p>
</td>
</tr>
<tr class=header>
<td class='plus'>+</td>
<td><p>tab3.txt</p></td>
<td><span id='ss' class='data'></span></td>
</tr>
<tr>
<td colspan="3" class="nopad">
<p><textarea cols="80" class="txta" rows="12" id="tab3.txt">And File 3</textarea>
<span id='tab3.txt' class='button' rel='qyz' url=tab3.txt>Save</span></p>
</td>
</tr>
<tr class=header>
<td class='plus'>+</td>
<td><p>tab4.txt</p></td>
<td><span id='ss' class='data'></span></td>
</tr>
<tr>
<td colspan="3" class="nopad">
<p><textarea cols="80" class="txta" rows="12" id="tab4.txt">It works!</textarea>
<span id='tab4.txt' class='button' rel='qyz' url=tab4.txt>Save</span></p>
</td>
</tr>
</table>
This should resolve your problem:
$(document).ready(function () {
$(".button").click(function () {
var txtArea = $(this).closest('tr').find('.txta').val();
var scriptString = $(this).closest('tr').find('.button').attr("url");
$.ajax({
method: 'get',
url: '../wp-content/plugins/custom-text-editor/writefile.php',
data: {
'myString': scriptString,
'txt': txtArea,
'ajax': true
},
success: function (data) {
$('#' + myString).text(data);
return false;
}
});
});
});
How it works:
$(this) gives access to an element being clicked. Even "this" (without dollar sign and without quotes) gives such access, but it is not a jquery object, we need jquery object for further manipulations.
closest('tr') iterates the chain of parent elements until it finds an element satisfying the specified selector (in this case it searches for closest tr-element).
find('.txta') iterates the descendants (of the current element) until it finds an element satisfying the specified selector (in this case it searches for any element having "txta" class, within the tr element).
The rest of code is unchanged.
Further notes:
Event handlers within event handlers (like $("textarea").keyup(function(){ ... $(".button").click(function() { ... ) should be avoided, since the effect is: each time an outer event is handled, a new handler for the inner event is created and attached.
Think of jquery as being kind of "navigation system" over DOM-tree. With functions like "closest", "find", "next", "prev" you navigate around and get to the desired element dynamically, at runtime.
When the desired object has ID and is unique, address it with "#ID" syntax.
When the desired object is repeated (like a row/cell within the table or an element within the cell), then use css-classes and DOM-traversal functions in order to address it.
If you need more information on DOM-traversing:
http://learn.jquery.com/using-jquery-core/traversing/
http://api.jquery.com/category/traversing/

Catching checkbox changes and indexing to toggle LEDs

I would like to catch a checkbox change and also catch the index of the checkbox selected or unselected. I'm wondering if this could be ok.
$("input[type='checkbox']").change(function () {
$("input[type='checkbox']").each(function (i) {
//my code here
switch (i) {
case 0:
break;
case 1:
break;
.
.
}
});
});
My html is something like this:
<table>
<tr>
<td id='led' bgcolor=#cccccc>OFF</td>
<td><input type='checkbox' name='' value='' ></td>
</tr>
<tr>
<td id='led' bgcolor=#cccccc>OFF</td>
<td><input type='checkbox' name='' value='' ></td>
</tr>
<tr>
<td id='led' bgcolor=#cccccc>OFF</td>
<td><input type='checkbox' name='' value='' ></td>
</tr>
<tr>
</table>
So I would like to detect what box was selected and then change the led to ON and to red background color. On the other hand if the the box is unselected I want to return the LED to OFF and change color to #cccccc
Without further details, this is the most generic code I can offer (with more information comes great, uh, answers):
$('input:checkbox').change(function(){
// caching the $(this) jQuery object, since we're using it more than once:
var that = $(this),
// index of element with regard to its sibling elements:
index = that.index(),
// index with regard to other checkbox elements:
checkboxIndex = that.index('input:checkbox');
if (this.checked){ // this.checked evaluates to a Boolean (true/false)
// this block executed only if the checkbox *is* checked
} else {
// this block executed only if the checkbox is *not* checked
}
});
Edited to address requirements in (edited/clarified) question:
$('input:checkbox').change(function () {
var that = this,
$that = $(that),
led = $that.closest('tr').find('td:first-child');
led.removeClass('on off').addClass(function(){
return that.checked ? 'on' : 'off';
});
});
JS Fiddle demo.
Coupling the above jQuery with the following CSS:
.led,
.led.off {
background-color: #ccc;
}
.led.on {
color: #000;
background-color: #f00;
}
And HTML:
<table>
<tr>
<td class='led'>OFF</td>
<td>
<input type='checkbox' name='' value='' />
</td>
</tr>
<tr>
<td class='led'>OFF</td>
<td>
<input type='checkbox' name='' value='' />
</td>
</tr>
<tr>
<td class='led'>OFF</td>
<td>
<input type='checkbox' name='' value='' />
</td>
</tr>
</table>
Note that I've replaced the id="led" wtih class="led", since an id must be unique within the document. This is important, when it comes to JavaScript, and HTML validity.
References:
:checkbox selector.
addClass().
closest().
index().
removeClass().
You can do if a checkbox is checked or not using this inside your each function code:
if ( $(this).is(':checked') ) {
// ...
} else {
// ...
}
$('input:checkbox').change(function() {
if (this.checked) {
// your code here
alert(this.value);
}
});

Categories

Resources