Why I can't get the input value - javascript

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

Related

Copy content from <td> into a text box using jQuery

With the code below, I don't seem to be able to just set the textbox to the value of an TD element. What I need to achieve is to populate Enter Refund Amount box with the already present value of Grand Total field above. Nothing else is needed except copying the content from one element to the other.
window.onload = function() {
var src = document.getElementById("grand_total").innerHTML;
dst = document.getElementById("refund_amount").innerHTML;
src.addEventListener('#refund_amount', function() {
dst = src;
});
};
Firstly, #refund_amount isn't a valid event name. Given the context of the code and your goal I would assume that should be click instead. You also need to bind the event handler on the Element reference, not the a string variable containing its innerHTML value. In addition, to set the value of an input element you need to use the value property of the Element directly. Try this:
var src = document.getElementById("grand_total");
var dst = document.getElementById("refund_amount");
src.addEventListener('click', function() {
dst.value = src.textContent;
});
<table>
<tbody>
<tr>
<td>Grand total:</td>
<td id="grand_total">26.58</td>
</tr>
<tr>
<td>Refund amount:</td>
<td><input type="text" id="refund_amount" /></td>
</tr>
</tbody>
</table>

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.

How to compare several td.text() in tr using jQuery

<table>
<tr id="tr1">
<td id="td1"> test1 </td>
<td id="td2"> test2 </td>
<td id="td3"> test1 </td>
<td id="td4"> test3 </td>
</tr>
</table>
Here I have a table with a tr in it and 4 td's.
Now, my question is, how can I compare the td.text() with the other one?
For example:
a loop that takes the text of first td and then compare it with other td's.
If it is the same, then give that td a class.
HERE: td id="td1" should get a class
BUT:
When I'm at the 3e td, the 3e td should get a class.
This code should work for you:
var tds;
$('tr').each(function(i, item){
tds = $(this).find('td');
tds.each(function(j, elem1){
tds.each(function(k, elem2){
if($(elem1)[0] != $(elem2)[0] && $(elem1).text() == $(elem2).text()){
$(elem1).addClass('cl');
}
});
});
});
FIDDLE: https://jsfiddle.net/lmgonzalves/cqa6m6va/1/
You can use this code:
function setClasses(word) {
var tds = $("tr td");
for(var i = 0; i < tds.length; i++) {
if(tds.eq(i).text() === word) {
tds.eq(i).addClass('red');
}
}
}
setClasses("test1");
jQuery selectors will be your friend here. :)
var $container = $("#tr")
$container.children().each(function() {
if (!($(this).hasClass("td")) {
var sTextVal = $(this).text();
var $currTextGroup = $container.children(":contains('" + sTextVal + "')");
if ($currTextGroup.length > 1) {
$currTextGroup.addClass("td");
}
}
});
I'll explain the logic, and then touch on one issue to be aware of . . .
Basically, this code:
Collects all of the the children of the <tr> and loops through them one at a time
If the current child does not already have a class of "td" (if it already has a "td" class, then this text has already been checked for duplicates), it retrieves the text from inside the element and searches for all of the children of the <tr> that contain that same text value
If more than one of the children in the <tr> contain that text, all of those children are given the class of "td"
The one potential issue that this solution could run into is if the text in the current element is present as part of the text in one of its siblings. For example, if the text in one sibling is "the", and it has some siblings that have text values of "then" and "there" and "the end", they will be found by :contains.
If your text values are sufficiently "patterned" (as they are in your example), though, this should not be an issue. If it is an issue, there is a more complex way to do that "common text" selection, but I won't bother with that, unless it is necessary.
If I understand correctly, you want to select the first 'td' in a 'tr' and compare it against the other 'td' in your table. Please try the below code and let me know if it works for you.
HTML (provided by OP)
<table>
<tr id="tr1">
<td id="td1"> test1 </td>
<td id="td2"> test2 </td>
<td id="td3"> test1 </td>
<td id="td4"> test3 </td>
</tr>
</table>
CSS
.color--red { color: red; }
jQuery
$(document).ready(function(){
var first = $("#tr1 :first-child").html();
$('#tr1 :not(:first-child)').each(function() {
if(first == $(this).html()){
$(this).addClass("color--red");
}
});
});
I tried to keep it as simple as possible. The variable first pertains to that first 'td' that you want to use for comparison. Note how the each function operates on 'all elements except the first child in the tr', which clearly will omit the first variable we declared initially. From there it's all about comparing using $(this).html() to grab the value of the currently selected element, against the value obtained from the first variable.
Once this succeeds, simply add a class of your choice. For simplicity's sake, I added my own color--red class to the mix, which should show red color text for the third 'td' element as you suggested in your question post. Enjoy! Let me know if you need anything further.

get jsonArray from table

I have a table and need to build json array. I need value from 1 and 4 column of table.
HTML
<table class="table table-striped" id="development_mapping">
<thead>
<tr>
<th>Visual Feature</th>
<th>Step</th>
<th>Output</th>
<th>Data Feature</th>
</tr>
</thead>
<tbody>
<tr><td>color</td>
<td><select id="sss"><option data-id="528092be144b4fbf65893404" selected="selected">first-step</option><option data-id="52809373144b4fbf6589340c">kmeans</option></select></td>
<td><select id="ooo"><option data-id="output" selected="selected">output</option></select></td>
<td><input id="value1" class="feature-execution"value="id"></td></tr></tbody>
</table>
Here is my solution, a function to made an json array from table
JAVASCRIPT
var jsonArray = {};
$('#development_mapping').find('tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});
I have done, but not understand, why I get " " from value of 4 column. I mean, why variable in variable is always getting " "
This is my DEMO
Your selector: $('#development_mapping').find('tr') is selecting all <tr> tags in the table. Even the one in the <thead>! The <thead> doesn't have <td> tags, so that's where the " " is coming from.
Try this:
$('#development_mapping').find('tbody tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});
You are using .text() but there is no actual text in your 3rd td tag.
try this maybe?
variable : $(this).find('td:eq(3) input').val()
There are 2 problems with your code.
Remove the surrounding <tr> in your table head definition.
Use this to access input value
variable: $(this).find('td:eq(3) > input').first().val()
$.find() will return a collection and you'll need to get the first object of the collection for further use. Plus, you'll need to search for input inside the cell, not the cell itself.
Here is the working fiddle: http://jsfiddle.net/toshkaexe/7q3KP/

using each method in jquery

I have a table which has input checkboxes.
When user selects checkbox I'm saving this value attribute to an array...so the user is clicking, checking and unchecking and after some time he will press the button.
In the button click event I'm trying to iterate through each of the records and check if the each input[type="checkbox"] has the same value as the one in the array, so if the values are the same then I will read all the td values from that row.
This is my code:
$('#something').click(function(){
$( "tr td input" ).each(function(index) {
//selected is an array which has values collected from the checked checkboxes..for example [2,3]
for(var i=0;i<selected.length;i++)
{
if($(this).val()==selected[i][0].value)
{
alert($('tr').eq(index).find('td').eq(1).text());
}
}
});
});
And html code:
<table>
<tbody>
<tr>
<td><input type="checkbox" value="on"></td>
<td>ID</td>
<td>Name</td>
</tr>
<tr>
<td><input type="checkbox" value="0"></td>
<td>1</td>
<td>John</td>
</tr>
<tr>
<td><input type="checkbox" value="1"></td>
<td>2</td>
<td>Steve</td>
</tr>
</tbody>
</table>
So for example if I have value [1] in the array. How can I get all the row information from that? My code is not working. Any idea?
I created a plunk that iterates over each input, reads the values and writes them to an array:
var checkBoxCollection = new Array();
var cb = {};
$("button").click(function(){
$("input").each(function(index, el){
id = $(el).attr("id");
val = $(el).val();
isChecked = $(el).is(':checked');
console.log(index, id, val);
checkBoxCollection.push({'id': id, 'val': val, 'isChecked': isChecked});
}); // each
console.log(checkBoxCollection);
}); // button.click
You could use this way to select the cell value as soon as the button is clicked and would only have to test if the box was checked. To learn how to use the console and the chrome dev tools you may take a look at this 7 minute video
Update with one checkbox for all
In my updated plunk you can see that i use two different selectors
// using different selector - see my comment and tell me if you can not do that
Select all <input class="cbAll" type="checkbox" id="cbAll" value="on">
// and each checkbox like this
<input class="cb" type="checkbox" id="cb0" value="0">
And the javascript
$("input.cbAll").click(function(){
$("input.cb").each(function(index, el){
// javascript ternary operator is optional this switches each checked state
$(el).is(':checked')
? $(el).prop('checked', false)
: $(el).prop('checked', true);
}); // each
});
Update including the copy of the text inside the <td>
In this plunk the text from the cells in the same tablerow of the checbox is copied into the array. The relevant code are these lines
isChecked = $(el).is(':checked');
if(isChecked){
var cells = $(el).parent().parent().children();
var cellId = cells.eq(1).text();
var cellName = cells.eq(2).text();
checkBoxCollection.push({'id': id, 'val': val
, 'isChecked': isChecked
, 'cellId': cellId
, 'cellName': cellName});
console.log(index, id, val, cellId, cellName);
}
In the screenshot you can see that the values of each checked textbox are copied.
As far as i can tell i solved all your questions:
use of jquery each to iterate over checkboxes
copy the text of cells within a tablerow into an array if the checkbox of that row is checked
If i understood your questions not fully please clarify what you would like to know.
It appears that the condition if($(this).val()==selected[i][0].value) is not true.
If it is a simple array, you don't need .value in the end. Simply compare with selected[i][0]
if($(this).val()==selected[i][0])

Categories

Resources