Form field values sum in jQuery - javascript

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();

Related

How to sum the values from dynamically created input fields

I have created Dynamic Add / Remove fields. Everything is working perfectly. I want sum of values from Amount field to be displayed on real time basis using JavaScript. I have tried but am unable to do. I am not much familiar with JavaScript.
Following is code:
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id="code" name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount.</i></small>
<div id="sum"></div>
</div>
</div>
You can use add keyup event listener and calculate sum as:
function calculateSum() { //Add a calculateSum function
var sum = 0;
$("input[name='allocate_amount[]']").each(function() {
sum += +this.value || 0;
});
$("#sum").text(sum);
}
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
calculateSum(); //Call calculateSum to update the sum valaue
return false;
});
});
$("body").on("keyup", "input[name='allocate_amount[]']", calculateSum); //update when keyup
Demo:
var i = 0;
jQuery(document).ready(function($) {
function calculateSum() {
var sum = 0;
$("input[name='allocate_amount[]']").each(function() {
sum += +this.value || 0;
});
$("#sum").text(sum);
}
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
calculateSum();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
$("body").on("keyup", "input[name='allocate_amount[]']", calculateSum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id="code" name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount.</i></small>
<div id="sum"></div>
</div>
</div>
I think you can do it with this code:
function calcAmount(){
var amount = 0;
$('input[name="allocate_amount[]"]').each(function(){
amount = amount + $(this).val();
});
return amount;
}
jQuery(document).ready(function($) {
$("input[name="allocate_amount[]]").blur(function(){
$("#sum").html(calcAmount());
});
});
Okay, I try to update your code: and it works fine:
main changes:
- assign ids to input fields
- make changes in function
have a look to jsfiddle
https://jsfiddle.net/dupinderdhiman/ygvphmxq/31/
Main changes:
var sum = eval($('#value1').val()) + eval($('#value2').val());
$('#sum').text(sum);
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" id='value1' name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id='value2' name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount. <span id="sum"></span></i></small>
</div>
</div>
<script type="text/javascript">
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
debugger;
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
var sum = eval($('#value1').val()) + eval($('#value2').val());
$('#sum').text(sum);
return false;
});
});
</script>
</body>
</html>

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>

JavaScript - How to navigation one textbox to another textbox using arrow key

JavaScript - How to navigation one textbox to another textbox using arrow key
I have many code test but not working please see below my html code and JavaScript Code
<div class="col-md-12" style="margin-top: 15px;">
<div class="col-md-2">
<div class="form-group">
<label>Date & Time</label>
<input name="date_and_time" class="form-control" readonly value="<?=date('Y-m-d H:i:s')?>" type="text">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Invoice Number</label>
<input name="invoice_number" class="form-control" readonly value="39" type="text">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Search Customer by Mobile / Name</label>
<input name="customer_search_mobile_name" class="form-control" value="" type="text">
</div>
</div>
</div>
JavaScript Code
<script type="text/javascript">
$(document).keydown(
function(e)
{
if (e.keyCode == 39) {
$(".form-control:focus").next().focus();
}
if (e.keyCode == 37) {
console.log('hi');
$(".form-control:focus").prev().focus();
}
}
);
</script>
Try this Code:
Plunker Link
HTML
<div class="col-md-12" style="margin-top: 15px;">
<div class="col-md-2">
<div class="form-group">
<label>Date & Time</label>
<input name="date_and_time" class="form-control" value="<?=date('Y-m-d H:i:s')?>" type="text">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Invoice Number</label>
<input name="invoice_number" class="form-control" value="39" type="text">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Search Customer by Mobile / Name</label>
<input name="customer_search_mobile_name" class="form-control" value="" type="text">
</div>
</div>
</div>
JS
var isShift = false;
$("input").keydown(function(e){
if(e.keyCode==16)
isShift = true;
if ((e.keyCode==40 || e.keyCode==39) && !isShift) {
$(this).parent().parent().next().find('input').focus()
}
else if ((e.keyCode==37 || e.keyCode==38) && !isShift) {
$(this).parent().parent().prev().find('input').focus()
}
});
$("input").keyup(function(e){
if(e.keyCode==16)
isShift = false;
});
<input class="my_input">
<input class="my_input">
<input class="my_input">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$('.my_input').keyup(function(e) {
if (e.keyCode == 39) {
var inputs = $('.my_input'); // array of all inputs
var index = inputs.index(this); // search which of the inputs is active
var newIndex = (index+1) % inputs.length; // index + 1, but cycle back to 0
$('.my_input').eq(newIndex).focus();
}
if (e.keyCode == 37) {
var inputs = $('.my_input'); // array of all inputs
var index = inputs.index(this); // search which of the inputs is active
var newIndex = index - 1; // index - 1
if(newIndex<0) {
newIndex = inputs.length - 1; // cycle to last element
}
$('.my_input').eq(newIndex).focus();
}
return true;
});
</script>

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.

disable an input if another input is clicked

I have three sections in a form, the first one contains one input and the second contains three inputs and the third contains a checkbox. How to
disable the two sections if checkbox is checked
disable the checkbox and a section if I tapped a text in the other section
enable the three sections if all of them are empty
I must have only one active section everytime.
What I did is not the solution because there is a problem in the second section. if only one input is empty in this section all the other inputs are enabled. any one can help me please.
Thanks and sorry about my english
document.getElementById("client").onblur = function () {
if (this.value.length > 0) {
document.getElementById("FirstName").disabled=true;
document.getElementById("LastName").disabled=true;
document.getElementById("Email").disabled=true;
document.getElementById("standard").disabled=true;
}else {
document.getElementById("FirstName").disabled=false;
document.getElementById("LastName").disabled=false;
document.getElementById("Email").disabled=false;
document.getElementById("standard").disabled=false;
}
}
document.getElementById("FirstName").onblur = function () {
if (this.value.length > 0) {
document.getElementById("client").disabled=true;
document.getElementById("standard").disabled=true;
}else {
document.getElementById("client").disabled = false;
document.getElementById("standard").disabled = false;
}
}
document.getElementById("LastName").onblur = function () {
if (this.value.length > 0) {
document.getElementById("client").disabled=true;
document.getElementById("standard").disabled=true;
}else {
document.getElementById("client").disabled = false;
document.getElementById("standard").disabled = false;
}
}
document.getElementById("Email").onblur = function () {
if (this.value.length > 0) {
document.getElementById("client").disabled=true;
document.getElementById("standard").disabled=true;
}else {
document.getElementById("client").disabled = false;
document.getElementById("standard").disabled = false;
}
}
document.getElementById("standard").onblur = function () {
if (this.checked) {
document.getElementById("client").disabled=true;
document.getElementById("FirstName").disabled=true;
document.getElementById("LastName").disabled=true;
document.getElementById("Email").disabled=true;
}else {
document.getElementById("client").disabled=false;
document.getElementById("FirstName").disabled=false;
document.getElementById("LastName").disabled=false;
document.getElementById("Email").disabled=false;
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-md-4">
<div class="row">
<div class="form-group col-md-12">
<label>Search Client</label>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<div class="input-group custom-search-form margin-bottom">
<input id="client" name="client" type="text" class="form-control input-sm" placeholder="Search...">
<span class="input-group-btn">
<button class="btn btn-default btn-sm" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</div>
</div>
</div>
<div class="col-md-8">
<div class="row">
<div class="form-group col-md-12">
<label>New Client</label>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<input type="text" class="form-control input-sm" id="FirstName" placeholder="First Name">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control input-sm" id="LastName" placeholder="Last Name">
</div>
<div class="form-group col-md-4">
<input type="email" class="form-control input-sm" id="Email" placeholder="Email">
</div>
</div>
</div>
</div>
<div class="checkbox margin-bottom">
<label>
<input id="standard" type="checkbox" value="">Standard
</label>
</div>
It sounds like you may want try the focus listener instead of the on Blur listener.
https://developer.mozilla.org/en-US/docs/Web/Events/focus
The second element seems to work when I entered in values for all of the fields. It looks like it's checking the length of what was entered.

Categories

Resources