Loop through multiple form and get their input values in jquery - javascript

I am dynamically generating forms using jquery. How can I loop through all the forms and alert their input values.
CODE FOR GENERATING FORMS
$.ajax({
method: 'GET',
url: 'api/PayrollSystem/GetEmployeeSalaryAmount?AdminId=' + 1,
success: function(data) {
if (Object.keys(data).length == 0) {
$.alert({
title: 'Saved',
content: 'Account Number Saved!',
});
var row = ('<tr ><td colspan="3" text-align="center"> <b>No Registered Users</b></td></tr>');
$('.EmpTable').append(row);
} else {
$.each(data, function(index, value) {
var rows = ('<div id="form_div"><form method="post"><table class="table table-hover employee_table' + index + ' " align=center><thead><tr><td><b>Employee</td> <td><b>Amount</td></tr></thead><tbody><tr><td><b>' + value.FullName + '</b></td><td><input type="hidden" class="form-control Leavename" name="Leavename[]" value="Basic" placeholder="Enter Leave Name"> <input readonly class="form-control LeaveAmount" type="number" name="LeaveAmount[]" value=' + value.SalaryAmount + ' /><input class="form-control EmpId" type="hidden" name="Id[]" value=' + value.Id + ' /></td></tr><tr id="row' + index + 1 + '"><td><input type="text" class="form-control Leavename" name="Leavename[]" placeholder="Enter Leave Name"> </td><td> <input type="number" class="form-control LeaveAmount" name="LeaveAmount[]" placeholder="Enter Leave Amount"></td> </tr></tbody> </table> <input type="button" class="btn btn-success addRow" onclick="add_row(' + index + '); " value=" + Add More Payroll Item"></form> </div><hr />');
$('.EmpTable').append(rows);
});
}
}
});
WHERE I TRIED GETTING THE VALUES OF THE INPUT FIELD BY ID
$('#saveAdj').click(function() {
$('form').each(function() {
alert($('.EmpId').val());
});
});

$('#saveAdj').click(function() {
$('form').each(function() {
var thisForm = this;
alert($('.EmpId', thisForm).val());
});
});
$('selector', container) will help you to search from container only;

You aren't providing any context for where to find .EmpId.
The callback function passed to the each() method will automatically be passed values for accessing the collection being enumerated. If you use those argument values, you can provide that context by passing it as the second argument to the JQuery object.
$('#saveAdj').click(function() {
// JQuery's .each() method will automatically pass 3 arguments
// to the provided callback function:
// a reference to the index position of that element
// a reference to the element being enumerated at the moment
$('form').each(function(index, element) {
// The element argument can be passed as the second argument to
// the JQuery object (after the selector) to provide context for where to search
alert($('.EmpId', element).val());
});
});

Related

Find sum of automatically generated input fields value

I have a button that when you click it appends an input fields in a div,
this values comes from ajax request.
var i = 0;
$(document).on('click', '#add-btn', function() {
++i;
var user = $('#productName').attr('value');
var price = $('#price').attr('value');
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "getPrice.php",
data: {user:user, price:price},
dataType: "html", //expect html to be returned
success: function(response){
$("#dynamicAddRemove").append('<tr style="height:5em;" id="tr"><td><input name="productName['+i+']" readonly class="form-control" type="text" value="'+user+'"/></td><td><div class="quantit buttons_added"><input class="form-control quantity" id="number" type="number" name="qty[' + i + ']" value="1"/></div></td><td><input class="form-control amount" type="text" readonly value="'+price+'" name="price[' +i +']"/></td><td class="td"><input type="text" value="'+price+'" name="subTotal['+i+']" placeholder="Subtotal" class="form-control subtotal" id="grandTotal" readonly/><td><button type="button" name="add" class="btn btn-danger remove-tr">-</button></td>');
}
});
});
after appending the input fields now i want to add every value of the subTotal to get grandTotal.
var iSum = 0;
$(document).on('mouseout', '.amount , .quantity, #addvalue', function() {
iSum = 0;
$('input[name="subTotal[]"]').each(function(){
var LiSum =parseInt($('input[name="subTotal[]"]').val());
if(LiSum != undefined || LiSum != ''){
iSum+=LiSum;
}
});
$('#sum').html(iSum);
alert(iSum);
});
after successfully appending values, i keep on getting 0 as grandTotal
Replace $('input[name="subTotal[]"]') by $('input[name^="subTotal"]'). This will find all input fields with names starting with "subTotal". The name "subTotal[]" you were originally looking for does not appear anywhere in your markup.

Passing parameter with underscore : Uncaught SyntaxError: Unexpected end of input

I have a function that returns a div when its called.
function docTypetbl(indx) {
return '<div><INPUT TYPE="HIDDEN" NAME="_1_1_15_1_' + indx + '_SavedValue" VALUE="' + document.getElementsByName('_1_1_15_1')[0].value + '"><INPUT CLASS="valueEditable TKL" TYPE="TEXT" ID="_1_1_15_1_' + indx + '" NAME="_1_1_15_1_' + indx + '" VALUE=" ' + document.getElementsByName('_1_1_15_1')[0].value + '" SIZE="32" ONKEYUP = "getTKLResults(event,this.value, myForm,_1_1_15_1,15,"755204_0",1,0)" ONCLICK= "getTKLResults(event,this.value,myForm,_1_1_15_1,15,"755204_0",1,0)"><div ID = "DTKL__1_1_15_1" style="position: absolute;"><table ID = "TKL__1_1_15_1"></table></div></div>';
};
The problem is with the onclick and onkeyup events. The parameter "755204_0" throw errors when used with "".
I tried giving '', but get "Invalid or unexpected token"
Your error is nested double quotes here: "755204_0"
I suggest:
Use template literal
Use data-attribute
simplify oninput="getTKLResults(this)"
then the function can get values and data-attribute from the element
function docTypetbl(indx) {
var val = document.querySelector('[name="_1_1_15_1"]').value;
return `<div>
<input type="hidden" name="_1_1_15_1_${indx}_SavedValue" value="${val}">
<input class="valueEditable TKL" type="text" id="_1_1_15_1_${indx}"
name="_1_1_15_1_${indx}" value="${val}" size="32"
data-code="755204_0" oninput="getTKLResults(this)" />
<div id="DTKL__1_1_15_1" style="position: absolute;">
<table id="TKL__1_1_15_1"></table>
</div>
</div>`;
};

jQuery Change number inside name attribute on cloned row with multiple inputs

I have a form row with 26 inputs on it, some text some select boxes. I have a button that clones the top row, adds an increment to the row number. However i'm struggling to work out how to increment the name and ID of the cloned field elements.
Form:
<tr id="CmasterRow" class="DB1_ROW">
<td><span id="cnumber"> <input type="text" size="2" readonly class="form-control" id="DB1[0][A]" name="DB1[0][A]" data-circuitNumber="0" data-EN="0" value="0"></span></td>
<td>
<div class="input-group">
<input type="text" class="form-control" id="DB1[0][B]" name="DB1[0][B]" data-EN="1">
</div>
</td>
<td>
<div class="input-group">
<input type="text" class="form-control" id="DB1[0][C]" size="2" name="DB1[0][C]" data-EN="2">
</div>
</td>
<td>
<input type="text" class="form-control" id="DB1[0][D]" size="4" name="DB1[0][D]" data-EN="3">
</td>
<td>
<div class="input-group">
<input type="text" class="form-control" id="DB1[0][E]" size="3" name="DB1[0][E]" data-EN="4">
</div>
</td>
<!-- ... etc ... etc ... -->
</tr>
Here's the javascript I have at the moment (the working on that clones the row)
var template = $('#CmasterRow'),
$("#addrow").click(function () {
var row = template.clone();
var n = $("[data-circuitNumber]").length;
row.find('input').val('');
row.find('[data-circuitNumber]').val(n);
row.find('input').attr('name').replace(/\[([0-9]+)\]/g,"[" + n + "]");
row.find('input').attr('id').replace(/\[([0-9]+)\]/g,"[" + n + "]");
row.insertBefore($('#disBoard tbody>tr:last').eq(-1));
// saveData(); - own function not needed for this issue.
return false;
/* Version 1 simple row clone
var row = $('#disBoard tbody>tr:first').clone(true);
var n = $("[data-circuitNumber]").length;
row.find('input').val('');
row.find('[data-circuitNumber]').val(n);
row.insertBefore($('#disBoard tbody>tr:last').eq(-1));
saveData();
return false;
*/
});
I 'think' I'm on the right lines with using the .find and the .replace and the regex. I am just a little stuck of getting it to work. I did get it working (of sorts) with a single form element however that java script has been chopped and changed with the above or i would have included that workings in this post.
Thanks for any help :)
To update an attribute for a node use:
var newValue = 'whatever'
row.find('selector').attr('your attribute', newValue);
Your code takes a value of an attribute, applies regex and then does nothing.
Javascript .replace does not replace anything in the original string and returns a new string with replaced values.
row.find('input').attr('name').replace(/\[([0-9]+)\]/g,"[" + n + "]");
row.find('input').attr('id').replace(/\[([0-9]+)\]/g,"[" + n + "]");
So the above lines basically return new values for id and name. you need to take those values and apply them as suggested by Eriks.
var newId=row.find('input').attr('name').replace(/\[([0-9]+)\]/g,"[" + n + "]");
var newName=row.find('input').attr('id').replace(/\[([0-9]+)\]/g,"[" + n + "]");
row.find('input').attr('id',newId);
row.find('input').attr('name',newName);
row.find('input').attr('id', function (i, val) {
val = val.replace(/\[([0-9]+)\]/g, "[" + n + "]");
return val
});
row.find('input').attr('name', function (i, val) {
val = val.replace(/\[([0-9]+)\]/g, "[" + n + "]");
return val
});
Thanks both for your help, I understand now where i was going wrong. I have completed the task by taking your input and developing the above code

radio btn selection will show select list or text field, then that value querys and displays in another text field

I have a form that when selecting the radio button it will query a database and populate either a select list or change select to a textbox for user input.(mostly working - won't go back to select after textbox - not as important now)
Then I want it to take the value from the select or textbox and put it in a string variable. Then I think I can take it from there. I hope. ( I will use string to query to get other info to populate bib numbers)
Here is my JS/php been trying everything
$(document).ready(function () {
var bibfield = "";
$('#a1').change(function () {
//$('#hiddenText').hide();
$('#hidden').empty();
//$('#hidden').show();
$.each(arrayShort, function (i, val) {
$('#hidden').append('<option value="' + val + '">' + val + '</option>');
});
});
$('#a2').change(function () {
//$('#hiddenText').hide();
$('#hidden').empty();
//$('#hidden').show();
$.each(arrayLong, function (i, val) {
$('#hidden').append('<option value="' + val + '">' + val + '</option>');
});
});
$('#a3').change(function () {
//$('#hidden').hide();
//$('#hiddenText')show();
$('#hidden').replaceWith('<input name="hidden" id="hiddenText" type="text" size="26" >');
});
})
here is my form
<input name="btn1" id="a1" type="radio" value="Radio button 1" />
<input name="btn1" id="a2" type="radio" value="Radio button 2" />
<input name="btn1" id="a3" type="radio" value="Radio button 3" />
<select id="hidden" name="hidden">
<option selected></option>
</select>
<input type="text" name="sBib" />
<input type="text" name="eBib" />
I need to populate the select if a1 or a2 is checked but if a3 is checked then I need to replace the select with a textbox BUT Then populate a variable bibfield so I can query with it.
New to this and I am so exhausted and can't think straight all help is appreciated!!!
here you are replacing hidden with hiddenText and again trying to find the hidden which is gone already
need to correct your code like below where i am replacing the whole select or input with same id="hidden"
$(document).ready(function () {
var bibfield = "";
// variable to indicate if select dropdown is available already otherwise create new
var selectAvailable=true;
$('#a1').change(function () {
//$('#hiddenText').hide();
//$('#hidden').empty();
//$('#hidden').show();
$.each(arrayShort, function (i, val) {
if(selectAvailable)
{
$('#hidden').append('<option value="' + val + '">' + val+ '</option>');
}
else
{
selectAvailable=true;
$('#hidden').replaceWith('<select id="hidden" name="hidden">
<option value="' + val + '">' + val + '</option></select>');
}
});
});
$('#a2').change(function () {
//$('#hiddenText').hide();
// $('#hidden').empty();
//$('#hidden').show();
$.each(arrayLong, function (i, val) {
if(selectAvailable)
{
$('#hidden').append('<option value="' + val + '">' + val + '</option>');
}
else
{
selectAvailable=true;
$('#hidden').replaceWith('<select id="hidden" name="hidden">
<option value="' + val + '">' + val + '</option></select>');
}
});
$('#a3').change(function () {
//$('#hidden').hide();
//$('#hiddenText')show();
selectAvailable=false;
$('#hidden').replaceWith('<input name="hidden" id="hidden" type="text" size="26" >');
});
});

Apply value to a jquery generated input field

my TD's are generated by grid object on a fly
i'm trying to change value of the fist empty input that is positioned inside :
$("#get_isrc").click(function(){
$.ajax({
url: 'xtras/isrc.php',
success: function(data){
$("#new_isrc").val(data);
$("#get_isrc").val('Apply');
$("#get_isrc").addClass('apply');
}
}).error(function(){
alert('Error');
});
});
$(".apply").live("click", function(){
var s = $("td[col=ISRC] input").val();
if (s === "") {
$(this).val(($("#new_isrc").val()));
}
});
html - static:
<h3>Generate next ISRC</h3>
<input id="new_isrc" type="text" />
<input id="get_isrc" type="button" value="Get next ISRC" />
html generated by jquery:
<tr id="4"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
<tr id="1"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
<tr id="2"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
<tr id="3"><td><input class="editableInput" type="text" /></td><td col="ISRC" class="editableCell"><input class="editableInput " type="text"></td></tr>
tr's 1 and 2 have ISRC values from database, tr 3 is empty, but positioned last
tr 4 - is newly added empty line and i want a generated isrc applied to it...
code i provided above doesn't work. why?
You are calling .val() into an array of inputs, do this:
$("td[col=ISRC] input").each(function() {
// each iteration function
var s = $(this).val();
if (s === "") {
$(this).val(($("#new_isrc").val()));
return false; // stops each iteration
}
});
Edit:
If you want to add the same value to all inputs, do this:
$("td[col=ISRC] input").each(function() {
var s = $(this).val();
if (s === "") {
$(this).val(($("#new_isrc").val()));
}
});
If you want to add dynamic values to all inputs, do this:
$("td[col=ISRC] input").each(function() {
var s = $(this).val();
if (s === "") {
$(this).val(getNextValue());
}
});
function getNextValue() {
// your business implementation here
}

Categories

Resources