Jquery child>Parent>child>child selector - javascript

I need help with my following code:
Html:
<table>
<tr class="oc">
<td class="process">process</td>
<td><input name="data" /></td>
</tr>
<tr class="oc">
<td class="process">process</td>
<td><input name="data" /></td>
</tr>
</table>
On click of td[class=process] , I need the value of input[name=data]. I tried in several ways and failed. I attempts include follows:
Inside Jquery on click function:
var v = $(this).parent().children(":eq(2)").children().val()*1;
var v = $(this).parent().children.children("input[name=data]").val()*1;
var v = $(this).parent().find("input[name=data]").val()*1;
var v = $(this).parent().children(":eq(2)").children().val()*1;
What happening is, every time I click the td[class=process], I am getting the previous value of input[name=data] + current value of input[name=data]
And, I have no idea why. Help would be highly appreciated.

Your third variant already works.
var v = $(this).parent().find("input[name=data]").val()*1;
Your 2nd approach is incorrect, as children is a function.
Your 1st and 4th approach (unless I'm blind) are the same. However, since :eq() is zero-indexed; the <td> you're selecting is actually position 1, not 2. You can see this working here.
var v = $(this).parent().children(":eq(1)").children().val()*1;
You may also like to hear about next(), which might make this a bit easier.
var v = $(this).next().children().val() * 1;
See next(), and this fiddle.

using jquery it is very simple
$('.process').click(function(e)
{
var myData = $(this).next().children().val();
});

You can use next() to target the next column and then find() or children() to access the input inside it.
$("td.process").click(function(){
var v = $(this).next("td").find("input[name='data']").val();
})

$(this).next().find('input[name=data]').val()

Related

How to get value from input field with Javascript?

How can I get the value of an specific input field with Javascript?
Lets take this shopify shop for example: https://geekymate.com/products/magic-doormat-1?variant=18941211607138
I am trying to create a script which is automatically applying an discount code based on the quantity filled in the quantity field.
But to do that I need to be able to get the latest value of the field.
How would the code look like to get the latest/current value?
EDIT: Thank you for the hint with the question. I do know that I need to use getElementById ( For the linked page above it would be this: var x = document.getElementById("Quanity").value; ) but how do I always get the latest input automatically if the enduser is changing the value?
The other answers are also correct (using jQuery .keyup), but you can also use this solution below (which is better). This solution uses pure javascript.
The code selects the element by using .getElementById() and uses .addEventListener() to do something when input changes.
var text = document.getElementById("text");
window.onload = function() {
text.addEventListener("input", function() {
console.log(text.value);
});
}
<input id="text" />
Or you can use the following if you want a jQuery solution. This uses jQuery .bind().
$("#text").bind("input", function() {
console.log($("#text").val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="text" />
keyup() function ;)
It runs each time, when user types new text.
Also, you can use input() or change() functions.
In jQuery it works like this:
$(document).on('keyup', '#InputID', function(){
//...code...
var discount = Number( document.getElementById('InputID').value )*10/100;
});
It's a Jquery function that runs on keypress. I've included a snippet below to see how it would tie in with an input field.
$('#code').keyup(function() {
var discountcode = this.value;
console.log(discountcode);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="code" type="test" />
Keyup runs every time a specific element is lifted. Imagine someone enters 'Hello'
You will see the following logged:
'H' 'He' 'Hel' 'Hell' 'Hello'
look at the code snippet. using JavaScript to get the values. and can use addEventListener to detect the change and use detectChange function to get the latest values.
var discount = [];
function detectChange() {
var table = document.getElementsByClassName("shappify_qb_grid")[0];
for (var i = 0; i < table.rows.length; i++) {
var row = "";
for (var j = 0; j < table.rows[i].cells.length; j++) {
if (j == 1) {
row = table.rows[i].cells[j].innerHTML;
rate = parseFloat(row);
if (rate && discount.indexOf(rate) < 0) {
discount.push(parseFloat(row));
console.log('---', parseFloat(row));
}
}
// console.log('discount : ', discount);
}
}
}
detectChange();
console.log('discount : ', discount);
<table class="shappify_qb_grid" border=1>
<thead>
<tr>
<th>Qty</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<td>Buy 1</td>
<td>0% Off</td>
</tr>
<tr>
<td>Buy 2</td>
<td>10% Off</td>
</tr>
<tr>
<td>Buy 4</td>
<td>12% Off</td>
</tr>
<tr>
<td>Buy 5</td>
<td>14% Off</td>
</tr>
<tr>
<td>Buy 6</td>
<td>17% Off</td>
</tr>
</tbody>
</table>
This work for me!
document.getElementById("text").value;
<input id="text" />
Use the document.getElementById(); -command to get the existence of the referenced element in your HTML page. Then use the same technique of assigning attributes in the original HTML coding rules.
Use document.getElementById('able').value = 'whatever';.

Filter Table with JQuery using the “each” element

OK everybody, I hope you can help me. I have a problem with JQuery or better with the each selector of JQuery.
I have an example table, where I want to filter for special values which I entered before. Those values I got from my input field , store them in a variable, split the data an create an JQuery Object.
Well and then I think I have a problem with the selection, marked in the code section.
<p>
<input id="testyear" size="4" type="text">
<input value="Werte" onclick="getvalue()" type="button">
</p>
<script>
function getvalue() {
var wert = $('#testyear').val();
$("#years").find("tr").hide();
var data = this.value.split(" ");
// create jQuery Object
var jQueryObject = $("#years").find("tr");
// i think here is my error, i want to display only the object which are equal or better stored in my variable “wert”.
$.each(data, function (){
//jQueryObject = jQueryObject.filter(wert);
jQueryObject == wert;
});
jQueryObject.show();
};
<!--Example Table-->
<table id="years">
<tbody>
<tr>
<td>1997</td>
<td class="century">20</td>
</tr>
<tr>
<td>2001</td>
<td class="century">21</td>
</tr>
</tbody>
</table>
I expect, that when I enter 1997 in the inpt field, the whole tr which contains 1997 will be displayed. I know it is simple but I have no idea so thanks for your help.
Use a filter on the TR's after initially hiding them all.
e.g.
getvalue = function() {
var wert = $('#testyear').val();
// create jQuery Object
$("#years tr").hide().filter(function() {
return ~~$("td", this).first().text() >= wert;
}).show();
};
JSFiddle: https://jsfiddle.net/TrueBlueAussie/h8Lejfac/
Notes:
The ~~ is a little conversion to integer trick
You seem to have extra code you do not need in the example
Just get filter to return true for each item you want to keep and false for the rest
When using jQuery, avoid using inline event handlers (like onclick=). Use jQuery event handlers instead. See below:
e.g.
$('#wert').click(function() {
var wert = $('#testyear').val();
// create jQuery Object
$("#years tr").hide().filter(function() {
return ~~$("td", this).first().text() >= wert;
}).show();
});
JSFiddle: https://jsfiddle.net/TrueBlueAussie/h8Lejfac/1/
I think your problem is not in each() method (not selector). Your problem is here:
var data = this.value.split(" ");
this is not defined (you are not in an object scope). I think you need this:
var data = wert.split(" ");
-----------^^^^
You've obtain the value of wert in the last line.

Jquery next() is not working

I have
<table class="prodtable">
<tr>
<td></td>
<td>
<input class="editok" value="2" />
</td>
<td>
<input name="prodnumber" value="1" />
<i></i>
</td>
</tr>
</table>
and this js
$('.prodtable').on('blur','.editok',function(){
var neuanzahl = $(this).val();
$(this).parent('td').text(neuanzahl);//<-- till here works fine
$(this).parent('td').next().find('input').val(neuanzahl);//<-- from here, failure
$(this).parent('td').next().find('i').addClass('icon-pencil');
});
the editok input was inserted dynamically, thats why i am setting the handler from parent table.
my problem is, on blur event, the value of the given input should be put in the next input which is inside the next td with name prodnumger and the <i> should get the class icon-pencil.
I am trying for 1 hour now, what a shame.. not a single success. what am I doing wrong here?
This line
$(this).parent('td').text(neuanzahl);
replaces everything in the TD, as that's what text() does, it overwrites everything, so on the next line when you do
$(this).parent('td').next().find('input') ...
there is no this, you just removed it with text()
Just chaining instead of using multiple lines will keep the reference
$('.prodtable').on('blur','.editok',function(){
var neuanzahl = this.value;
$(this).parent('td')
.text(neuanzahl)
.next('td')
.find('input')
.val(neuanzahl)
.next('i')
.addClass('icon-pencil');
});
FIDDLE
The minute you call $(this).parent('td').text(...), you've removed the input from its parent. So $(this).parent('td') in the following calls won't match anything.
Save that td at the start, and use it throughout:
$('.prodtable').on('blur','.editok',function(){
var neuanzahl = $(this).val();
var td = $(this).parent('td');
td.text(neuanzahl);
td.next().find('input').val(neuanzahl);
td.next().find('i').addClass('icon-pencil');
});
Example: http://codepen.io/paulroub/pen/xHwdi
Solution is to store reference of next div in a variable.
$('.prodtable').on('blur', '.editok', function () {
var td = $(this).parent('td');
var next = $(this).parent('td').next(); //Store reference of next div in a variable
var neuanzahl = $(this).val();
td.text(neuanzahl);
next.find('input').val(neuanzahl);
next.find('i').addClass('icon-pencil');
});
Problem with your code is that when $(this).parent('td').text(neuanzahl) reference to this is lost as you have replaced the content to td.
Your table opening tag is not spelled correctly that is likely why you are having difficulties.

Why I can't get the input value

I have this table in my HTML:
<table class="dataTable" id="repaymentShedule">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
</tr>
</thead>
<tbody data-bind="foreach: creditDetails">
<tr>
<td class="paymentDate" data-bind="text: dateOfPayment"></td>
<td class="startBalance" data-bind="text: beginingBalance"></td>
<td class="monthlyInt" data-bind="text: monthlyInterest"></td>
<td class="principal"><input data-bind="value: princpalPayment"></input></td>
<td class="monthlyInst" data-bind="text: monthlyInstallment"></td>
<td class="remainingBalance" data-bind="text: endingBalance"></td>
<td class="paid"><input type="checkbox" data-bind="checked: isPaid, disable: isPaid, click: testFunc, value: true"></td> <!-- value: true moje da ne e nujno -->
<td class="currentDate" data-bind="text: currentDate"></td>
</tr>
</tbody>
</table>
The values are comming from knockout js bindings.
and I'm trying to get all the values of the principal class with the function below:
updateValues = function(){
$("tbody").find("tr").each(function() {
var principal = $(this).find('td.principal').val();
console.log(principal);
});
};
Bu the console returns: (an empty string)
EDIT:
The above function works without any problems on the paymentDate class only by changing the .val() to .text()
I'm pretty sure that I'm not getting the value the right way, or that the binding is not allowing me to get the current value, but I'm really not able to spot the issue
You need to do this:
var principal = $(this).find('td.principal :input').val();
to get the value of the input element inside the table cell with class principal.
Also, as per the .val() API Documentation :-
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of elements, the .val() method returns an array
containing each selected option; if no option is selected, it returns
null.
Hence, you are getting empty string in console while using your code.
The above function works without any problems on the paymentDate class
only by changing the .val() to .text()
This also explains why you got the correct value after changing the .val() to .text() for the paymentDate table cell, as it does not have any input element inside it.
<td class="principal"><input data-bind="value: princpalPayment"></input></td>
You don't need a closing </input> tag, as input elements are self-closing.
And you just need to target better.
var principal = $(this).find('td.principal input').val();
If you're using KnockoutJS you probably don't need to use jQuery at all. Get the correct value from your ViewModel, something like this:
updateValues = function() {
var details = MyMainViewModel.creditDetails();
for (var i = 0; i < details.length; i++) {
var principal = details[i].princpalPayment();
console.log(principal);
}
};
No dependency on your view, and thus unit testable. In addition, if you put this function in the correct bit of scope (e.g. the observable bound to the data table) you'll have access to all the relevant other observables when you want to use the result.
your not looking for the input value your looking at the td value which clearly doesnt exist
here is a jsfiddle with the fixed jquery
http://jsfiddle.net/krxva/
updateValues = function(){
$("tbody").find("tr").each(function() {
var principal = $(this).find('td.principal').find('input').val();
console.log(principal);
});
};
var principal = $(this).find('td.principal').val();
console.log(principal);
Above willn't work because td has an input element also.
Since you want value of input element inside that td, so use like this :
var principal = $(this).find('td.principal input').val();
// Or use this
var principal = $(this).find('td.principal > input').val();
console.log(principal);
Refer this for understanding

How to select value/innerHTML of a certain <td> within a certain <tr>? Using Javascript only. No jQuery

<table>
<tr>
<td>foo1</td>
<td>bar1</td>
<td><input type="button" id="button1" onClick="get(this);"></td>
</tr>
<tr>
<td>foo2</td>
<td>bar2</td>
<td><input type="button" id="button2" onClick="get(this);"></td>
</tr>
</table>
Goal: To get buttons button1 and button2 to trigger the same function get() which should get the value of the first <td> in the same <tr> the button resides in. Which is, in this case: foo1 and foo2 respectively.
This is a rough outline of the function which should help understand what I'm trying to achieve-
function get(element){
alert(element.tr.first_td.innerHTML);
}
I realize there was a jQuery solution to a similar problem. But I do not understand jQuery well enough to translate it back to JavaScript. If it is possible at all using JavaScript, please show me how.
Crawl up the parentNode twice to get to the tableRow element. From there, access the first td from the HTMLCollection of cells, and get the innerHTML value:
function find( element ) {
alert( element.parentNode.parentNode.cells[0].innerHTML );
}​
Fiddle: http://jsfiddle.net/jonathansampson/WuWnw/
Try this, since you have many tr and td tags right, so, you can do DOM Parsing. But you need to specify one ID for the table to get that table. For now lets call it foo-table.
var table = document.getElementById("foo-table");
var cells = table.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
alert(cells[i].innerHTML);
}
If you don't wanna give an ID and you are sure that there is only one table, then use this:
var table = document.getElementsByTagName("table");
var cells = table[0].getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
alert(cells[i].innerHTML);
}
Enjoy! Hope this helps! :) No jQuery or any other plugin. Pure JavaScript. :)
<table>
<tr>
<td id="button1_value">foo1</td>
<td>bar1</td>
<td><input type="button" id="button1" onClick="get('button1_value');"></td>
</tr>
<tr>
<td id="button2_value">foo2</td>
<td>bar2</td>
<td><input type="button" id="button2" onClick="get('button2_value');"></td>
</tr>
</table>
You shoul identify what you want to get using an ID so that you can easily retrieve it. This also helps prevent the chance of getting erroneous data. If you give the component an id you should be able to use document.getElementById() to get that component.
function get(element){
var obj = document.getElementById(element)
alert(obj.innerHTML);
}

Categories

Resources