add/remove all textbox id increment - javascript

How to Set Add/remove in all text-box id Auto increment (ItemCode,ItemName Add To +1 And Remove to -1.)
<div id="mainDiv">
<div class="one">
<div class="row">
<div class="input-field col s1">
<input type="text" id="sno" class="sno" name="Sr[]" value="1" >
<label for="Sr" >Sr</label>
</div>
<div class="input-field col s2">
<input id="ItemCode" type="text" name="ItemCode[]" onKeyUp="showHint(this.value)">
<label for="ItemCode" >Item Code</label>
</div>
<div class="input-field col s2">
<input id="ItemName" type="text" name="ItemName[]" value=" ">
<label for="ItemName" >Item Name</label>
</div>
<div class="input-field col s1 add">
Add
</div>
<div class="input-field col s1 delete">
Remove
</div>
</div>
</div>
</div>
$(document).ready(function () {
$(".add").click(function () {
var length = $('.one').length;
var cloned = $(this).closest('.one').clone(true);
cloned.appendTo("#mainDiv").find('.sno').val(length + 1);
cloned.find(':input:not(".sno")').val(" ");
var parent = $(this).closest('.one');
});
$('.delete').click(function () {
if($('.one').length==1){
alert("This is default row and can't deleted");
return false;
}
var parent = $(this).closest('.one');
$(this).parents(".one").remove();
// reset serial numbers again
$('.sno').each(function(i){
this.value=i+1;
})
});
});
https://jsfiddle.net/Nilesh_Patel/05e3wtcm/1/ here example

try to add this code to your add event
cloned.find('input[name="ItemCode[]"]').attr('id','ItemCode'+(length + 1));
cloned.find('input[name="ItemName[]"]').attr('id','ItemName'+(length + 1));

Here is what you can do. This will reset the id's on delete as well.
Since the for attribute of the labels should be bound to the inputs id you may want to change those as well.
$(document).ready(function () {
$(".add").click(function () {
var length = $('.one').length;
var cloned = $(this).closest('.one').clone(true);
cloned.appendTo("#mainDiv").find('.sno').val(length + 1);
cloned.find(':input:not(".sno")').val(" ");
cloned.find("label[for*='ItemCode']").attr('for', 'ItemCode' + (length+1));
cloned.find("input[id*='ItemCode']").attr('id', 'ItemCode' + (length+1));
cloned.find("label[for*='ItemName']").attr('for', 'ItemName' + (length+1));
cloned.find("input[id*='ItemName']").attr('id', 'ItemName' + (length+1));
var parent = $(this).closest('.one');
});
$('.delete').click(function () {
if($('.one').length==1){
alert("This is default row and can't deleted");
return false;
}
var parent = $(this).closest('.one');
$(this).parents(".one").remove();
$('.one').each(function(index, item) {
$(this).find('.sno').val(index+1);
$(this).find("label[for*='ItemCode']").attr('for', 'ItemCode' + (index+1));
$(this).find("input[id*='ItemCode']").attr('id', 'ItemCode' + (index+1));
$(this).find("label[for*='ItemName']").attr('for', 'ItemName' + (index+1));
$(this).find("input[id*='ItemName']").attr('id', 'ItemName' + (index+1));
});
});
});
<div id="mainDiv">
<div class="one">
<div class="row">
<div class="input-field col s1">
<input type="text" id="sno" class="sno" name="Sr[]" value="1" />
<label for="Sr" >Sr</label>
</div>
<div class="input-field col s2">
<input id="ItemCode" type="text" name="ItemCode[]" onKeyUp="showHint(this.value)" />
<label for="ItemCode" >Item Code</label>
</div>
<div class="input-field col s2">
<input id="ItemName" type="text" name="ItemName[]" value=" " />
<label for="ItemName" >Item Name</label>
</div>
<div class="input-field col s1 add">
Add
</div>
<div class="input-field col s1 delete">
Remove
</div>
</div>
</div>
</div>

You can reset the serial numbers using the following function. check the jsfiddle https://jsfiddle.net/05e3wtcm/4/
function ResetSerialNumbers(){
$('.sno').each(function(i){
var val = i+1;
this.value=val;
$(this).closest('.row').find("input[id^='ItemCode']").first().attr("id",'ItemCode'+val);
$(this).closest('.row').find("input[id^='ItemName']").first().attr("id",'ItemName'+val);
});
}

Related

Optimize the repetitive code for adding new option to select jquery

Here is my fiddle : DEMO
I have repeated codes for adding new options to rule and event category select. How do I optimize the same to eliminate the repeated code?
//Adding new category for event
$(document).on('click', '.addevent', function() {
var found = false; // Track if new value was found in list
// Loop through list options
$("#categoryevent > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#new-option-event').val('');
}
});
// If not found
if ($('#new-option-event').val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#new-option-event").val().trim();
var opt = '<option>' + val + '</option>';
$('#categoryevent').append(opt);
$('#categoryevent').val(val);
$('#new-option-event').val('');
$("#categoryevent").click();
}
}
});
Here you go - a common function helps a lot:
//Adding new category for rule
$(document).on('click', '.addrule', function() {
AddElement("categoryrule", "new-option-rule");
});
//Adding new category for event
$(document).on('click', '.addevent', function() {
AddElement("categoryevent", "new-option-event");
});
function AddElement(selectId, newElementId){
var found = false; // Track if new value was found in list
// Loop through list options
$( "#" + selectId + " > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#" + newElementId).val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#' + newElementId).val('');
}
});
// If not found
if ($('#' + newElementId).val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#" + newElementId).val().trim();
var opt = '<option>' + val + '</option>';
$('#' + selectId).append(opt);
$('#' + selectId).val(val);
$('#' + newElementId).val('');
$("#" + selectId).click();
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>
Here you go with some optimised code https://jsfiddle.net/3tLx884e/2/
//Adding new category for rule
$(document).on('click', '.addrule', function() {
var found = false; // Track if new value was found in list
// Loop through list options
var text = $("#new-option-rule").val().trim();
$("#categoryrule > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if (text.toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!");
found = true; // Set flag if value exists
}
if((idx + 1) === $('#categoryrule > option').length){
if ( !found && (text != '')) {
// Create new option and append to list
$('#categoryrule')
.append('<option>' + text + '</option>')
.val(text);
}
$('#new-option-rule').val('');
}
});
// If not found
});
//Adding new category for event
$(document).on('click', '.addevent', function() {
var found = false; // Track if new value was found in list
// Loop through list options
$("#categoryevent > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#new-option-event').val('');
}
});
// If not found
if ($('#new-option-event').val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#new-option-event").val().trim();
var opt = '<option>' + val + '</option>';
$('#categoryevent').append(opt);
$('#categoryevent').val(val);
$('#new-option-event').val('');
$("#categoryevent").click();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>
Hope this will help you.
This is my take on the problem, following jquery's slogan: "write less, do more" ...
I reduced the code further by working on local context. I. e. I only need to define one click event for everything. The click function itself figures out, what to change. It does not need any ids to do its job:
//Adding new category for rule and event
$('.form-group').on('click', 'button', addElement);
function addElement(){
var $grp=$(this).closest('.form-group'),
ival=$('input:text',$grp).val().trim(), // new input value
$sel=$('select',$grp.prev()), // select element
opts=$.makeArray($('option',$sel).map(function(i,op){
return op.textContent.toLowerCase(); }));
if ($.inArray(ival.toLowerCase(),opts)===-1){ // check existing option values
$sel.append('<option value="'+ival+'" selected>'+ival+'</option>');
}
else {alert(ival+' exists already in '+$sel[0].id);}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>

Codeigniter form serialize not working

i'm triying to pass data from form to controller in codeigniter...but when I want to print a table with the results...i'm getting null on every row of the table. Here is my code:
FORM
<form class="col s12" id="update_form" name="update_form" method="post" >
<div class="row">
<div class="input-field col s6">
<input id="update_name" type="text" name="name" class="validate">
<label for="first_name">Nombre</label>
</div>
<div class="input-field col s6">
<input id="update_last_name" name="lastname" type="text" class="validate">
<label for="last_name">Apellido</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="update_side" type="text" name="side" class="validate">
<label for="partido">Partido</label>
</div>
<div class="input-field col s6">
<input id="update_charge" type="text" name="charge" class="validate">
<label for="cargo">Cargo</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<div class="file-field input-field no-margin-top">
<div class="btn light-blue darken-4">
<span>Animación</span>
<input type="file">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" name="animation" type="text">
</div>
</div>
</div>
<div class="input-field col s6">
<select id="update_section" name="section" autocomplete="off">
<option value="" disabled selected>Seleccione una opción</option>
<option value="1">Presidencia</option>
<option value="2">Senadores</option>
<option value="3">Diputados</option>
</select>
<label>Sección</label>
</div>
</div>
<input type="hidden" name="update_politic_hide" id="update_politic_hdn" value="">
</form>
Jquery
$("#update_politic_btn").click(function(event) {
/* Act on the event */
var chango = $("#update_form").serialize();
alert(chango);
$.post(baseurl + 'admin/update_politic', {
data: chango
},
function(data) {
console.log(data);
list_politic();
});
event.preventDefault();
});
Controller
public function update_politic(){
if ($this->input->is_ajax_request()) {
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["animation"] = $this->input->post("animation");
$params["section"] = $this->input->post("section");
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
$this->load->model("politic");
$this->politic->update($params);
}
}
MODEL
public function update($param){
$id = $param["id"];
$values = array(
"POLITIC_NAME" => $param["name"],
"POLITIC_LASTNAME" => $param["lastname"],
"POLITIC_SIDE" => $param["side"],
"POLITIC_CHARGE" => $param["charge"],
//"animation" => $param["animation"],
"SECTION_ID" => $param["section"],
);
$this->db->update("politics",$values);
$this->db->where("POLITIC_ID",$id);
}
HELP!!! I don't understan why i'm getting null values once I want print results!!
Your where condition should come first like,
public function update($param){
$id = $param["id"];
$values = array(
"POLITIC_NAME" => $param["name"],
"POLITIC_LASTNAME" => $param["lastname"],
"POLITIC_SIDE" => $param["side"],
"POLITIC_CHARGE" => $param["charge"],
//"animation" => $param["animation"],
"SECTION_ID" => $param["section"],
);
$this->db->where("POLITIC_ID",$id);
$this->db->update("politics",$values);
}
And show us your list_politic(); code if it is not working.
I think you are passing data in incorrect way if you are using serialize() then use it directly in $.post like,
$.post(baseurl + 'admin/update_politic',chango,function(data) {
console.log(data);
list_politic();
});

how can i capture multiple form inputs and save in an array

<template name="uploadTicket">
<div class="row">
<h3> Upload Ticket</h3>
<form class="ticket-form col s12" enctype="multipart/form-data">
<div class="row">
<div class="input-field col s12">
<input id="name" type="text" class="validate">
<label for="name">Event Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="location" type="text" class="validate">
<label for="location">Location</label>
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input id="date" type="date" class="validate">
<label for="date"></label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<textarea id="description" class="materialize-textarea"></textarea>
<label for="Description">Description</label>
</div>
</div>
<div class="row">
<div class="col s6">
<h5>More Price Fields</h5>
</div>
<div class="col s6">
<a class="btn-floating btn-large waves-effect waves-light red" id="addField"><i class="mdi mdi-plus"></i></a>
</div>
</div>
<div class="wrapper">
<div class="row">
<div class="input-field col s4">
<input name="priceClass[]" type="text" class="validate">
<label for="priceClass[]">Class</label>
</div>
<div class="input-field col s4">
<input name="priceAmount[]" type="text" class="validate">
<label for="priceAmount[]">Price</label>
</div>
<div class="input-field col s4">
<h6>Input Price Classes and Amounts.</h6>
</div>
</div>
<br>
</div>
<br>
<div class="row">
<div >
<button class="waves-effect waves-light btn" type="submit">Upload</button>
</div>
</div>
</form>
</div>
</template>
This is my Template
Template.uploadTicket.events({
'click #addField': function (event) {
event.preventDefault();
var max_fields = 10;
var wrapper = $(".wrapper");
var add_button = $(".addField");
var x = 1;
if (x < max_fields)
{
x++; //text box increment
$(wrapper).append(' <div class="row"> <div class="input-field col s4"> <input name="priceClass[]" type="text" class="validate"> <label for="priceClass[]">Class</label> </div> <div class="input-field col s4"> <input name="priceAmount[]" type="text" class="validate"> <label for="priceAmount[]">Price</label> </div> <a class="btn-floating btn-large waves-effect waves-light red" id="removeField"><i class="mdi mdi-minus"></i></a></div> <br>'); //add input box
}
$(wrapper).on("click","#removeField", function(e)
{ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
}
});
This is my JavaScript for that template. I am giving the user option to add multiple fields so that they can have different classes for prices. Like gold class for a certain amount, VIP for another amount ,regular for another amount and so on. I am having a problem with how to get those input values when submitting the values and saving them into an array.
You would use jquery to loop through your inputs and send their values into an empty array. Then take the array with data and send it to your collection.
let valueStore = [];
console.log(valueStore) // an empty array
$('.input-field input').each(function(){
if (this.value != ''){
valueStore.push(this.value)
}
})
console.log(valueStore) // will have your values.
You can use JQuery-Selectors to get all Input Fields. You allready gave them a class. After that you can extract all necessary information into your array.
The JQuery-Selector should look something like:
$('.input-field')
Use a forEach loop to get every selected element.

How To Get Right SrNo in Add remove Clone With My Calculation

How To Get Right SrNo in Add remove Clone With My Calculation
Click To Add(Multiple Time) After Delete Some Row After Re Click Add To Get SrNo Wrong And I Want With My Calculation...
<div id="button_pro">
<div id='input_1' class="row">
<div class="input-field col s1">
<input class="sno" type="text" name="Sr_1" value="1" >
<label for="Sr">Sr</label>
</div>
<div class="input-field col s2">
<input id="item_code" type="text" name="item_code_1" value=" ">
<label for="item_code">Item Code</label>
</div>
<div class="input-field col s2">
<input id="item_name" type="text" name="item_name_1" value=" ">
<label for="item_name">Item Name</label>
</div>
<div class="input-field col s1">
<input type="text" class="quantity" name="quantity_1" value=" ">
<label for="quantity">Quantity</label>
</div>
<div class="input-field col s1">
<input type="text" class="net_rate" name="net_rate_1" value=" ">
<label for="net_rate">Net Rate</label>
</div>
<div class="input-field col s1">
<input type="text" class="tax" name="tax_1" value=" ">
<label for="tax">tax</label>
</div>
<div class="input-field col s1">
<input type="text" class="Gross Rate" name="Gross Rate_1" value=" ">
<label for="Gross Rate">Gross Rate</label>
</div>
<div class="input-field col s1">
<input type="text" class="total" name="total_1" value=" " readonly>
<label for="total">total</label>
</div>
<div class="input-field col s2"> <i class="mdi-content-add">Add</i>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s8">
</div>
<div class="input-field col s2">
<input type="text" name="Grand" id="Grand" value=" ">
<label for="net_rate">Grand Total</label>
</div>
</div>
$('document').ready(function(){
var id=2,txt_box;
$('#button_pro').on('click','.add',function(){
$(this).remove();
txt_box='<div id="input_'+id+'" class="row"><div class="input-field col s1"><input type="text" name="Sr_'+id+'" value="'+id+'" ><label for="SrNo" class="active">SrNo</label></div><div class="input-field col s2"><input id="item_code" type="text" name="item_code_'+id+'"><label for="item_code" class="active">Item Code</label></div><div class="input-field col s2"><input id="item_name" type="text" name="item_name_'+id+'"><label for="item_name" class="active">Item Name</label></div><div class="input-field col s1"><input id="qty" type="text" name="quantity_'+id+'"><label for="quantity" class="active">Quantity</label></div><div class="input-field col s1"><input type="text" name="net_rate_'+id+'" ><label for="net_rate" class="active">Net Rate</label></div><div class="input-field col s1"><input type="text" name="tax_'+id+'" ><label for="tax"class="active">tax</label></div><div class="input-field col s1"><input type="text" name="Gross_Rate_'+id+'"><label for="Gross Rate" class="active">Gross Rate</label></div><div class="input-field col s1"><input type="text" name="total_'+id+'"><label for="total" class="active">total</label></div><div class="input-field col s2"><i class="mdi-content-add">Add</i></div><i class="mdi-content-clear">Remove</i></div>';
$("#button_pro").append(txt_box);
id++;
});
$('#button_pro').on('click','.remove',function(){
var parent=$(this).parent().prev().attr("id");
var parent_im=$(this).parent().attr("id");
$("#"+parent_im).slideUp('fast',function(){
$("#"+parent_im).remove();
if($('.add').length<1){
$("#"+parent).append('<div class="input-field col s2"> <i class="mdi-content-add">Add</i></div> ');
}
});
});
});
http://jsfiddle.net/p6jaxvzz/5/ Example For Problem
$('#button_pro').on('click', '.remove', function () {
var parent = $(this).parent().prev().attr("id");
var parent_im = $(this).parent().attr("id");
$("#" + parent_im).slideUp('fast', function () {
$("#" + parent_im).remove();
if ($('.add').length < 1) {
$("#" + parent).append('<div class="input-field col s2"> <i class="mdi-content-add">Add</i></div> ');
}
var $rows = $('.row');
$rows.each(function (i) {
if (i < $rows.length - 1) {
i++;
var $inputs = $('input', this);
$inputs.eq(0).attr('name', 'Sr_' + i).val(i);
$inputs.eq(1).attr('name', 'item_code_' + i);
$inputs.eq(2).attr('name', 'item_name_' + i);
$inputs.eq(3).attr('name', 'quantity_' + i);
$inputs.eq(4).attr('name', 'net_rate_' + i);
$inputs.eq(5).attr('name', 'tax_' + i);
$inputs.eq(6).attr('name', 'Gross_Rate_' + i);
$inputs.eq(7).attr('name', 'total_' + i);
}
});
id--;
});
});
Fiddle
This will surely help you. I have moddifed your sequence of elements in HTML too, but they are fine don't worry about that.
Here just showing you only for two fields, you add rest in var clone
JSFiddle
HTML
<div class="button_pro">
<div id='input_1' class="row">
<div class="input-field col s1">
<input class="sno" type="text" name="Sr_1" value="1">
<label for="Sr">Sr</label>
</div>
<div class="input-field col s2">
<input id="item_code" type="text" name="item_code_1" value=" ">
<label for="item_code">Item Code</label>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s2">
<a href="#" class="btn-floating waves-effect waves-light add ">
<i class="mdi-content-add">Add</i>
</a>
</div>
<div class="input-field col s2">
<a href="#" class="btn-floating waves-effect waves-light remove ">
<i class="mdi-content-add">Remove</i>
</a>
</div>
<div class="input-field col s8"></div>
<div class="input-field col s2">
<input type="text" name="Grand" id="Grand" value=" ">
<label for="net_rate">Grand Total</label>
</div>
</div>
JavaScript/JQuery
$(".remove").hide();
$(function () {
$(".add").click(function () {
num = $(".button_pro").length;
//alert(num);
if(num>=1)
{
$(".remove").show();
}
incr = num + 1;
var clone = '<div class="button_pro">';
clone += '<div id="input_' + incr + '" class="row">';
clone += '<div class="input-field col s1">';
clone += '<input class="sno" type="text" name="Sr_' + incr + '" value="' + incr + '">';
clone += '<label for="Sr">Sr</label>';
clone += '</div>';
clone += '<div class="input-field col s2">';
clone += '<input id="item_code" type="text" name="item_code_' + incr + '" value=" ">'
clone += '<label for="item_code">Item Code</label>'
clone += '</div>';
clone += '</div>';
clone += '</div>';
$(clone).insertBefore($(this).closest('.row'));
});
$(".remove").click(function () {
lastnum = $(".button_pro").length;
if(lastnum == 2)
{
$(".remove").hide();
}
$(".button_pro:nth-child(" + lastnum + ")").remove();
});
});

Form field values sum in jQuery

I can't seem to get this to work for a project I'm doing. Basically I'm trying to get the values in the "Revenue" fields to total at the bottom in the "Total Revenue" field.
I've made a JSFiddle which hopefully will make it easier to understand-
HTML markup:
<div class="form-group">
<label class="control-label col-md-2">April</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="AprilInput" placeholder="eg. 35,328" type="text" id="AprilInput"></input>
</div>
</div>
<label class="control-label col-md-1">Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="Output" id="AprilOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">May</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="MayInput" placeholder="eg. 35,328" type="text" id="MayInput"></input>
</div>
</div>
<label class="control-label col-md-1">Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control1" name="Output" id="MayOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">June</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="JuneInput" placeholder="eg. 35,328" type="text" id="JuneInput"></input>
</div>
</div>
<label class="control-label col-md-1">Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control1" name="Output" id="JuneOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
<br/>
<span class="form-horizontal">
<div class="row">
<div class="col-lg-12">
<div class="widget-container fluid-height clearfix">
<div class="heading">
<i class="icon-reorder"></i>Annual Total
</div>
<div class="widget-content padded">
<div class="form-group">
<label class="control-label col-md-6">Total Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="TotalOutput" id="TotalOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
You could tidy the code up a little:
function SetupInput(obj,output,sumfunction){
$(obj).keyup(function(){
var n = parseInt($(this).val());
var n = this.value.replace(/,/g, "");
if(n <= 155000) {
$(output).val(numberWithCommas((n/100*70).toFixed(0)));
}
else if(n <= 175000) {
$(output).val(numberWithCommas((n/100*75).toFixed(0)));
}
else {
$(output).val(numberWithCommas((n/100*80).toFixed(0)));
}
sumfunction();
});
}
SetupInput($('#AprilInput')[0],$('#AprilOutput')[0],calculateSum);
SetupInput($('#MayInput')[0],$('#MayOutput')[0],calculateSum);
SetupInput($('#JuneInput')[0],$('#JuneOutput')[0],calculateSum);
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".form-control1").each(function() {
//add only if the value is number
var value=this.value.replace(',','');//remove ','
if(!isNaN(value) && value.length!=0) {
sum += parseFloat(value);
console.log(this.id,sum);
}
});
//.toFixed() method to roundoff the final sum
$("#TotalOutput").val(sum.toFixed(0));
}
Check out the jsfiddle: http://jsfiddle.net/2jY6P/43/
You are looping though Output tag. Change it to .form-contol:
$(".form-control").each(function() { /* ... */ }
And not .html, but .val():
`$("#TotalOutput").val(sum.toFixed(0));`
i edited you code: http://jsfiddle.net/2jY6P/38/
changed:
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$("input[name='Output']").keyup(function(){
calculateSum();
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$("input[name='Output']").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method to roundoff the final sum
$("#TotalOutput").val(sum.toFixed(0));
}
$('Output') should be input $("[name='Output']")
$("#TotalOutput").html(sum.toFixed(0));
should be $("#TotalOutput").val(sum.toFixed(0));
I put some changes in
http://jsfiddle.net/2jY6P/39/
$(document).keyup(function() {
var sumRevenue = 0;
$.each($(".revenue"), function() {
var val = $.trim($(this).val());
if(val != "")
sumRevenue += parseFloat(val);
});
$("#sumrevenue").val(sumRevenue);
});
function calculateTotalREv(){
var totalRev = 0;
$("input[name='Output']").each(function() {
totalRev = eval(total+parseFloat($(this).val()));
});
alert(totalRev);
}
calculateTotalREv();

Categories

Resources