jQuery traversing and finding textboxes - javascript

If I am looping through elements in a table - say a hidden field of class "pmtos" - how do I get a reference to the text field (input) within the same cell in the table?
jQuery is:
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this).val();
//
//find text box in same cell - and populate with some value
//
//
});
Thank you for any guidance in getting this working.
Mark

Here's a solution to the question before it was edited (as requested):
$('#allocate').click(function () {
var recd = parseFloat( $('#pmtRecd').val() );
$('input.pmtallocated').each(function() {
var value = parseFloat( $(this).parent().prev().text() );
this.value = (recd >= value) ? value : recd;
recd = recd - this.value;
if (recd == 0) {
return false;
}
});
});
Note: This doesn't rely on the hidden input. It takes the text from the td in the second column.
Here's the fiddle
To answer the question post-edit
You can use siblings('.pmtallocated') or prev('.pmtallocated') to get the input. Using siblings() would probably be the better of the two as it doesn't rely on pmtallocated coming directly before pmtos in the markup:
$(this).siblings('.pmtallocated').val()

Try
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this);
var cell = os.parent(); // gets the parent, i.e. the table cell
var input = cell.find('input')[0];
});

You could use $(this).closest('input')

Check this out. may works for you.
$(".pmtos").each(function () {
var os = $(this).val();
var input = $(this).closest('td').find('input[type=text]');
});

Related

Form values are overwritten after change

I have a form that shows up when each row in a table is double clicked. The values of this form can be updated and the form should be submitted with all row changes. But each time I double click on a row and edit the values of that form for that row, the previous values I had changed get overwritten. In order to work around this, I tried adding all the changes to a map with the row id as the key and the values of the form as the value. But the form still won't update with the new values. Here is a fiddle to demonstrate what I mean:
https://jsfiddle.net/4fr3edk7/2/
If I double click on the row that says "Adam Smith" and change that name to John Doe, when I double click on the second row and then double Click on "Adam Smith" again, it should say "John" on the first textbox and "Doe" on the second one. But the new value never seems to save.
This code snippet loops through each key, then loops through each value of that key:
for(var i = 0; i<key.length; i++){
var getval = globalchanges[key[i]];
for(var k=0; k<getval.length; k++){
$("#input1").val(getval[0]);
$("#input2").val(getval[1]);
}
}
How can I get the new changes to save? (The table rows don't have to show the changes, just the textbox values). Any help would be appreciated.
First, as mentioned by #Taplar you are binding the click event multiple times. Your approach is close enough, the idea of storing the changes is valid. You should have 2 functions, store the changes on button click and the second one to retrieve the changes by id.
Updated Fiddle
This function will get the values of the form and will store in on a global object
function setMap(id){
var firstrow = $("#input1").val();
var secondrow = $("#input2").val();
globalchanges[id] = [firstrow,secondrow];
}
This other function will check if the global object has values for the passed id, if not, it will use the values on the row
function getMap(id, tr){
if(globalchanges[id] != undefined && globalchanges[id].length == 2){
$("#input1").val(globalchanges[id][0]);
$("#input2").val(globalchanges[id][1]);
}
else{
$("#input1").val($(tr).find('td').eq(1).text());
$("#input2").val($(tr).find('td').eq(2).text());
}
}
Please note there are also changes on the dbclick and click events, they should be separated
$("#table tr").dblclick(function(){
$("#txtbox-wrapper").css({"display" : "block"});
var id = $(this).find('td').eq(0).text();
$('#id').val(id);
getMap(id,this);
});
$("#savebtn").click(function(){
var id = $('#id').val();
setMap(id);
});
And that we added and additional input to store the id on the form.
You are going to need to rethink your logic because of this part
$("#table tr").dblclick(function(){
$("#txtbox-wrapper").css({"display" : "block"});
var id = $(this).find('td').eq(0).text();
$("#input1").val($(this).find('td').eq(1).text());
$("#input2").val($(this).find('td').eq(2).text());
$("#savebtn").click(function(){
addToMap(id);
});
});
-Every time- you double click a table row you are adding a new click binding to the savebtn element. This means if you double click both rows, when you click that button it will execute addToMap for both ids. You may have other issues with your logic relying on only two other inputs for multiple rows, but this double/triple/+ binding is going to bite you.
There are few changes required in your logic as well as implementation.
1: Do not bind save event inside row click.
2: You are selecting the value in row double click event from td element. You need to update this element to keep your logic working
3: Keep track of which row is getting updated.
Updated Code
var globalchanges = {};
var rowSelected = null;
$("#table tr").dblclick(function() {
$("#txtbox-wrapper").css({
"display": "block"
});
rowSelected = $(this).find('td').eq(0).text();
$("#input1").val($(this).find('td').eq(1).text());
$("#input2").val($(this).find('td').eq(2).text());
});
$("#savebtn").click(function() {
addToMap(rowSelected);
});
function addToMap(row) {
var array = [];
var changes = {};
var firstrow = $("#input1").val();
var secondrow = $("#input2").val();
array.push(firstrow, secondrow);
globalchanges[row] = array;
makeChanges(row);
}
function makeChanges(row) {
var key = Object.keys(globalchanges);
console.log(key);
$("#table tr td").each(function(k, v) {
if ($(v).text() == key) {
$(v).next().html(globalchanges[row][0]);
$(v).next().next().html(globalchanges[row][1]);
globalchanges = {};
}
});
}
Working fiddle : https://jsfiddle.net/yudLxsgu/

How to give a unique id for each cell when adding custom columns?

I wrote following code to add a custom column to my table. but i want to add a unique id to each cell in those columns. the format should be a(column no)(cell no>)
ex :- for the column no 4 :- a41, a42, a43, ........
So please can anyone tell me how to do that. Thank You!
$(document).ready(function ()
{
var myform = $('#myform'),
iter = 4;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
var colName = $("#txtText").val();
if (colName!="")
{
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td>'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
}
});
iter += 1;
});
});
You seem to have code that's modifying the contents of the table (adding cells), which argues fairly strongly against adding an id to every cell, or at least one based on its row/column position, as you have to change them when you add cells to the table.
But if you really want to do that, after your modifications, run a nested loop and assign the ids using the indexes passed into each, overwriting any previous id they may have had:
myform.find("tr").each(function(row) {
$(this).find("td").each(function(col) {
this.id = "a" + row + col;
});
});
(Note that this assumes no nested tables.)
try this
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'">'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'"><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
you just have to define and iterate the column_no and cell_no variable
When all other cells are numbered consistently (for example using a data-attribute with value rXcX), you could use something like:
function addColumn(){
$('table tr').each(
function(i, row) {
var nwcell = $('<td>'), previdx;
$(row).append(nwcell);
previdx = nwcell.prev('td').attr('data-cellindex');
nwcell.attr('data-cellindex',
previdx.substr(0,previdx.indexOf('c')+1)
+ (+previdx.substr(-previdx.indexOf('c'))+1));
});
}
Worked out in this jsFiddle

How to find td element id with value x?

I need to find exactly that td row which contains value priview '2'
I know the td row first half id, but it is dynamic: MovementNumber_M_* (Where * can be from 1 to Milion)
So need to search all rows from MovementNumber_M_1 to MovementNumber_M_9999 which contains MovementNumber_M_*.value=2 and returning directly that td row id which contained that value.
Can you help me? Thanks in advice.
Right and helpfull answers guaranteed ;)
//EDIT
function DgIdOnClick (e,r){
var MovementNumber = document.getElementById(e).value;
//alert('MovementNumber: '+MovementNumber+' Type :'+r);
var result = $('[id^="MovementNumber_M_"][value='+MovementNumber+']');
result.each(function(){
alert($(this).attr("id"));
});
}
OK value=1 is for init and thats why are alerting all rows but if value is 2 then jq is not finding him WHY ?
The function DgIdOnClick is inicialized #
$( document ).ready(function() {
var SecondDiagnosis=$( "span[id^='lov_Dg2Id_D_']" );
var SpanBlock2=SecondDiagnosis.find('a');
var eventH2=SpanBlock2.attr( "onclick" );
SpanBlock2.attr("onclick", "DgIdOnClick(document.getElementById('MovementNumber_D_'+parentElement.getAttribute('id').substring(12)).id,2);"+eventH2);
var FirstDiagnosis=$( "span[id^='lov_DgId_D_']" );
var SpanBlock=FirstDiagnosis.find('a');
var eventH=SpanBlock.attr( "onclick" );
SpanBlock.attr("onclick", "DgIdOnClick(document.getElementById('MovementNumber_D_'+parentElement.getAttribute('id').substring(11)).id,1);"+eventH);
});
function DgIdOnClick is on other .js file
If i am alerting IN DgIdOnClick alert(document.getElementById('MovementNumber_M_2').value)//MovementNumber_M_2 Then value is 2 but jq is not founding it
This alerts the ID's of each row containing that value
var result = $('[id^="MovementNumber_M_"][value="2"]');
result.each(function(){
alert($(this).attr("id"));
});
http://jsfiddle.net/q8QaG/
Update:
This alerts the id of all inputs with the value of 2, even on input update
$("#button").click(function(){
$('[id^="MovementNumber_M_"]').each(function(){
var value = $(this).val();
if(value == 2){
alert($(this).attr("id"));
}
});
});
http://jsfiddle.net/q8QaG/3/
$('#TableID').find('td').filter(':contains("SOME_TEXT")');
The previous 2 answers have the string encoding similarly incorrect. This should be it:
$('[id^="MovementNumber_M_"][value="2"]');
You can use combination of Attribute Starts With Selector [name^="value"] and Attribute Equals Selector [name="value"]
var myElement= $("[id^='MovementNumber_M_'][value=2]");
As per comment, if you need id use attr()
var myElementId = $("[id^='MovementNumber_M_'][value=2]").attr('id');

Using custom attribute jQuery selectors with dropdown select (take 2)

This issue is making me want to smash my computer. I have a form, I want to calculate values from selections on the form. I have two jsfiddles here, I really want to have it so I can make selections, then calculate on click. But I can't even get the form to work on click. So the other fiddle uses on change and keyup functions. There is an issue on that form as well. If you change the first select to "option 2", you'll see the value for that select ends up being "1.379999999996" instead of "1.38". Why is this happening?
Fiddle with click function
JS:
$('#submit').click(function(){
var price=$(this).find("option:selected").attr('data-price');
var ink=$('#ink').val();
var loc1=$('#loc1').val();
var res= price*1 + ink*1 + loc1*1 ;
$('#bleh').val( res || 0 );
});
Fiddle with change and keyup functions
JS:
$('#ink, #loc1, .sel').on('keyup change',function(){
var price=$('option:selected', this).attr('data-price');
var ink=$('#ink').val();
var loc1=$('#loc1').val();
var res= price*1 + ink*1 + loc1*1 ;
$('#bleh').val( res || 0 );
});
Your selector $(this).find("option:selected") is wrong as this here points to the #submit button, so you need to find out the select element using its id #style
$('#submit').click(function(){
var price=$('#style').find("option:selected").attr('data-price');
var ink=$('#ink').val();
var loc1=$('#loc1').val();
var res= price*1 + ink*1 + loc1*1 ;
$('#bleh').val( res || 0 );
});
Demo: Fiddle

JQuery DataTables How to get selected rows from table when we using paging?

For example I selected (checked) 2 rows from second page than go to first page and select 3 rows. I want get information from 5 selected rows when I stay at first page.
$('tr.row_selected') - not working
Thanks.
Upd.
I created handler somthing like this:
$('#example').find('tr td.sel-checkbox').live("click", function () {
/*code here*/
});
But right now when click event is hadle the row from table is hidding. I think it may be sorting or grouping operation of DataTables. Any idea what I must do with this?
When a checkbox gets selected, store the row information you want in a global object as a Key-Value pair
I don't remember specifically how i did it before but the syntax was something like
$('input[type=checkbox]').click(function()
{
var row = $(this).parent(); //this or something like it, you want the TR element, it's just a matter of how far up you need to go
var columns = row.children(); //these are the td elements
var id = columns[0].val(); //since these are TDs, you may need to go down another element to get to the actual value
if (!this.checked) //becomes checked (not sure may be the other way around, don't remember when this event will get fired)
{
var val1 = columns[1].val();
var val2 = columns[2].val();
myCheckValues[id] =[val1,val2]; //Add the data to your global object which should be declared on document ready
}
else delete myCheckValues[id];
});
When you submit, get the selected rows from your object:
for (var i = 0; i < myCheckValues.length; i++)
...
Sorry, haven't done JS in a long time so code as is might not work but you get the idea.
$('#example').find('tr td.sel-checkbox').live("click", function () {
var data = oTable.fnGetData(this);
// get key and data value from data object
var isSelected = $(this).hasClass('row_selected');
if(isSelected) {
myCheckValues[key] = value;
checkedCount++;
} else {
delete myCheckValues[key];
checkedCount--;
}
});
.....
On submit
if(checkedCount > 0) {
for(var ArrVal in myCheckValues) {
var values = myCheckValues[ArrVal]; // manipulate with checked rows values data
}
}

Categories

Resources