I want to select a input field in next TD with Jquery. I can not use ID or class because the table's row can be add or removed.
like ,
<tr>
<td><input type='text' name='price[]' onkeyup = 'getTest(this)' /> </td>
<td><input type='text' name='qty[]' onkeyup = 'getPrice(this)' value='1' /> </td>
<td><input type='text' name='amount[]' /> </td>
</tr>
function getTest(obj){
//I want to select qty[] and amount[]
}
function getPrice(obj){
//I want to select price[] and amount[]
}
anybody know how to select the input fields, please help~!
Thanks
working demo of your expected behavior of your webpage.
Chinmayee's answer is much better than this one, but if you don't want to change any of your HTML mark-up, you can simply drop this into your JavaScript and it will work:
function getTest(obj) {
var tr = $(obj).closest('tr');
var qty = tr.find('input[name="qty[]"]');
var amount = tr.find('input[name="amount[]"]');
console.log('qty: ' + qty.val());
console.log('amount: ' + amount.val());
}
function getPrice(obj) {
var tr = $(obj).closest('tr');
var price = tr.find('input[name="price[]"]');
var amount = tr.find('input[name="amount[]"]');
console.log('price: ' + price.val());
console.log('amount: ' + amount.val());
}
But the reason why Chinmayee's answer is better than mine is because it uses unobtrusive JavaScript, and it also uses event delegation, so it will perform better.
Here's a possible solution for your problem (assuming you want amount to be price * qty):
$(document).ready(function(){
$('[name="price[]"], [name="qty[]"]').live('keyup', function(){
var inputs = $(this).closest('tr').find('input');
$(inputs[2]).val($(inputs[0]).val()*$(inputs[1]).val());
});
});
Your getTest() and getPrice() methods are no longer required with this solution and you can also drop the onkeyup="..." attributes on the input elements.
See here for a working demo.
Related
i need put value of general price
for all inputs but only take the value for 1st input.
Code :
<script type="text/javascript">
$('#GPrecio').change(function () {
$('#Precio').val($(this).val());
});
</script>
HTML :
<input type='text' size='3' name='GPrecio' id='GPrecio'>
$table.="<td>Precio : <br><input type='text' size='3' name='Precio[]' id='Precio'></td>";
Thank for answers and the time.
This will take the value of #GPrecio and apply it to all input name=Precio[] elements
$('#GPrecio').blur(function () {
$('[name="Precio[]"]').val($(this).val());
});
Also, if you have more than one element with id="Precio", that is a problem. Better to not use IDs unless you need them. Is there a reason you're using the same ID for each? You would be better off using a data-attribute, like <input type='text' size='3' name='Precio[]' data-inputtype='Precio'>, in which case your function could be refined to:
$('#GPrecio').blur(function () {
$('[data-inputtype="Precio"]').val($(this).val());
});
Suggest you to use classes instead of ids if you are going to use the same value.
Your input row could be like this:
<input type='text' size='3' name='Precio[]' class='Precio'>
Assuming Precio is the class name for all your inputs in the table row.
$('#GPrecio').change(function () {
let newValue = $(this).val();
$(".Precio").each(function() {
$(this).val(newValue);
})
});
As you can't use multiple same id, change it to class first:
<input type='text' size='3' name='Precio[]' class='Precio'>
And then jQuery trigger:
<script type="text/javascript">
$('#GPrecio').change(function () {
var gpval = $(this).val();
$('.Precio').each(function( index ) {
$(this).val(gpval);
});
});
</script>
I used for loop to copy the table to n times. The code below works only in first table. How can i get to work in all tables?. I am a beginner.
function copy() {
var text1 = document.getElementById("Name1").value;
document.getElementById("Name2").value = text1;
var text2 = document.getElementById("Name3").value;
document.getElementById("Name4").value = text2;
}
<td rowspan="3" style="height:100px;">Name <input type="text" name="Emp name" placeholder="enter your name" id="Name1" /><br> ID <input type="id" name="Emp Id" placeholder="enter id" id="Name3"> </td>
<tr id="p001">
<td colspan="10" style="border:1px solid #ffffff;height:150px;"><input type="button" value="Get data" onclick="copy();" /><label for="text"> Name : <input type="text" id="Name2"></label>
<label for="text"> ID : <input type="id" id="Name4"></label> </td>
</tr>
ID's should always be unique. When using duplicate ID's it will only work on the first one and ignore the rest. By pushing in the selector to the function you can reuse your function for multiple tables.
https://jsfiddle.net/m5aqdswe/
onclick="copy('Name');"
function copy(selector) {
var text1 = document.getElementById(selector + "1").value;
document.getElementById(selector + "2").value = text1;
var text2 = document.getElementById(selector + "3").value;
document.getElementById(selector + "4").value = text2;
}
Hope this helps
EDIT TO HELP WITH YOUR FIDDLE MISTAKE
After checking your code I can see that you haven't implemented my fix. You have an onclick on the button calling copy();. You're not passing in any arguments so your JS is static. So when you add another table you're creating duplicate ID's.
When searching for an ID document.getElementById("Name1") it will search through the DOM until it finds that first id="Name1" and then stop. That is why your second table never works.
To fix that we need to push in your ID name to the function so that the JS becomes dynamic. copy('Name') where "Name" is the first part of your ID. The numbers will still be used.
In the function you need to grab that arguments by passing it in to the function and calling it whatever you like. I chose 'selector' because it is most descriptive. onclick="copy(selector)"
No the function will replace all the 'selector' variables with the string you passed through, namely "Name" so document.getElementById(selector + "1") will actually be document.getElementById("Name1"). This way you can create as many clones as you like but remember to change the clone table ID's and pass in the correct argument to the onclick.
Here is your fixed fiddle. https://jsfiddle.net/3shjhu98/2/
Please don't just copy, go see what I did. You'll need to fix your clone function to use dynamic arguments instead of static ones.
function check() {
var rowCount = $('table.mytable tbody tr');
for (var index = 0; index < rowCount.length; index++) {
var tr = $('table.mytable tbody tr')[index];
var td = $(tr).find('td');
for (var j = 0; j < rowCount.length; j++) {
copy('table.mytable tbody tr[data-index=' + index + '] td[data-index=' + j + ']');
}
}
}
function copy(selector) {
var val_1 = $(selector).find('input:first').val();
$(selector).find('input:last').val(val_1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="mytable">
<tbody>
<tr data-index="0">
<td data-index="0">
<input type="text" onblur="check()" />
<input type="text" />
</td>
</tr>
</tbody>
</table>
Hi. try it...
I think you need to pass table selector like [ table.className ] etc. then you find input text box and get the value this and paste into another text box.
Like this.
///it mean you pass first table row of first table data.
copy('table.className tbody tr[data-index=1] td[data-index=1]');
function copy(selector) {
var val_1 = $(selector).find('input#Name1').val();
$(selector).find('input#Name2').val(val_1);
}
<tbody id="dailysale_tbody">
<tr class="items">
<td><select id="items_select" name="dailysale[luitem_id]"><option value=""></option></select></td>
<td><select id="brands_select" name="dailysale[lubrand_id]"><option value=""></option></select></td>
<td><select id="models_select" name="dailysale[lumodel_id]"><option value=""></option></select></td>
<td><input class="texts" id="dailysale_qty" name="dailysale[qty]" type="text" /></td>
<td><input class="texts" id="dailysale_price" name="dailysale[price]" type="text" /></td>
<td><input class="texts" id="dailysale_total" name="dailysale[total]" type="text" /></td>
<td><input type="checkbox" class="delete_row"></td>
</tr>
$(function() {
$('#dailysale_qty, #dailysale_price').keyup(function() {
var last_item = $('.items').find('#dailysale_qty');
var qty = last_row.find('#dailysale_qty').val();
var price = last_row.find('#dailysale_price').val();
var sub_total = last_row.find('#dailysale_total');
var s_total = qty * price;
if (isNaN(s_total)) {
sub_total.val('0');
}
else
sub_total.val(s_total);
});
});
I am able to perform calculations on this row. However, when I dynamically add rows with jquery, calculations are not working on the other rows.
When the calculating function is bind a button onclick, everything works well. But not on input keyup as required. I want to perform calculations on the new added row with onkeyup on qty and price input fields.
Note than upon cloning, the ids are stripped of the current row and assigned to the new row for reference.
You probably not registering keyup function when you adding new row.
You should do :
$('#dailysale_qty, #dailysale_price').unbind('keyup').keyup( function(...
Every time you adding new row.
#Nosyara The suggested line of code isn't working. Here is how am adding new rows. The commented line is what you suggested.
$(function(){
$('#newitembtn').click(function(){
//$('#dailysale_qty, #dailysale_price').unbind('keyup').keyup(function() {
var last_row = $('#dailysale_tbody').find('tr:last');
var newrow = last_row.clone();
last_row.find('#items_select').removeAttr('id');
last_row.find('#brands_select').removeAttr('id');
last_row.find('#models_select').removeAttr('id');
last_row.find('#dailysale_qty').removeAttr('id');
last_row.find('#dailysale_price').removeAttr('id');
last_row.find('#dailysale_total').removeAttr('id');
newrow.find('#items_select').val('');
newrow.find('#brands_select').val('');
newrow.find('#models_select').val('');
newrow.find('#dailysale_qty').val('');
newrow.find('#dailysale_price').val('');
newrow.find('#dailysale_total').val('');
last_row.after(newrow);
});
});
});
here is my sample code
<table id="accessListTable">
<tr class="ui-grid groupHead">
<td><input type="checkbox" class="groupHeadCheck"/></td>
</tr>
<tr>
<td><input type="checkbox" id="1"/></td>
</tr>
<tr>
<td><input type="checkbox" id="2"/></td>
</tr>
<tr>
<td><input type="checkbox" id="3"/></td>
</tr>
<tr class="ui-grid groupHead">
<td><input type="checkbox" class="groupHeadCheck"/></td>
</tr>
<tr>
<td><input type="checkbox" id="4"/></td>
</tr>
</table>
E.g, When the checkbox in first row with class groupHeadCheck, all the checkboxex of id 1, 2 and 3 will also be checked.
And if all the checkboxes of 1, 2, and 3 are already checked, the checkbox in first row will be checked.
Please any help!
You can add a click handler to the group checkbox then inside the handler you can find its tr element and the tr's next sibling element till the next occurrence of tr.groupHead
$(function ($) {
$(".groupHeadCheck").on("click", function (event) {
$(this).closest('tr').nextUntil('tr.groupHead').find('input[type="checkbox"]').prop('checked', this.checked)
})
});
Demo: Fiddle
I am sure it can be done in a prettier manner, but this is the basic idea:
$("table tbody").on("change", "input[type=checkbox]", function (e) {
var currentCB = $(this);
var isChecked = this.checked;
if (currentCB.is(".groupHeadCheck")) {
var allCbs = currentCB.closest('tr').nextUntil('tr.groupHead').find('[type="checkbox"]');
allCbs.prop('checked', isChecked);
} else {
var allCbs = currentCB.closest('tr').prevAll("tr.groupHead:first").nextUntil('tr.groupHead').andSelf().find('[type="checkbox"]');
var allSlaves = allCbs.not(".groupHeadCheck");
var master = allCbs.filter(".groupHeadCheck");
var allChecked = isChecked ? allSlaves.filter(":checked").length === allSlaves.length : false;
master.prop("checked", allChecked);
}
});
and if you need to run the code to force the check all state
$(".groupHead").next().find("[type=checkbox]").change();
JSFiddle
This would check all if the first is checked (or uncheck all)
$(document).on('click', '.groupHeadCheck',function() {
$(this).closest('tr').nextUntil('tr.groupHead').find('input[type="checkbox"]').prop('checked', $(this).prop('checked'))
});
you could fiddle a bit with your classes (or IDs) to make it right for you
I know this is already answered, but I wanted a more generic way of doing this. In my case, I wanted to check all in a column until I hit a new group. I also had 3 columns with checkboxes. The ones in the first checkbox column all had names starting with "S_", the second "A_" and the third "C_". I used this to pick out the checkboxes I wanted. I also didn't name the heading checkboxes that were used to do the "check all" so it would stop when it hit the next groupings row.
You could use the class name to apply the same logic.
First, here is what a check all checkbox looked like:
<td>
<input type="checkbox" onchange="checkAll(this, 'S_');" />
</td>
Then the javascript function it calls when clicked:
function checkAll(sender, match)
{
var table = $(sender).closest('table').get(0);
var selector = "input[type='checkbox'][name^='" + match + "']";
for (var i = $(sender).closest('tr').index() + 1; i < table.rows.length; i++)
{
var cb = $(table.rows[i]).find(selector).get(0);
if (cb === undefined)
break;
if ($(cb).is(':enabled'))
cb.checked = sender.checked;
}
}
So it will search each subsequent row for a checkbox with the name starting with "S_". Only the checkboxes the user has rights to will be changed. I was going to use $(td).index() to find the right column, but this didn't work out because some rows had colspan's greater than 1.
I have simple form with 2 textfield Name and Phone and can add new field when click Add new button. You can refer here jsfiddle .
My problem is how to add new textfield without press Add New button? When user fill up Text Input name and Text Input Phone new row <tr class="person"> will automatically added.
My second problem is I'm not sure how to write code for delete.
UPDATE : I also want to set maximum clone, can this be done?
If by "fill up" you mean "when the user enters as many characters as the Phone field allows" then you can add a maxlength="10" attribute to the input (setting the value as appropriate):
<input type="text" name="phone[]" id="phone" maxlength="10"/>
...and add a handler to the keyup event that checks whether the current value has reached the maxlength:
$('input[name="phone\[\]"]').keyup(function() {
if (this===$('input[name="phone\[\]"]').last()[0]
&& this.value.length===+$(this).attr("maxlength")) {
$("#add").click();
}
});
Note that you probably only want to do this test if the user is typing in the last row, hence the first part of the if test above.
Also you probably want the newly cloned fields to be blank, so you can do this within your add function:
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last')
.find("input").val("");
To set a maximum number of rows you can put a test in your add function:
$("#add").click(function() {
var $lastRow = $('#mytable tbody>tr:last');
if ($lastRow.index() < 10) { // set maximum rows here
$lastRow.clone(true).insertAfter($lastRow).find("input").val("");
}
return false;
});
Note also that you don't need to give those inputs an id attribute, but if you do you shouldn't copy it when you clone because id should be unique.
For a delete function, add a delete button to each row:
<td><input type="button" class="deleteRow" value="Delete"/></td>
...and then:
$("#mytable").on("click","input.deleteRow", function(){
if ($("#mytable tr").length > 2) // don't delete the last row
$(this).closest("tr").remove();
});
Demo: http://jsfiddle.net/3J65U/15/
I would expand on enclares - I would use .blur() for each textbox , and each time check and make sure each value is not "" - that would make sure both are filled
Then in jQuery:
$(document).ready(function() {
$(".phone").blur(function() {
var phonetxt = $('.phone'.val();
var nametxt = $('.name').val();
if ( phonetxt != "" && nametxt != "" ){
$(this).closest('tr').clone(true)
.insertAfter('#mytable tr:last')
.find('input').val('').first().focus();
});
}
$(".name").blur(function() {
var phonetxt = $('.phone'.val();
var nametxt = $('.name').val();
if ( phonetxt != "" && nametxt != "" ){
$(this).closest('tr').clone(true)
.insertAfter('#mytable tr:last')
.find('input').val('').first().focus();
});
}
});
You could do it on blur as well as the add new button. Also be careful with duplicated id's, use classes instead:
<tr class="person">
<td><input type="text" name="name[]" class="name" /></td>
<td><input type="text" name="phone[]" class="phone" /></td>
</tr>
Then in jQuery:
$('.phone').blur(function() {
var ppl = $('.person').length;
if ( this.value && ppl < 5 ) { // Max 5 people
$(this).closest('tr').clone(true)
.insertAfter('#mytable tr:last')
.find('input').val('').first().focus();
$(this).off('blur');
}
});
Demo: http://jsfiddle.net/elclanrs/YEBQt/ (tab from input to input)