Optimize the repetitive code for adding new option to select jquery - javascript

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>

Related

JQuery Replace Function Did Not Work On Certain Select Dropdown

What I want to do is replace the id for every input. I have several inputs in my page.
This is the coding for some user input
<div class="row">
<div class="col">
<div class="form-group row">
<label class="col-md-2 col-form-label" for="daddr3_1">Address 3:</label>
<div class="col-md-9">
<input class="form-control" rows="1" maxlength="30" type="text" id="daddr3_1" name="daddr3[]" placeholder="Third line of address as in Identity Card (optional)">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<?php
include_once "common.php";
$common = new Common();
$countries = $common->getCountry($connection);
?>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="countryId_1">Country:</label>
<div class="col-md-5">
<select name="countryId[]" id="countryId_1" class="form-control" onchange="getStateByCountry();">
<option>Country</option>
<?php
if ($countries->num_rows > 0 ){
while ($country = $countries->fetch_object()) {
$countryName = $country->name; ?>
<option value="<?php echo $country->id; ?>"><?php echo $countryName;?></option>
<?php }
}
?>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="stateId_1">State:</label>
<div class="col-md-5">
<select name="stateId[]" id="stateId_1" class="form-control" onchange="getCityByState();getPostalByState()">
<option>State</option>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="cityDiv_1">City:</label>
<div class="col-md-5">
<select name="cityDiv[]" id="cityDiv_1" class="form-control">
<option value="">City</option>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="dpostal">Postal:</label>
<div class="col-md-5">
<select name="postalDiv[]" id="postalDiv_1" class="form-control">
<option>Postal</option>
</select>
</div>
</div>
</div>
</div>
I want to increase the _1 of the input if user add more than one item by duplicating the form.
This is the script to replace the _1 everytime user duplicate the form.
var attrs = ['for', 'id', 'name'];
function resetAttributeNames(section) {
var tags = section.find('input, label, select'), idx = section.index();
tags.each(function() {
var $this = $(this);
$.each(attrs, function(i, attr) {
var attr_val = $this.attr(attr);
if (attr_val) {
$this.attr(attr, attr_val.replace(/_\d+$/, '_'+(idx + 1)))
}
})
})
}
As you can see, in user input for country, state, city, and postal I used onchange function. I wonder if it ain't working because of the onchange function. Because the id can be replaced for Address 3 input. Only the list I mention above is not working.
This is the script of onchange function
<script>
function getStateByCountry() {
var countryId = $("#countryId_1").val();
$.post("ajax.php",{getStateByCountry:'getStateByCountry',countryId:countryId},function (response) {
var data = response.split('^');
$("#stateId_1").html(data[1]);
});
}
function getCityByState() {
var stateId = $("#stateId_1").val();
$.post("ajax.php",{getCityByState:'getCityByState',stateId:stateId},function (response) {
var data = response.split('^');
$("#cityDiv_1").html(data[1]);
});
}
function getPostalByState() {
var stateId = $("#stateId_1").val();
$.post("ajax.php",{getPostalByState:'getPostalByState',stateId:stateId},function (response) {
var data = response.split('^');
$("#postalDiv_1").html(data[1]);
});
}
function enable(){
var check = document.getElementById("check");
var btn = document.getElementById("btn");
if(check.checked){
btn.removeAttribute("disabled");
}
else{
btn.disabled = "true";
}
}
</script>
Any help is appreciated :)

on change function also affect on clone div

i want to show and hide div base on change function.. and its work well on first div whenever i add(append) new div that time change function affect in both div.
$(".transport_type").hide();
$(".rate").hide();
$(".adult").hide();
$(".child").hide();
$("body").on("change", "#transport_cat", function(e) {
e.preventDefault();
if($(this).val() == 'PVT') {
$('.rate').show();
} else {
$('.rate').hide();
}
if($(this).val() == 'SIC') {
$('.adult').show();
$('.child').show();
} else {
$('.adult').hide();
$('.child').hide();
}
});
here is a demo here
i want to do only show hide div on change that select div not want to affect on another div.please help me...
Couple of mistakes:
Do not use id attribute for transport_cat element as this element is getting cloned and multiple elements with same id is wrong
While hide/show div, set the context as well, just $('.rate').show() will show all divs with rate class. So set context.
Remove $("body").on("change", "#transport_cat", function(e) { binding of change event while cloning as you are using $.on() method
I have updated the fiddle - https://jsfiddle.net/swpL5xwp/2/
<select class="form_line_only form-control className transport_cat" name="tr_cartypes[]">
<option selected> Select Tour </option>
<option value="PVT"> PVT </option>
<option value="SIC"> SIC </option>
</select>
$("body").on("change", ".transport_cat", function(e) {
e.preventDefault();
var $context = $(this).parents('.entry_special_offers');
if ($(this).val() == 'PVT') {
$('.rate',$context).show();
} else {
$('.rate',$context).hide();
}
if ($(this).val() == 'SIC') {
$('.adult',$context).show();
$('.child',$context).show();
} else {
$('.adult',$context).hide();
$('.child',$context).hide();
}
});
Couple of things you need to look into,
You need to find the closest entry_special_offers class.
You need fix your current implementation where you find all elements with class rate / adult and others. You should find them withing current entry_special_offers div only.
Also you have attached change events twice which is not required.
$(".transport_type").hide();
$(".rate").hide();
$(".adult").hide();
$(".child").hide();
$("body").on("change", "#transport_cat", function(e) {
e.preventDefault();
if ($(this).val() == 'PVT') {
$(this).closest(".entry_special_offers").find('.rate').show();
} else {
$(this).closest(".entry_special_offers").find('.rate').hide();
}
if ($(this).val() == 'SIC') {
$(this).closest(".entry_special_offers").find('.adult').show();
$(this).closest(".entry_special_offers").find('.child').show();
} else {
$(this).closest(".entry_special_offers").find('.adult').hide();
$(this).closest(".entry_special_offers").find('.child').hide();
}
});
$(function()
{
$(document).on('click', '.btn-add', function(e)
{
e.preventDefault();
var controlForm = $('.controls_special_offers:first'),
currentEntry = $(this).closest('.entry_special_offers'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.entry_special_offers:not(:last) .btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}).on('click', '.btn-remove', function(e)
{
$(this).closest('.entry_special_offers').remove();
e.preventDefault();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container excursions margin_top">
<!--container hotel -->
<div class="controls_special_offers">
<div class="entry_special_offers input-group col-sm-12 col-xs-12 ">
<div class="col-sm-2 col-xs-6">
<div class="form-group">
<label for="exampleInputindate">Tour</label>
<div class="form-group">
<select class="form_line_only form-control className" name="tr_cartypes[]" id="transport_cat">
<option selected>Select Tour</option>
<option value="PVT">PVT</option>
<option value="SIC">SIC</option>
</select>
</div>
</div>
</div>
<div class="col-sm-3 col-xs-6 transport_type">
<div class="form-group">
<label for="exampleInputindate">transportation type</label>
<div class="form-group">
<select class="form_line_only form-control " name="tr_seattype[]">
<option selected>Select Type</option>
<option>7 Seater</option>
<option>15 Seater</option>
<option>34 Seater</option>
<option>50 Seater</option>
</select>
</div>
</div>
</div>
<div class="col-sm-2 col-xs-6 rate">
<div class="form-group ">
<label for="exampleInputindate">rate</label>
<div class="form-group">
<input type="number" name="tc_rates[]" id="tc_rate" class=" form_line_only form-control" placeholder="Enter Price" value="" autocomplete="off">
</div>
</div>
</div>
<div class="col-sm-2 col-xs-6 adult">
<div class="form-group">
<label for="exampleInputindate">Adult</label>
<div class="form-group">
<input type="number" name="tc_adults[]" id="tc_adult" class=" form_line_only form-control" placeholder="Adult Price" value="" autocomplete="off">
</div>
</div>
</div>
<div class="col-sm-2 col-xs-6 child">
<div class="form-group">
<label for="exampleInputindate">Child</label>
<div class="form-group">
<input type="number" name="tc_childs[]" id="tc_child" class=" form_line_only form-control" placeholder=" Child Price " value="" autocomplete="off">
</div>
</div>
</div>
<span class="input-group-btn day_plan pull-left">
<button class="btn btn-success btn-add add_col" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
<br>
</div>
</div>

Changing the message in onblur event upon condition for all input fields in jquery

I have more than 20 input fields with onblur defined in all the fields with its respective message in it. Upon condition, i wanted to change the message.
Following is my HTML code:
<div class="form-group">
<div class="col-sm-2"></div>
<label for="fullname1" class="col-sm-3 control-label">
<span id="w7_E">Full Name</span>
<span id="w7_B">Poskod</span>
</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="fullname1" name="fullname" onkeyup="checkKeyUp(this);" onblur="checkOnBlur(this,'Please Enter Your fullname');" placeholder="Name">
</div>
<div class="col-sm-3"></div>
<div class="text-danger" data-valmsg-replace="true" data-valmsg-for="fullname1"></div>
</div>
<div class="form-group">
<div class="col-sm-2"></div>
<label for="postcode1" class="col-sm-3 control-label">
<span id="w20_E">Postcode</span>
<span id="w20_B">Poskod</span></label>
<div class="col-sm-4">
<input type="text" class="form-control" id="postcode1" name="postcode" placeholder="Postcode" onkeyup="checkKeyUp(this);fetch_state(this);" onblur="checkOnBlur(this,'Please Enter Your Postcode');">
</div>
<div class="col-sm-3"></div>
</div>
<div class="form-group">
<div class="col-sm-2"></div>
<label for="state1" class="col-sm-3 control-label">
<span id="w21_E">State</span>
<span id="w21_B">Negeri</span></label>
<div class="col-sm-4">
<input type="text" class="form-control" id="state1" name="state" placeholder="State" onkeyup="checkKeyUp(this);" onblur="checkOnBlur(this,'Please Enter Your State');">
</div>
<div class="col-sm-3"></div>
</div>
My Jquery code:
function checkOnBlur(me, message) {
var e_id = $(me).attr('name');
var element_name= (this.name);
if (!(me.val()).length) {
var exist = document.getElementById(e_id + '_e');
var langID='<%=session.getAttribute("language_sel")%>';
if (exist == null) {
var htmlString = "";
if(langID == 'B') {
if (element_name == "fullname") {
message = "Sila masukkan nama penuh penama";
}
if (element_name == "postcode") {
message = "Sila masukkan poskod";
}
if (element_name == "state") {
message = "Sila masukkan negeri";
}
}
htmlString += '<label id=' + e_id + '_e' + ' ' + 'class="error">' + message + '</label>';
$(htmlString).insertAfter("#" + e_id);
$('#' + e_id).focus();
}
}
}
If langID = "B", message in jquery code should appear.
Please help me to resolve this.
Thanks in advance.

Unable to dynamically add name attribute to form element

I wish to dynamically add the name attribute as 'pickup_city2' and 'pickup_address2' to select elements with ids, pickup_cityExtend and pickup_addressExtend.
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id').insertAfter($pick);
var city = document.getElementById('pickup_cityExtend');
city.setAttribute('name', 'pickup_city2');
var address = document.getElementById('pickup_addressExtend');
address.setAttribute('name', 'pickup_address2');
}
if (!this.checked) {
$clone.remove();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="cityPick form-horizontal form-label-right" action="" method="POST" novalidate>{% csrf_token %}
<div class="form-group">
<div class="city col-md-4 col-sm-4 col-xs-10">
<div class="item form-group">
<label class="control-label" for="city">City<span class="required">*</span>
</label>
<div class="">
<select class="form-control" id="city" name="pick_up_city">
<option>Select City</option>
<option>Mumbai</option>
<option>Delhi</option>
<option>Jaipur</option>
</select>
</div>
</div>
</div>
<div class="address col-md-7 col-sm-7 col-xs-10">
<div class="item form-group">
<label class="control-label" for="address">Address<span class="required">*</span>
</label>
<div class="">
<input type="text" class="form-control" id="address" name="pick_up_address">
</div>
</div>
</div>
<div class="multiCheck col-md-4 col-sm-4 col-xs-12">
<input type="checkbox" value="Yes" id="multiCheck">Have more than one pickup point?
<br>
</div>
</div>
<div class="form-group hide" id="cityPickExtend">
<div class="city col-md-4 col-sm-4 col-xs-10">
<div class="item form-group">
<label class="control-label" for="city">City<span class="required">*</span>
</label>
<div class="">
<select class="form-control" id="pickup_cityExtend" name="">
<option>Select City</option>
<option>Mumbai</option>
<option>Delhi</option>
<option>Jaipur</option>
</select>
</div>
</div>
</div>
<div class="address col-md-7 col-sm-7 col-xs-10">
<div class="item form-group">
<label class="control-label" for="address">Address<span class="required">*</span>
</label>
<div class="">
<input type="text" class="form-control" id="pickup_addressExtend" name="">
</div>
</div>
</div>
<div class="removeBtn col-md-1 col-sm-1 col-xs-2">
<button type="button" id="removeBtn">Remove</button>
</div>
<div class="addBtn">
<button type="button" id="addBtn">Add another pickup location</button>
</div>
</div>
<div class="item form-group">
<label for="shipment_datetime" class="control-label dateTime">Pickup Date & time
<span class="required">*</span>
</label>
<div class="input-group date form_datetime col-md-4 col-sm-4 col-xs-12" data-date="" data-date-format="dd MM yyyy - HH:ii p" data-link-field="dtp_input1">
<input class="form-control" size="16" name="shipment_datetime" type="text" value="" readonly style="background-color: #fff;">
<span class="input-group-addon">
<span class="glyphicon glyphicon-remove"></span>
</span>
<span class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</span>
</div>
</div>
</form>
Below is my jquery code.
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id').insertAfter($pick);
var city = document.getElementById('pickup_cityExtend');
city.setAttribute('name', 'pickup_city2');
var address = document.getElementById('pickup_addressExtend');
address.setAttribute('name', 'pickup_address2');
}
if (!this.checked) {
$clone.remove();
}
})
Within the part that you clone, there are four elements that have an id attribute. As id values must be unique, the DOM API will always return the first match when you query for a certain id, such as in these lines:
var city = document.getElementById('pickup_cityExtend');
var address = document.getElementById('pickup_addressExtend');
The results do not match the elements in the part you added to the document.
In order to make it work, you need to replace the id values with something that is unique (by adding a 2 for instance).
As a side note: you are mixing jQuery syntax with native DOM methods to retrieve elements. It would be more consistent if you would not use document.getElementById, but the jQuery $('#...') equivalent.
Here is some adjusted code:
var $clone;
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id');
// Add '2' to all ID values, and set name value to the same.
$clone.find('[id]').each(function () {
var id = $(this).attr('id') + '2';
$(this).attr('id', id).attr('name', id);
});
// Now that the id value are unique, it is OK to add the clone:
$clone.insertAfter($pick);
} else if ($clone) { // Check whether we actually have a clone
$clone.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