How to Set id for each row of a column - javascript

This is one of the rows in my table.
<td>
<select id="itemcodeid" name="itemcode[]" class="form-control itemcode">
<option></option>
#foreach($productsdata as $d)
<option>{{$d->itemcode}}</option>
#endforeach
</select>
</td>
I am using Select2 to fill data.
<script type="text/javascript">
$("#itemcodeid").select2
({
placeholder: "Select Itemcode",
allowClear: true
});
</script>
But when i add rows to table how to refer the upcoming rows with id. Because this works only on first row.
Below is image of first row.
But in Other rows i am unable to type and select(second image) because id reference is not done so kindly tell how to refer id of the rows added.
Help or suggestion will be highly useful.Thank You.
This is the code which gets executed when i press the plus button(verify image).
<script type="text/javascript">
$('.addrow').on('click',function()
{ addrowfn();
});
function addrowfn()
{
var tr = '<tr>'+
'<td>'+
'<select id="itemcodeid" name="itemcode[]" class="form-control itemcode">'+
'<option></option>'+
'#foreach($productsdata as $d)'+
'<option>{{$d->itemcode}}</option>'+
'#endforeach'+
'</select>'+
'</td>'+
'<td><input type="text" name="proname[]" class="form-control proname"></td>'+
'<td><input type="text" name="actualprice[]" class="form-control actualprice"></td>'+
'<td><input type="text" name="discount[]" class="form-control discount"></td>'+
'<td><input type="text" name="gst[]" class="form-control gst"></td>'+
'<td><input type="text" name="quantity[]" class="form-control quantity"></td>'+
'<td><input type="text" name="finalprorate[]" class="form-control finalprorate"></td>'+
'<td><input type="text" name="finalbillrate[]" class="form-control finalbillrate"></td>'+
'<td>'+
'<a href="#" class="remove btn btn-danger">'+
'<center>'+
'<i class="glyphicon glyphicon-remove"></i>'+
'</center>'+
'</a>'+
'</td>'+
'</tr>';
$('tbody').append(tr);
}
$('body').on('click','.remove',function()
{ var l=$('tbody tr').length;
console.log(l);
if(l==1)
{ alert('You Cannot Remove all Rows!!!');
}
else
$(this).parent().parent().remove();
});
</script>
Kindly Tell me if there are any corrections.

I'm not sure if this code works, as I haven't tested it, but I would, at minimum, make these two changes:
Listen for the appended node using a MutationObserver, then turn
the regular select into a select2();
Create a variable to keep track of the rows, and make each select's ID dynamic, e.g. 'itemcodeid_3' and 'itemcodeid_5' etc. Do the same for 'name' attribute
var target = document.getElementById('<INSERT_ID_HERE>');
var rows = 1;
if (target) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation && mutation.addedNodes) {
mutation.addedNodes.forEach(function(el) {
if (el && el.nodeName === "SELECT") {
$(el).select2();
}
});
}
});
});
observer.observe(target, {
childList: true
});
} // end if
$('.addrow').on('click',function()
{
addrowfn();
});
function addrowfn()
{
rows++;
var tr = '<tr>'+
'<td>'+
'<select id="itemcodeid_" ' + rows + ' name="itemcode_' + rows + '[]" class="form-control itemcode">'+
'<option></option>'+
'#foreach($productsdata as $d)'+
'<option>{{$d->itemcode}}</option>'+
'#endforeach'+
'</select>'+
'</td>'+
'<td><input type="text" name="proname[]" class="form-control proname"></td>'+
'<td><input type="text" name="actualprice[]" class="form-control actualprice"></td>'+
'<td><input type="text" name="discount[]" class="form-control discount"></td>'+
'<td><input type="text" name="gst[]" class="form-control gst"></td>'+
'<td><input type="text" name="quantity[]" class="form-control quantity"></td>'+
'<td><input type="text" name="finalprorate[]" class="form-control finalprorate"></td>'+
'<td><input type="text" name="finalbillrate[]" class="form-control finalbillrate"></td>'+
'<td>'+
'<a href="#" class="remove btn btn-danger">'+
'<center>'+
'<i class="glyphicon glyphicon-remove"></i>'+
'</center>'+
'</a>'+
'</td>'+
'</tr>';
$('tbody').append(tr);
}
$('body').on('click','.remove',function()
{
var l=$('tbody tr').length;
console.log(l);
if(l==1)
{
alert('You Cannot Remove all Rows!!!');
}
else {
$(this).parent().parent().remove();
}
});
It may not work because it sees the appended node as instead of ...have to test
Additionally, you may wish to look at using a template engine for this, such as John Resig's jQuery solution or Mustache.js,
Handlebars.js

Related

How to handle auto-populate dropdown for dynamic table row in JavaScript?

I am working on adding dynamic table rows. There is a button for adding table rows when a user clicks on that button. So there I have three dropdowns. Each dropdown have some ID. So I have implemented the things where I am trying to auto populate first dropdown on that button click. So I am clicking add more rows then for second row, empty dropdown is created.
I want that whenever a user clicks on add more rows, then each dropdown of rows should be auto-populated. I hope that I am clear with my words.
Below is the script to load data in dropdown and to create rows dynamically:
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
var url = "api/get/activecompany";
$.post(url, {
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
var list = data.response;
var option = "<option selected disabled>Select Company</option>";
if(list.length > 0){
for(var i = 0; i < list.length; i++){
var content = "<option value='"+list[i].companyid+"'>"+list[i].companyname+" <span>("+list[i].dotnumber+")</span></option>";
option = option + content;
}
}
document.getElementById('lcompanyselect').innerHTML = option;
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
});
$("body").on("click", ".remove", function() {
$(this).closest("tr").remove();
});
});
function GetDynamicTextBox(value) {
return '<td class="">'+'<select class="js-example-placeholder-single js-states form-control" id="lcompanyselect" onchange="getDriverAndTruck()";></select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_co"></td>'
+'<td><select class="js-example-placeholder-single js-states form-control" id="ldriverselect"></select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_driver"></td>'
+'<td class=""><select class="js-example-placeholder-single js-states form-control" id="ltruckselect"></select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_truck"></td>'
+ '<td><input name = "tripnumber" type="text" class="form-control" id="ltripnumber"/></td>'
+'<td><select id="lsubtrip" name="subtrip" class="js-example-placeholder-single js-states form-control"><option disabled selected></option>'
+'<option value="1">1</option><option value="2">2</option><option value="3">3</option></select>'
+ '<td><input name = "date" type="date" class="form-control" id="ldate"/></td>'
+ '<td><input name = "pickupcity" type="date" class="form-control" id="lpickupcity"/></td>'
+ '<td><input name = "pickupstate" type="date" class="form-control" id="lpickupstate"/></td>'
+ '<td><input name = "deliverydate" type="date" class="form-control" id="ldeliverydate"/></td>'
+ '<td><input name = "delivercity" type="text" class="form-control" id="ldelivercity"/></td>'
+ '<td><input name = "deliverstate" type="text" class="form-control" id="ldeliverstate"/></td>'
+ '<td><input name = "loadnumber" type="text" class="form-control" id="lloadnumber"/></td>'
+ '<td><input name = "loadrate" type="text" class="form-control" id="lloadrate" onkeyup="lcount();"/><span id="lerrormessage"></span></td>'
+ '<td><input name = "dispatchfee" type="text" class="form-control" id="ldispatchfee" readonly/></td>'
+ '<td><input name = "fuel" type="text" class="form-control" id="lfuel"/></td>'
+ '<td><input name = "cardfee" type="text" class="form-control" id="lcardfee"/></td>'
+ '<td><input name = "onloadrepair" type="text" class="form-control" id="lonloadrepair"/></td>'
+ '<td><input name = "shoprepair" type="text" class="form-control" id="lshoprepair"/></td>'
+ '<td><input name = "trailerrent" type="text" class="form-control" id="ltrailerrent"/></td>'
+ '<td><input name = "comcheck" type="text" class="form-control" id="lcomcheck"/></td>'
+ '<td><input name = "advance" type="text" class="form-control" id="ladvance"/></td>'
+ '<td><input name = "miscellenous" type="text" class="form-control" id="lmiscellenous"/></td>'
+ '<td><input name = "misc1" type="text" class="form-control" id="lmisc1"/></td>'
+ '<td><input name = "misc2" type="text" class="form-control" id="lmisc2"/></td>'
+ '<td><input name = "misc3" type="text" class="form-control" id="lmisc3"/></td>'
+ '<td><input name = "misc4" type="text" class="form-control" id="lmisc4"/></td>'
+ '<td><input name = "total" type="text" class="form-control" id="ltotal" readonly/></td>'
+ '<td><input name = "layover" type="text" class="form-control" id="llayover"/></td>'
+ '<td><input name = "addtl1" type="text" class="form-control" id="laddtl1"/></td>'
+ '<td><input name = "addtl2" type="text" class="form-control" id="laddtl2"/></td>'
+ '<td><input name = "addtl3" type="text" class="form-control" id="laddtl3"/></td>'
+ '<td><input name = "subtotal" type="text" class="form-control" id="lsubtotal" readonly/></td>'
+ '<td><input name = "paymentmode" type="text" class="form-control" id="lpaymentmode"/></td>'
+ '<td><input name = "pay" type="text" class="form-control" id="lpay"/></td>'
+ '<td><input name = "notes" type="text" class="form-control" id="lnotes"/></td>'
+ '<td><input name = "grandtotal" type="text" class="form-control" id="lgrandtotal" readonly/></td>'
+ '<td><button type="button" class="btn btn-outline-info text-info" onclick="savetriplist();">Submit</button>'
+'<button type="button" class="btn btn-outline-danger text-danger remove">Remove</button></td>'
}
The one thing I have observed in your code is, its looking for a dropdown with id as lcompanyselect and then fills it with options. when the code runs for the first time it adds the dropdown on the dom, but when the code runs second time (when add button clicked) its filling the same dropdown which was added earlier, because the code is looking for element with id as lcompanyselect and it has found one.
document.getElementById('lcompanyselect').innerHTML = option;
Instead, I would suggest to have a placeholder for dropdown in your, function
GetDynamicTextBox(value)
<select class="js-example-placeholder-single js-states form-control" id="lcompanyselect" onchange="getDriverAndTruck()";>{Placeholder}</select>
and in code when you are finding the element, instead replace the {placeholder} with options html.
This is how modified code looks.
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<tr />");
var dynamicTextboxHtml = div.html(GetDynamicTextBox(""));
var url = "api/get/activecompany";
$.post(url, {
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
var list = data.response;
var option = "<option selected disabled>Select Company</option>";
if(list.length > 0){
for(var i = 0; i < list.length; i++){
var content = "<option value='"+list[i].companyid+"'>"+list[i].companyname+" <span>("+list[i].dotnumber+")</span></option>";
option = option + content;
}
}
dynamicTextboxHtml.replace("{OptionsPlaceholder}",content);
$("#TextBoxContainer").append(dynamicTextboxHtml);
dynamicTextboxHtml = '';
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
});
$("body").on("click", ".remove", function() {
$(this).closest("tr").remove();
});
});
function GetDynamicTextBox(value) {
return '<td class="">'+'<select class="js-example-placeholder-single js-states form-control" id="lcompanyselect" onchange="getDriverAndTruck()";>{OptionsPlaceholder}</select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_co"></td>'
+'<td><select class="js-example-placeholder-single js-states form-control" id="ldriverselect"></select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_driver"></td>'
+'<td class=""><select class="js-example-placeholder-single js-states form-control" id="ltruckselect"></select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_truck"></td>'
+ '<td><input name = "tripnumber" type="text" class="form-control" id="ltripnumber"/></td>'
+'<td><select id="lsubtrip" name="subtrip" class="js-example-placeholder-single js-states form-control"><option disabled selected></option>'
+'<option value="1">1</option><option value="2">2</option><option value="3">3</option></select>'
+ '<td><input name = "date" type="date" class="form-control" id="ldate"/></td>'
+ '<td><input name = "pickupcity" type="date" class="form-control" id="lpickupcity"/></td>'
+ '<td><input name = "pickupstate" type="date" class="form-control" id="lpickupstate"/></td>'
+ '<td><input name = "deliverydate" type="date" class="form-control" id="ldeliverydate"/></td>'
+ '<td><input name = "delivercity" type="text" class="form-control" id="ldelivercity"/></td>'
+ '<td><input name = "deliverstate" type="text" class="form-control" id="ldeliverstate"/></td>'
+ '<td><input name = "loadnumber" type="text" class="form-control" id="lloadnumber"/></td>'
+ '<td><input name = "loadrate" type="text" class="form-control" id="lloadrate" onkeyup="lcount();"/><span id="lerrormessage"></span></td>'
+ '<td><input name = "dispatchfee" type="text" class="form-control" id="ldispatchfee" readonly/></td>'
+ '<td><input name = "fuel" type="text" class="form-control" id="lfuel"/></td>'
+ '<td><input name = "cardfee" type="text" class="form-control" id="lcardfee"/></td>'
+ '<td><input name = "onloadrepair" type="text" class="form-control" id="lonloadrepair"/></td>'
+ '<td><input name = "shoprepair" type="text" class="form-control" id="lshoprepair"/></td>'
+ '<td><input name = "trailerrent" type="text" class="form-control" id="ltrailerrent"/></td>'
+ '<td><input name = "comcheck" type="text" class="form-control" id="lcomcheck"/></td>'
+ '<td><input name = "advance" type="text" class="form-control" id="ladvance"/></td>'
+ '<td><input name = "miscellenous" type="text" class="form-control" id="lmiscellenous"/></td>'
+ '<td><input name = "misc1" type="text" class="form-control" id="lmisc1"/></td>'
+ '<td><input name = "misc2" type="text" class="form-control" id="lmisc2"/></td>'
+ '<td><input name = "misc3" type="text" class="form-control" id="lmisc3"/></td>'
+ '<td><input name = "misc4" type="text" class="form-control" id="lmisc4"/></td>'
+ '<td><input name = "total" type="text" class="form-control" id="ltotal" readonly/></td>'
+ '<td><input name = "layover" type="text" class="form-control" id="llayover"/></td>'
+ '<td><input name = "addtl1" type="text" class="form-control" id="laddtl1"/></td>'
+ '<td><input name = "addtl2" type="text" class="form-control" id="laddtl2"/></td>'
+ '<td><input name = "addtl3" type="text" class="form-control" id="laddtl3"/></td>'
+ '<td><input name = "subtotal" type="text" class="form-control" id="lsubtotal" readonly/></td>'
+ '<td><input name = "paymentmode" type="text" class="form-control" id="lpaymentmode"/></td>'
+ '<td><input name = "pay" type="text" class="form-control" id="lpay"/></td>'
+ '<td><input name = "notes" type="text" class="form-control" id="lnotes"/></td>'
+ '<td><input name = "grandtotal" type="text" class="form-control" id="lgrandtotal" readonly/></td>'
+ '<td><button type="button" class="btn btn-outline-info text-info" onclick="savetriplist();">Submit</button>'
+'<button type="button" class="btn btn-outline-danger text-danger remove">Remove</button></td>'
}

Display data after choose product name using ajax

I try to use ajax output data from database I pass data product_name and product weight How can i display product weight out of
Now my Output
<select>category</select> //after select category It will display product name
<select>productname</select> //after select productname How can i display my product weight outof select tag
i want to display <span>product_weight</span> after I choose product_name
Here is my AJAX call . i try to console my data i get product_weight in my data already.
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findProductName')!!}',
data:{'id':cat_id},
success:function(data){
// console.log('success');
console.log(data);
// console.log(data.length);
op+='<option value="0" selected disabled>chose product</option>';
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].id_p+'" name="id_p">'+data[i].product_name+data[i].product_weight+'</option>';
}
div.find('.productname').html(" ");
div.find('.productname').append(op);
// console.log(data.length);
},
error:function(){
}
});
here is my html
<select style="width:50%;" class="productcategory" id="prod_cat_id" name="id_c[]">
<option value="0" disabled="true" selected="true">category</option>
#foreach($category as $c)
<option value="{{$c->id_c}}" name="id_c" id="id_c">{{$c->category_name}}</option>
#endforeach
</select>
<select style="width:48%;" class="productname" name="id_p[]">
<option value="0" disabled="true" selected="true"> productname</option>
</select>
here is my append jeavescript
<script type="text/javascript">
var i = 0;
$(document).ready(function() {
$('#add-form').click(function() {
i++;
$('#add-me').append(
'<tbody id="row'+i+'"><tr>'+
'<td class="col-md-7">'+
'<select style="width:50%;" class="productcategory" id="prod_cat_id" name="id_c['+ i +']"><option value="0" disabled="true" selected="true">category</option>#foreach($category as $c)<option value="{{$c->id_c}}" name="id_c[]" id="id_c[]">{{$c->category_name}}</option>#endforeach</select><select style="width:48%;" class="productname" name="id_p['+ i +']"><option value="0" disabled="true" selected="true"> product name</option></select>'
+'</td>'
+'<td class="col-md-1">'
+'<div id="target_div_where_to_display_weight['+i+']" name="target_div_where_to_display_weight['+i+']">'
+'</div>'
+'<td class="col-md-1">'
+'<input id="quantity" type="text" name="quantity_box[]" class="form-control"/>'
+'</td>'
+'<td class="col-md-1">'
+'<input id="unit_price" type="text" name="unit_price[]" class="form-control"/>'
+'</td>'
+'<td class="col-md-1">'
+'<input id="price" type="text" name="price[]" class="form-control"/>'
+'</td>'
+'<td class="col-md-2">'
+'<button id="'+i+'" type="button" class="btn btn-danger delegated-btn">Delete</button>'
+'</td>'
+'</tr></tbody>'
);
$('button.btn.btn-danger').click(function() {
var whichtr = $(this).closest("tr");
whichtr.remove();
});
});
});
</script>
here is my output look like
update
You can store product_weight in a new tag attribute inside each option tag, like "data-weight". In order to display the corresponding weight you would just need to do this:
$("select.productname").on("change",function(){
var weight = $(this).find(":selected").data("weight"); // .attr("data-weight");
var span = "<span>"+weight+"</span>";
$("#target_div_where_to_display_weight").html(span);
});
UPDATE
In your ajax request replace:
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].id_p+'" name="id_p">'+data[i].product_name+data[i].product_weight+'</option>';
}
by
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].id_p+'" name="id_p" data-product_weight="'+data[i].product_weight+'">'+data[i].product_name+data[i].product_weight+'</option>';
}
and in the code i wrote before replace the first instruction by:
var weight = $(this).find(":selected").data("product_weight"); // or .attr("data-product_weight");
UPDATE 2
If you want to append to a div the weight of each product you choose, the should look like this:
First, change your "#target_div_where_to_display_weight" div by a "<div id='weights_wrapper'></div>", then change the first function (on change) by:
<pre>$("select.productname").on("change",function(){
var prod = $(this).find(":selected"); // .attr("data-weight");
var weight = prod.data("product_weight");
var id_p = prod.val();
var added_content = "";
var content = "<div class='weight' data-ip_p='"+id_p+"'><span>"+weight+"</span>"+added_content+"</div>";
$("#weights_wrapper").append(content);
});</pre>
In this way you can add anchor tags to manage every weight's block. For example, if you want to delete a weight after adding it, you could set added_content = ''; and then createthe following function:
<pre>$("#weights_wrapper").on("click",".close_weight",function(){
$(this).parent().remove();
});</pre>

Setting a dropdown selected value when generating a html table using jquery

I am generating a html table with a dropdown and a textbox from an array. I am storing array value property value in textbox and based on the value comin in the key property I want to to set the selected value of the dropdown in each row.
How can I set the dropdown value.
My code is like this. Everything is done I want only to set dropdown selected value.
var filtrnode=[arrayvalue];
$.each(filterNodeData.FilterData, function (i, item) {
debugger;
var newData = filterNodeData.FilterData[i];
trHTML += '<tr><td>' + '<select class="form-control"><option value="and">And</option><option value="or">Or</option></select>' + '</td>' +
'<td>' + '<input class="form-control" size=35 type="text" id="filterValue" value= ' + filterNodeData.FilterData[i].value + '>' + '</td>' +
'<td><input type="button" id="delFilter" class="delHeader btn btn-md red" value="Delete" onclick="deleteFilter(this)" ></td>' +
'<td><input type="button" id="AddFilter" class="btn btn-md btn-primary" value="Add" onclick="insertFilter()" ></td>' + '</tr>';
});
$('#filterTable').append(trHTML);
Thanks
You can set it by getting the option selected for that index like,
$.each(filterNodeData.FilterData, function (i, item) {
var newData = filterNodeData.FilterData[i],
value=newData.value,
key = newData.key;
trHTML += '<tr><td>' + '<select class="form-control">'+
'<option value="and" '+(key=='and'?'selected':'')+'>And</option>'+
'<option value="or" '+(key=='or'?'selected':'')+'>Or</option>'+
'</select></td>' +
'<td>' + '<input class="form-control" size=35 type="text" id="filterValue" value= ' + value + '>' + '</td>' +
'<td><input type="button" id="delFilter" class="delHeader btn btn-md red" value="Delete" onclick="deleteFilter(this)" ></td>' +
'<td><input type="button" id="AddFilter" class="btn btn-md btn-primary" value="Add" onclick="insertFilter()" ></td>' + '</tr>';
});
$('#filterTable').append(trHTML);
I would do it like this:
$(document).ready(function() {
// store your html as a variable, `` alows you to use lines in string
var row = `
<tr>
<td><select class="form-control"><option value="and">And</option><option value="or">Or</option></select></td>
<td><input class="form-control" size=35 type="text" id="filterValue"></td>
<td><input type="button" id="delFilter" class="delHeader btn btn-md red" value="Delete" onclick="deleteFilter(this)" ></td>
<td><input type="button" id="AddFilter" class="btn btn-md btn-primary" value="Add" onclick="insertFilter()" ></td>
</tr>
`
var filtrnode = [{arrayvalue}];
$.each(filtrnode, function(i, item) {
// make a jQuery object from your html variable
var newRow = $(row);
// and now you are free to use jQuery selectors and functions on it
newRow.find("select option[value="+ item.key +"]").prop("selected", true);
newRow.find("input[type='text']").val(item.value);
$('#filterTable').append(newRow);
});
});
Storing your HTML code as a variable using `` allows you tu use line breaks and create a code which is easier to read. After you create a jQuery object from your stored HTML you can access all of jQuery functions which is cool. This makes your code less prone to mistakes and typos. Here is a jsFiddle.

Index-Id always has the same value for every input

So I have dynamically created form that I would like to get index-id of certain inputs with names like championSpell[] I need to know which one is which so i thought of using index-id but it changes every inputs index to the same value when pressing add spell button. You can test the problem here http://89.69.172.125/test.php
$(function() {
$('body').on('click', '#addSpell',function() {
$(
'<p><select name="change[]" id="change[]" onchange="val(this)"><option value="Passive">Passive</option><option value="Q" selected>Q</option><option value="W">W</option><option value="E">E</option><option value="R">R</option></select><label for="var"><input type="text" id="championSpell[]" name="championSpell[]" data-id="" readOnly="true"><br><textarea type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> Add Change Remove Spell</p>').appendTo($(this).next());
$('input[name="championSpell[]"]').attr('data-id', y);
y++;
return false;
});
});
Bad practice aside
(as in, using label as a block element)
(using jquery to create such a template file)
(etc)
(etc)
The problem resides with the variable y not being initialized, and changing all data-id values in the end. Try this updated (and a bit more readable) bit
$(function () {
var y = 0;
$('#addSpell').on('click', function(){
$(['<p>',
'<select name="change[]" id="change[]" onchange="val(this)">',
'<option value="Passive">Passive</option>',
'<option value="Q" selected>Q</option>',
'<option value="W">W</option>',
'<option value="E">E</option>',
'<option value="R">R</option>',
'</select>',
'<label for="var">',
'<input type="text" id="championSpell[]" name="championSpell[]" data-id="' + y +'" readOnly="true">',
'<br>',
'<textarea type="text" id="p_scnt" size="20" name="p_scnt_' + y + '" value="" placeholder="Enter Description">',
'<select>','' +
'<option value="buff">Buff</option>',
'<option value="nerf">Nerf</option>',
'<option value="new">New</option>',
'<option value="change">Change</option>',
'<option value="bugfix">Bugfix</option>',
'</select>',
'</label>',
'Add Change',
'Remove Spell',
'</p>'].join('')).appendTo($(this).next());
y++;
return false;
});
});
In you code $('input[name="championSpell[]"]').attr('data-id', y); this will change all inputs data-id. So instead of that directly add its data-id.
Like data-id="'+y+'"
I HAVE UPDATE YOUR CODE.
PLEASE TRY THIS CODE
$(function() {
$('body').on('click', '#addSpell',function() {
var championdataid = $('input[id="champion[]"]').attr('data-id');
$(
'<p><select name="change[]" id="change[]" onchange="val(this)"><option value="Passive">Passive</option><option value="Q" selected>Q</option><option value="W">W</option><option value="E">E</option><option value="R">R</option></select><label for="var"><input type="text" id="championSpell[]" name="championSpell[]" data-id="'+y+championdataid +'" readOnly="true"><br><textarea type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> Add Change Remove Spell</p>').appendTo($(this).next());
//$('input[name="championSpell[]"]').attr('data-id', y);
y++;
return false;
});
});

jQuery Calculations after appending more input fields

I am building an expense template an am having an issue regarding using jQuery Calculations and click functionality to append a set of input fields.
I am combining twooncodes, one to calculate the sum of the values in input fields, and the other to Add a new row of input fields when the user clicks so (these are also to be added to the sum). Problem is, the sum is not adding to the total from the newly appended rows. Only the default row of fields adds.
Any help is appreciated (Fiddle ex: http://jsfiddle.net/NicoleScotsburn/o8x02sjh/4/ )
Appending table with inputs code:
//Increment Variables
var items = $('#items');
var i = $('#items td').size() + 1;
var mileage = $('#mileage');
var j = $('#mileage td').size() + 1;
//Append Table Rows
$('#addItem').on('click', function() {
$('<tr><td> <label for="date"><input type="text" id="date" size="10" name="date_' + i +'" value="" placeholder="mm/dd/yyyy" /></label></td>' +
'<td> <label for="desc"><input type="text" id="desc" size="30" name="desc_' + i +'" /></label></td>' +
'<td> $<label for="entmt"><input type="text" id="sum" size="10" name="entmt_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="meals"><input type="text" id="sum" size="10" name="meals_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="other"><input type="text" id="sum" size="10" name="other_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="travel"><input type="text" id="sum" size="10" name="travel_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="lodging"><input type="text" id="sum" size="10" name="lodging_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="hst"><input type="text" id="sum" size="10" name="hst_' + i +'" placeholder="0.00" /></label></td>' +
'<td> Remove</td></tr>').appendTo(items);
i++;
return false;
});
$('#addMileage').on('click', function() {
$('<tr><td> <label for="mdate"><input type="text" id="mdate" size="10" name="mdate' + j +'" value="" placeholder="mm/dd/yyyy" /></label></td>' +
'<td> <label for="mlocation"><input type="text" id="mlocation" size="30" name="mlocation' + j +'" value="" placeholder="" /></label></td>' +
'<td> <label for="km"><input type="text" id="km" size="10" name="km' + j +'" value="" placeholder="" />KM</label></td>' +
'<td> Remove</td></tr>').appendTo(mileage);
j++;
return false;
});
//Remove Buttons
$('body').on('click', '#remItem', function() {
if( i > 2 ) {
$(this).parents('tr').remove();
i--;
}
return false;
});
$('body').on('click', '#remMileage', function() {
if( j > 2 ) {
$(this).parents('tr').remove();
j--;
}
return false;
});
Calculation function: (This works assuming the id of the input is id="sum" and gets outputted to another input called totalsum.
$("input[id^=sum]").sum("keyup", "#totalSum");
I am not familiar with jQuery Calculations, but it looks like what you are doing can be achieved using plain jQuery or javascript. I did a quick google search for jquery sum and I found this other stackoverflow post that might help you. stackoverflow sum
You can add a class attribute called "sum" to all the fields you want to sum up and use the jquery marked as the answer. Once you get done calculating the total you can assign it to the total amount input field.
$('.sum').blur(function () {
var sum = 0;
$('.sum').each(function() {
sum += Number($(this).val());
});
$("#totalsum").val(sum);
});​​​​​​​​​

Categories