How to use closest() in jQuery - javascript

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.

Related

the "closest()" method in jquery wont work

so i have this html code and jquery code. And when i press a tablerows "produkter" button whith the class name "fa-products", i want to find the hidden field input that is on the same tablerow as the button you choose to click(every tablerow have a hidden field input and a "produkter button"). Then i want to save the value of the hidden field in a variable thats all can anyone help me? when i "console.log(discountId);" it responds undefiend
<div class="eastSide row top-buffer col-xs-8" style="overflow:scroll; height:250px;">
<table style="width:100%">
<tr>
<th>Code</th>
<th>Aktiv</th>
<th>Skapad</th>
<th></th>
</tr>
#foreach (var discount in Model.DiscountList)
{
<tr>
<td><input name="codeTextBox" id="codeTextBox" value="#discount.Code" maxlength="18" /></td>
<td><input type="checkbox" id="activeCheckBox" name="activeCheckBox" checked="#discount.Active" /></td>
<td><input type="datetime" value="#discount.CreatedDate" readonly /></td>
<td>
<input type="button" value="Radera" class="fa fa-remove" data-url="#Url.Action("DeleteDiscountCode","Discount",new { id= discount.Id})" />
<input type="button" value="Uppdatera" class="fa fa-update" data-url="#Url.Action("UpdateDiscount","Discount")" />
<input type="button" value="Produkter" class="fa fa-products" id="#discount.Id" data-url="#Url.Action("chooseProductsForDiscountCode","Discount")" />
</td>
<td><input id="id" type="hidden" value="#discount.Id" /></td>
</tr>
}
</table>
</div>
<script>
$(".fa-products").on("click", function (e) {
var discountId = $(event.target).closest('input[type="hidden"]').val();
console.log(discountId);
});
</script>
It will not work, because the hidden input is not the parent of the registered element.
Probably this will solve your issue: $(event.target).closest('tr').find('input[type="hidden"]').val();
You need to do search for common parent element via closest and then find input inside of the result:
$(".fa-products").on("click", function (e) {
var discountId = $(event.target).closest('tr').find('input[type="hidden"]').val();
console.log(discountId);
});

Unable to traverse the DOM to find related input

I want get the value of next immediate input value by class. Here is my code:
<table>
<tr>
<td>
<input class='name' value='demo1'/>
</td>
<td>
<input class='age' value='23'/>
</td>
<td>
<input class='name' value='demo2'/>
</td>
<td>
<input class='age' value='24'/>
</td>
</tr>
</table>
and JS file
$('body').on('blur','.name',function(){
alert($(this).parent().next('.age').val());
});
I want the value of age next to name? What have I missed?
My JSfiddle link is: http://jsfiddle.net/mvkc95f8/
Thank you
The .age input field is within the sibling td element, so you need to use .next() to get that td, then .find('.age') to retrieve the input. Try this:
alert($(this).parent().next().find('.age').val());
Updated fiddle

How to select a specific html node with a jquery selector and JavaScript?

I have the following html table:
<tbody>
<tr>
<td class="rich-tabpanel-content">
<table>
<tbody>
<tr>
<td>
<span class="bold">Overview</span>
</td>
</tr>
<tr>
<td>
<input class="titleInput" type="text"></input>
</td>
</tr>
<tr>
<td>
<span class="bold">Shorttext</span>
</td>
</tr>
<tr>
<td>
<textarea class="shorttextInput"></textarea>
</td>
</tr>
<tr>
<td>
<span class="bold">Longtext</span>
</td>
</tr>
<tr>
<td>
<textarea class="longtextInput"></textarea>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
Now i want to select these tags in DOM:
<span class="bold">Overview</span>
<span class="bold">Shorttext</span>
<span class="bold">Longtext</span>
I have written these line of JQuery and Java Script Code to change the value of these HTML Tags, but the command
"jQuery(value).parent().prev();"
doesn´t select the right html tag in the DOM:
jQuery('.titleInput').each(function(index, value) {
selectAndExpand(value);
}
function selectAndExpand(value) {
var captionCell = jQuery(value).parent().prev();
captionCell.empty();
var newCaption = '<span class="bold">' + "HERE IS MY NEW INPUTVALUE" + '</span>';
captionCell.append(newCaption);
};
How can i solve this problem?
It is important to navigate for example from the node
<textarea class="longtextInput"></textarea>
to
<span class="bold">Longtext</span>
or from
<input class="titleInput" type="text"></input>
to
<span class="bold">Overview</span>
Use:
$('.bold').each(function(){
$(this).html("HERE IS MY NEW INPUTVALUE")
});
Working Fiddle
With Javascript:
var elements = document.getElementsByClassName('bold');
console.log(elements[0]);
console.log(elements[1]);
console.log(elements[2]);
With jQuery:
var elements = $('.bold');
console.log(elements[0]);
console.log(elements[1]);
console.log(elements[2]);
or...
console.log($('td:contains("Overview")'));
console.log($('td:contains("Shorttext")'));
console.log($('td:contains("Longtext")'));
Cheers.
You can select them by class name (when the class name is the same, in your case "bold"):
$(".bold");
To select all textareas after them and set values to these "bold" - element use
var spans = $(".bold");
$.each(spans, function(index, item) {
var spanTd = $(item).closest("tr");
var value = $(spanTd).next().find("textarea").val();
if (value === undefined) { //if there aren't textarea - get textbox.
value = $(spanTd).next().find("input[type='text']").val();
}
$(item).html(value);
});
EDIT: Demo - http://jsfiddle.net/h9fpy/
use class selector in your case use $('.bold') to select the span class bold and you can easily navigate to prev and next like $('.bold').parent('tr').next().find('.bold'); and also give the bold class to your input elements so that we can easily navigate.

Deleting a specific row in a table

I'm trying to delete a specific row from a table using javascript. The way I'm trying to do it now, is by retrieving the ID of the current row by clicking a button (the delete button) and then deleting the row. The problem is that I'm not retrieving the current row ID in the table. If someone could help me retrieve the the ID of the current row when the user clicks the delete button, I think I can solve the rest myself. Thanks
/*The Javascript*/
function delete_row() {
alert('id goes here');
//getElementById('row').innerHTML ='hello';
//id.deleteRow();
//var table = document.getElementByTagName('items_table');
//var row = table.rows[index];
//document.getElementByTagName('items_table').deleteRow(0);
}
/*The HTML of the Table*/
<table id="items_table">
<tr id="row_1">
<td>
<input type="text" value="item1"/>
</td>
<td>
<button onclick="delete_row();">X</button>
</td>
</tr>
/* Five rows in this table... */
<tr id="row_5">
<td>
<input type="text" value="item5"/>
</td>
<td>
<button onclick="delete_row();">X</button>
</td>
</tr>
</table>
You could just ascend the tree until you find a row:
function delete_row(btn) {
var tr = btn;
while(tr && tr.nodeName != "TR") tr = tr.parentNode;
if( !tr) throw new Error("Failed to find the row, was the function called correctly?");
tr.parentNode.removeChild(tr); // delete it
}
And:
<button onClick="delete_row(this);">X</button>
The this is important, as it provides a reference to the button that was clicked, so we can find the row it is in.
Check this code. It has been verified and will do your job perfectly. :)
<script>
function delete_row(me) {
alert(me.parentNode.parentNode.id);
}
</script>
<table id="items_table">
<tr id="row_1">
<td>
<input type="text" value="item1"/>
</td>
<td>
<button onclick="delete_row(this);">X</button>
</td>
</tr>
<tr id="row_5">
<td>
<input type="text" value="item5"/>
</td>
<td>
<button onclick="delete_row(this);">X</button>
</td>
</tr>
</table>
Can't you just change <button onclick="delete_row();">X</button> to <button onclick="delete_row('row_5');">X</button>, in each row, respectively?
Your handler would look like:
function delete_row(theID) {
alert(theID);
}

Can't show a display none inside a table

I'm having a problem with style.display.
I want to show a submit box (which is inside a table) when I change a number and it's not working.
Here's the code:
<head>
<script>
function changedisp(Section){
if (Section.style.display=="none"){
Section.style.display=""
}
else{
Section.style.display="none"
}
}
function raisenumber(s,s1) {
var x;
x = document.getElementById(s).innerHTML;
document.getElementById(s).innerHTML = x*1 + 1;
changedisp(s1);
}
</script>
</head>
<body>
<table>
<tr>
<th><b>ID</b></th>
<th><b>number</b></th>
<th><b>buttoon</b></th>
<th><b>submit</b></th>
</tr>
<form action="modifica_inventario.php" method="post">
<tr>
<td> <b id="cell1A">item number1</b></td>
<td> <b id="cell2A">10</b></td>
<td> <button id="cell3A" type="button" onClick=raisenumber("cell2A","cell4A")>+1</button></td>
<td> <b id="cell4A" style="display: none;"> <input type="submit" value="submit"/></b> &nbsp </td>
</tr>
<tr>
<td> <b id="cell1B">item number1</b></td>
<td> <b id="cell2B">10</b></td>
<td> <button id="cell3B" type="button" onClick=raisenumber("cell2B","cell4B")>+1</button></td>
<td> <b id="cell4B" style="display: none;"> <input type="submit" value="submit"/></b> &nbsp </td>
</tr>
</form>
</table>
</body>
Well I don't know why it's not showing on and off the submit button every time a press the button...
I also tried replacing
changedisp(s1);
by
s1.style.display="";
Any comments about this?
You need to pass the actual element you are trying to hide and show to your changedisp function. In your code you are just passing the ID name of the element. Try this...
function raisenumber(s,s1) {
var x;
x = document.getElementById(s).innerHTML;
document.getElementById(s).innerHTML = x*1 + 1;
changedisp(document.getElementById(s1));
}
notice changedisp(document.getElementById(s1)); passes the actual element instead of just the ID.
You need to set it to a display type explicitly:
Section.style.display="inline";
Or inline-block, or block, or whatever you want.
A <B> is by default display:inline, so trying setting to "inline" not the empty string, "".

Categories

Resources