How to decrease and increase the value of a textbox? - javascript

I have a booking flight form that takes input of the number of travelers. I created 3 textboxes each taking in number of travelers for Adult, Children and Infant and a main textbox to show the final result in it, however it does not work.
Here is my code snippet:
$(function() {
$(".button-click a").on("click", function() {
var $button = $(this);
var oldValue = $button.closest("ul").prev().val();
if ($button.text() == "+") {
var newVal = parseInt(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseInt(oldValue - 1);
} else {
newVal = 0;
}
}
$button.closest("ul").prev().val(newVal);
var total_value = 0;
$(".cat_textbox").each(function() {
total_value += parseInt($(this).val());
});
$(".main").val(total_value);
})
});
<html>
<head>
<title>Input Number Incrementer</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<label>
Count all1 Traveller(s)
<input type="text" class="main" value="0" placeholder="" />
</label>
<br/>
<br/>
<label>
Adults
<ul class="button-group button-click">
<li><i class="fa fa-plus"><span class="hide">+</span></i>
</li>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
<li><i class="fa fa-minus"><span class="hide">-</span></i>
</li>
</ul>
</label>
<label>
Children
<ul class="button-group button-click">
<li><i class="fa fa-plus"><span class="hide">+</span></i>
</li>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
<li><i class="fa fa-minus"><span class="hide">-</span></i>
</li>
</ul>
</label>
<label>
Infants
<ul class="button-group button-click">
<li><i class="fa fa-plus"><span class="hide">+</span></i>
</li>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
<li><i class="fa fa-minus"><span class="hide">-</span></i>
</li>
</ul>
</label>
</body>
</html>

You can have 2 different handlers for + and - and search input using this
$(function() {
registerEvents();
});
function registerEvents(){
$('.button-group .fa-plus').on('click', function(){
var input = $(this).closest('li').next()
input.val(+input.val() + 1);
updateTravellerCount();
return false;
})
$('.button-group .fa-minus').on('click', function(){
var input = $(this).closest('li').prev()
var val = +input.val() > 0 ? +input.val() - 1 : 0
input.val(val);
updateTravellerCount();
return false;
});
}
function updateTravellerCount(){
var total = 0;
$.each($('.button-group input'), function(){
total += +$(this).val();
});
$('.main').val(total)
}
<html>
<head>
<title>Input Number Incrementer</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<label>
Count all1 Traveller(s)
<input type="text" class="main" value="0" placeholder="" />
</label>
<br/>
<br/>
<label>
Adults
<ul class="button-group button-click">
<li><i class="fa fa-plus"><span class="hide">+</span></i>
</li>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
<li><i class="fa fa-minus"><span class="hide">-</span></i>
</li>
</ul>
</label>
<label>
Children
<ul class="button-group button-click">
<li><i class="fa fa-plus"><span class="hide">+</span></i>
</li>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
<li><i class="fa fa-minus"><span class="hide">-</span></i>
</li>
</ul>
</label>
<label>
Infants
<ul class="button-group button-click">
<li><i class="fa fa-plus"><span class="hide">+</span></i>
</li>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
<li><i class="fa fa-minus"><span class="hide">-</span></i>
</li>
</ul>
</label>
</body>
</html>
I have tried to make it more modular. Not my best attempt but might help JSFiddle

You are using the selector ".button-click a" which should be ".button-click > a"
which would denote an a element with an element with the class button-click as a parent

I have added two different classes to the anchor tags and formatted the jQuery to keep things clean and easy.
Plnkr Demo:
http://plnkr.co/edit/GqOeRWaaAq8BjeQSVDHc?p=preview
Stack Snippet:
$(function() {
$(".button-click a").on("click", function() {
var $button = $(this);
var oldValue = $button.closest("ul").children('input').val();
if ($button.hasClass('plus')) {
var newVal = parseInt(oldValue) +1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseInt(oldValue - 1);
} else {
newVal = 0;
}
}
$button.closest("ul").children('input').val(newVal)
var total_value = 0;
$(".cat_textbox").each(function(){
total_value += parseInt($(this).val());
});
$(".main").val(total_value);
})
});
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
</head>
<body>
<label>
Count all1 Traveller(s)
<input class="main" value="0" placeholder="" type="text" />
</label>
<br />
<br />
<label>
Adults
<ul class="button-group button-click">
<li>
<a href="#" class="small button secondary plus">
<i class="fa fa-plus">
<span class="hide">+</span>
</i>
</a>
</li>
<input class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" type="text" />
<li>
<a href="#" class="small button secondary minus">
<i class="fa fa-minus">
<span class="hide">-</span>
</i>
</a>
</li>
</ul>
</label>
<label>
Children
<ul class="button-group button-click">
<li>
<a href="#" class="small button secondary plus">
<i class="fa fa-plus">
<span class="hide">+</span>
</i>
</a>
</li>
<input class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" type="text" />
<li>
<a href="#" class="small button secondary minus">
<i class="fa fa-minus">
<span class="hide">-</span>
</i>
</a>
</li>
</ul>
</label>
<label>
Infants
<ul class="button-group button-click">
<li>
<a href="#" class="small button secondary plus">
<i class="fa fa-plus">
<span class="hide">+</span>
</i>
</a>
</li>
<input class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" type="text" />
<li>
<a href="#" class="small button secondary minus">
<i class="fa fa-minus">
<span class="hide">-</span>
</i>
</a>
</li>
</ul>
</label>
</body>
</html>

Some older browsers may have issues with <input type="number" why don't you try something like this :
<html>
<head>
<title>Input Number Incrementer</title>
</head>
<body>
<label>
Count all1 Traveller(s)
<input type="text" class="main" value="0" placeholder="" />
</label>
<br/><br/>
<label>
Adults
<ul class="button-group button-click">
<li><i class="fa fa-plus"><span class="hide">+</span></i></li>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
<li><i class="fa fa-minus"><span class="hide">-</span></i></li>
</ul>
</label>
<label>
Children
<ul class="button-group button-click">
<li><i class="fa fa-plus"><span class="hide">+</span></i></li>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
<li><i class="fa fa-minus"><span class="hide">-</span></i></li>
</ul>
</label>
<label>
Infants
<ul class="button-group button-click">
<li><i class="fa fa-plus"><span class="hide">+</span></i></li>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
<li><i class="fa fa-minus"><span class="hide">-</span></i></li>
</ul>
</label>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(function() {
$(".button-click a").on("click", function() {
var $button = $(this);
var input = $button.closest("ul").find("input");
var oldValue = parseInt(input.val());
var newVal = 0;
var total_value = 0;
if ($button.text() == "+") {
newVal = parseInt(oldValue) +1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
newVal = parseInt(oldValue - 1);
} else {
newVal = 0;
}
}
$(input).val(newVal);
$(".cat_textbox").each(function(){
total_value += parseInt($(this).val());
});
$(".main").val(total_value);
});
});
</script>
</body>
</html>

Try This:
I have modified your existing function little bit.
$(function() {
$(".button-click a").on("click", function() {
var $button = $(this);
var mainCount=$('.main').val();
var bText= $button.text();
var oldVal=$button.closest("ul").children('input').val();
var nexVal=null;
if(bText=='+'){
nexVal=parseInt(oldVal) +1;
mainCount=parseInt(mainCount) +1;
}else{
nexVal=parseInt(oldVal) -1;
mainCount=parseInt(mainCount) -1;
}
$button.closest("ul").children('input').val(nexVal);
$('.main').val(mainCount);
});
});

Related

onclick not firing on first click (answer only in Plain Javascript)

Here is my Html Code
<div>
<input type="checkbox" class="input-checkbox-correct" name="checkCheckbox"
onclick="addRightAnswer();">
<input type="text"
placeholder="Enter your option"
class="form-control-range-number"
id="get-radio-input5"
name="get-radio-input"><input
type="number" class="get-radio-input-number" value="0"
name="get-radio-input"/>
<button type="click" onclick="addMoreOptions(this)"><i
class="fa fa-plus-circle" aria-hidden="true"></i></button>
<button type="click" onclick="removeOptions(this)"><i
class="fa fa-minus-circle" aria-hidden="true"></i></button>
</div>
<div>
<input type="checkbox" class="input-checkbox-correct" name="checkCheckbox"
onclick="addRightAnswer();">
<input type="text"
placeholder="Enter your option"
class="form-control-range-number"
id="get-radio-input5"
name="get-radio-input">
<input
type="number" class="get-radio-input-number" value="0"
name="get-radio-input"/>
<button type="click" onclick="addMoreOptions(this)"><i
class="fa fa-plus-circle" aria-hidden="true"></i></button>
<button type="click" onclick="removeOptions(this)"><i
class="fa fa-minus-circle" aria-hidden="true"></i></button>
</div>
<div>
<input type="checkbox" class="input-checkbox-correct" name="checkCheckbox"
onclick="addRightAnswer();">
<input type="text"
placeholder="Enter your option"
class="form-control-range-number"
id="get-radio-input5"
name="get-radio-input">
<input
type="number" class="get-radio-input-number" value="0"
name="get-radio-input"/>
<button type="click" onclick="addMoreOptions(this)"><i
class="fa fa-plus-circle" aria-hidden="true"></i></button>
<button type="click" onclick="removeOptions(this)"><i
class="fa fa-minus-circle" aria-hidden="true"></i></button>
</div>
<div>
<input type="checkbox" class="input-checkbox-correct" name="checkCheckbox"
onclick="addRightAnswer();">
<input type="text"
placeholder="Enter your option"
class="form-control-range-number"
id="get-radio-input5"
name="get-radio-input">
<input
type="number" class="get-radio-input-number" value="0"
name="get-radio-input"/>
<button type="click" onclick="addMoreOptions(this)"><i
class="fa fa-plus-circle" aria-hidden="true"></i></button>
<button type="click" onclick="removeOptions(this)"><i
class="fa fa-minus-circle" aria-hidden="true"></i></button>
</div>
This is my Javascript Code
function addRightAnswer() {
var getRadioOptionsNumberCheck = document.querySelectorAll('.input-checkbox-correct');
var getRadioInputNumber = document.querySelectorAll('.get-radio-input-number');
getRadioOptionsNumberCheck.forEach(function(current, index) {
current.addEventListener('click', function() {
if (current.checked) {
getRadioInputNumber[index].value = 1; //
}
else
{
getRadioInputNumber[index].value = 0;
}
});
});
}
initially value is 0 after one click value wiill increase by 1 , but in my case everything is working But First click on Checkbox value is not increasing in 2nd click value is increasing
You don't need to add an Event Listener if you already call addRightAnswer() on click.
Right now when you click the checkbox, you add the event listener, which will then modify the input value at the next click.
function addRightAnswer() {
var getRadioOptionsNumberCheck = document.querySelectorAll('.input-checkbox-correct');
var getRadioInputNumber = document.querySelectorAll('.get-radio-input-number');
getRadioOptionsNumberCheck.forEach(function(current, index) {
if (current.checked) {
getRadioInputNumber[index].value = 1; //
} else {
getRadioInputNumber[index].value = 0;
}
});
}
<div><input type="checkbox" class="input-checkbox-correct" name="checkCheckbox" onclick="addRightAnswer();"><input type="text" placeholder="Enter your option" class="form-control-range-number" id="get-radio-input5" name="get-radio-input"><input type="number"
class="get-radio-input-number" value="0" name="get-radio-input" /><button type="click" onclick="addMoreOptions(this)"><i class="fa fa-plus-circle" aria-hidden="true"></i></button><button type="click" onclick="removeOptions(this)"><i class="fa fa-minus-circle" aria-hidden="true"></i></button></div>

How to set a function on group of child that recently appended

I wrote the below code for a booking flight and it works good. when i click on class that called firstadd it will append a new div under page. my problem is the plus and the minus that recently added not work. i want to click on each plus and minus then the value of each textbox change . the same as div with classname : new
here is my snippet :
$(function() {
var createChildDropdown = function(i) {
var $childDropdown = $('<div />', {
'class': 'childs'
});
$childDropdown.append($('<label />', {
'for': 'childDropdown-' + i
}).text('Child ' + i));
$childDropdown.append($('<select />', {
'id': 'childDropdown-' + i
}));
var options = ['a', 'b', 'c'];
options.forEach(function(option, index) {
$childDropdown.find('select').append($('<option />')
.text(option).attr('value', index));
});
return $childDropdown;
};
var destroyChildDropdown = function($el, i) {
$el.find('div.childs').get(i).remove();
};
$(".button-click a").on("click", function() {
var html = '<div class="new">'+
'<label>'+
'<span>Adult</span>'+
'<input type="text" class="travel" id="CAT_Custom_410672" name="CAT_Custom_410672" value="0" />'+
'<ul class="button-group button-click">'+
'<li><i class="fa fa-plus"><span class="hide">+</span></i></li>'+
'<li><i class="fa fa-minus"><span class="hide">-</span></i></li>'+
'</ul>'+
'</label>'+
'<label>'+
'<span>Child</span>'+
'<input type="text" class="travel" id="CAT_Custom_410672" name="CAT_Custom_410672" value="0" />'+
'<ul class="button-group button-click">'+
'<li><i class="fa fa-plus"><span class="hide">+</span></i></li>'+
'<li><i class="fa fa-minus"><span class="hide">-</span></i></li>'+
'</ul>'+
'</label>'+
'</div>';
$("#collectnew").append(html);
var button = $(this);
var oldVal = parseInt(button.closest("ul").prev().val());
var newVal = (button.text() == "+") ? oldVal + 1 : (oldVal > 0) ? oldVal - 1 : 0;
var total_value = "";
button.closest("ul").prev().val(newVal);
$(".travel").each(function() {
var cat = $(this).prev('span').text();
total_value += cat + ": " + $(this).val() + ", ";
});
total_value = total_value.substring(0, total_value.length - 2);
$(".main").val(total_value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label>
Count Room
<input type="text" name="no_travellers" class="main" value="Room:1, Adult:1" placeholder="" />
</label>
<br/>
<label>
<span>Room</span>
<input type="text" class="travel" id="CAT_Custom_410672" name="CAT_Custom_410672" value="1" />
<ul class="button-group button-click">
<li><i class="fa fa-plus firstadd"><span class="hide">+</span></i></li>
<li><i class="fa fa-minus firstadd"><span class="hide">-</span></i></li>
</ul>
</label>
<div id="collectnew">
<div class="new" style="border:1px solid red;">
<label>
<span>Adult</span>
<input type="text" class="travel" id="CAT_Custom_410672" name="CAT_Custom_410672" value="0" />
<ul class="button-group button-click">
<li><i class="fa fa-plus"><span class="hide">+</span></i></li>
<li><i class="fa fa-minus"><span class="hide">-</span></i></li>
</ul>
</label>
<label>
<span>Child</span>
<input type="text" class="travel" id="CAT_Custom_410672" name="CAT_Custom_410672" value="0" />
<ul class="button-group button-click-child">
<li><i class="fa fa-plus"><span class="hide">+</span></i></li>
<li><i class="fa fa-minus"><span class="hide">-</span></i></li>
</ul>
</label>
</div>
</div>
<div class="childDropdowns"></div>
$(".button-click a").on("click", function() {}
replace this by
$(document).on("click",".button-click a" ,function() {});

How to Keep Focus on a Dropdown List?

I have created a multi-select dropdown list. Currently when an input is selected, if the user clicks on the label to make a selection, the dropdown list disappears. If they click on the actual checkbox, the list stays in focus. I'd like to keep focus on the dropdown list until the user is finished making their selections and clicks the Submit button; regardless of where they click inside of the list. I've tried various combinations of click/focus listener functions as well as playing with the Bootstrap data attributes, but nothing seems to work.
function ddInputsChanged($inputs, $outputWrapper) {
var $inputs = $('#ddDistrict input');
var $outputWrapper = $('#lblDistrict');
var outputLabel = 'All';
var firstChecked = true;
$inputs.each(function() {
if (this.checked) {
var currentLabel = $(this).next('label').text();
if (firstChecked == true) {
firstChecked = false;
outputLabel = currentLabel;
} else
outputLabel = outputLabel + ', ' + currentLabel;
}
});
$outputWrapper.text(outputLabel);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="col-lg-12">
<div class="button-group" style="padding: 7px 0px 7px 0px; margin-left: 18px;">
<button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown"><span class="glyphicon glyphicon-user"></span> Districts <span class="caret"></span>
</button>
<ul id="ddDistrict" class="dropdown-menu">
<li>
<input type="checkbox" id="inpDist1" value="1">
<label for="inpDist1" class="input small" data-value="1">District 1 (Porter)</label>
</li>
<li>
<input type="checkbox" id="inpDist2" value="2">
<label for="inpDist2" class="input small" data-value="2">District 2 (Jones Jr.)</label>
</li>
<li>
<input type="checkbox" id="inpDist3" value="3">
<label for="inpDist3" class="input small" data-value="3">District 3 (Horne)</label>
</li>
<li>
<input type="checkbox" id="inpDist4" value="4">
<label for="inpDist4" class="input small" data-value="4">District 4 (Haddaway)</label>
</li>
<li>
<input type="checkbox" id="inpDist5" value="5">
<label for="inpDist5" class="input small" data-value="5">District 5 (Duncan)</label>
</li>
<li>
<input type="checkbox" id="inpDist6" value="6">
<label for="inpDist6" class="input small" data-value="6">District 6 (Willner)</label>
</li>
<li>
<input type="checkbox" id="inpDist7" value="7">
<label for="inpDist7" class="input small" data-value="7">District 7 (Brady)</label>
</li>
<li>
<button type="button" class="btn btn-default btn-sm btn-info center-block" onclick="ddInputsChanged('#ddDistrict input', '#lblDistrict');">Submit</button>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div id="lblDistrict"></div>
</div>
</div>
This seemed to do the trick in a little test. Added stop propagation and added code to close the menu after submit.
$(document).on('click', '.dropdown-menu', function (e) {
e.stopPropagation();
});
function ddInputsChanged($inputs, $outputWrapper) {
var $inputs = $('#ddDistrict input');
var $outputWrapper = $('#lblDistrict');
var outputLabel = 'All';
var firstChecked = true;
$inputs.each(function() {
if (this.checked) {
var currentLabel = $(this).next('label').text();
if (firstChecked === true) {
firstChecked = false;
outputLabel = currentLabel;
} else
outputLabel = outputLabel + ', ' + currentLabel;
}
});
$outputWrapper.text(outputLabel);
$(".open").removeClass('open');
}

jQuery not seeing click() event

I'm attempting to change a message describing a product's condition when the user clicks on an element. The code below seems to be valid, however when I click on the element (.conditionOption label), my message is not being changed.
I'm using jQuery 1.7.2, so .live(); is still valid, I have however attempted to switch things to .click() with the same results.
HTML CODE
<div class="productAttributeRow productAttributeConfigurablePickListSet productAttributeRuleCondition" id="a9e1018b0d4a98a6836fdf644eb227a1">
<div class="productAttributeLabel">
<label for="4fe3d80e78f0e0dc478e7ee56e98d3ea">
<span class="required">*</span>
<span class="name">Cosmetic Condition:</span>
<i class="fa fa-info-circle conditionHelp helpIcon modalOpener"></i>
</label>
</div>
<div class="productAttributeValue">
<div class="productOptionViewRectangle conditionOption">
<ul class="list-horizontal">
<li class="option">
<label for="4a43f295a3273a1b90567090ac3fc9f3">
<input type="radio" class="validation" name="attribute[267]" value="1216" id="4a43f295a3273a1b90567090ac3fc9f3">
<span class="name">Excellent</span>
</input>
</label>
</li>
<li class="option">
<label for="f03ed6c05af7ea80dc1b75d853f43026">
<input type="radio" class="validation" name="attribute[267]" value="311" id="f03ed6c05af7ea80dc1b75d853f43026">
<span class="name">Good</span>
</input>
</label>
</li>
<li class="option selected selectedValue">
<label for="1598c6f69093cdf495f564397485e044">
<input type="radio" class="validation" name="attribute[267]" value="312" id="1598c6f69093cdf495f564397485e044" checked="checked">
<span class="name">Fair</span>
</input>
</label>
</li>
</ul>
<div id="conditionExplanationWrapper">
<span id="conditionExplanation">MESSAGE 1</span>
</div>
</div>
</div>
<div class="cf"></div>
</div>
Javascript/jQuery
function conditionExplanation() {
// Set vars for three conditions
var excellentMessage = 'MESSAGE 1';
var goodMessage = 'MESSAGE 2';
var fairMessage = 'MESSAGE 3';
// Assign finder class to div
$('.productOptionViewRectangle:contains("Excellent")').addClass('conditionOption');
// Build wrapper for message
$('.conditionOption').append('<div id="conditionExplanationWrapper"><span id="conditionExplanation"></span></div>');
// Insert message corresponding to .conditionOption .selectedValue
$('.conditionOption label').live('click', function(){
if ($('.conditionOption .selectedValue:contains("Excellent")')) {
$('#conditionExplanation').html(excellentMessage);
} else if ($('.conditionOption .selectedValue:contains("Good")')) {
$('#conditionExplanation').html(goodMessage);
} else if ($('.conditionOption .selectedValue:contains("Fair")')) {
$('#conditionExplanation').html(fairMessage);
}
});
}
See Fiddle at https://jsfiddle.net/mvnxg3t4/
The problem is that you're comparing the same value over and over; instead you should make use of this and then use regular text search:
var value = $(this).text();
if (value.indexOf('Excellent') != -1) {
$('#conditionExplanation').html(excellentMessage);
} else if (value.indexOf('Good') != -1) {
$('#conditionExplanation').html(goodMessage);
} else if (value.indexOf('Fair') != -1) {
$('#conditionExplanation').html(fairMessage);
}
$(document).ready(conditionExplanation);
function conditionExplanation()
{
// Set vars for three conditions
var excellentMessage = 'MESSAGE 1';
var goodMessage = 'MESSAGE 2';
var fairMessage = 'MESSAGE 3';
// Assign finder class to div
$('.productOptionViewRectangle:contains("Excellent")').addClass('conditionOption');
// Build wrapper for message
$('.conditionOption').append('<div id="conditionExplanationWrapper"><span id="conditionExplanation"></span></div>');
// Insert message corresponding to .conditionOption .selectedValue
$('.conditionOption label').live('click', function (e) {
var value = $(this).text();
if (value.indexOf('Excellent') != -1) {
$('#conditionExplanation').html(excellentMessage);
} else if (value.indexOf('Good') != -1) {
$('#conditionExplanation').html(goodMessage);
} else if (value.indexOf('Fair') != -1) {
$('#conditionExplanation').html(fairMessage);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="productAttributeRow productAttributeConfigurablePickListSet productAttributeRuleCondition" id="a9e1018b0d4a98a6836fdf644eb227a1">
<div class="productAttributeLabel">
<label for="4fe3d80e78f0e0dc478e7ee56e98d3ea">
<span class="required">*</span>
<span class="name">Cosmetic Condition:</span>
<i class="fa fa-info-circle conditionHelp helpIcon modalOpener"></i>
</label>
</div>
<div class="productAttributeValue">
<div class="productOptionViewRectangle conditionOption">
<ul class="list-horizontal">
<li class="option">
<label for="4a43f295a3273a1b90567090ac3fc9f3">
<input type="radio" class="validation" name="attribute[267]" value="1216" id="4a43f295a3273a1b90567090ac3fc9f3">
<span class="name">Excellent</span>
</input>
</label>
</li>
<li class="option">
<label for="f03ed6c05af7ea80dc1b75d853f43026">
<input type="radio" class="validation" name="attribute[267]" value="311" id="f03ed6c05af7ea80dc1b75d853f43026">
<span class="name">Good</span>
</input>
</label>
</li>
<li class="option selected selectedValue">
<label for="1598c6f69093cdf495f564397485e044">
<input type="radio" class="validation" name="attribute[267]" value="312" id="1598c6f69093cdf495f564397485e044" checked="checked">
<span class="name">Fair</span>
</input>
</label>
</li>
</ul>
<div id="conditionExplanationWrapper">
<span id="conditionExplanation">MESSAGE 1</span>
</div>
</div>
</div>
<div class="cf"></div>
</div>
Try using on click and add it in on your on load of body.
$(function () {
$('.conditionOption label').click(function () {
});
});

Calculating Values in Radio Button

I am trying to make a nutrition calculator. It should the values in the radio button and display the value, but I have no idea why it isn't working. The code below doesn't seem to work.
<html>
<head>
<script language="JavaScript" type="text/javascript">
$(document).ready(function() {
$('.options').on('change', 'input', function() {
var $self = $(this);
var inputType = $self.attr('type');
if (inputType == 'radio') {
$self.parent('li').addClass('active').siblings().removeClass('active');
} else if (inputType == 'checkbox') {
$self.parent('li').toggleClass('active');
}
runUpdate();
});
});
function runUpdate() {
//get the sum of the elements
var calories = $(".caloriesSum", '.active').sum();
var fat = $(".fatSum", '.active').sum();
var satfat = $(".satfatSum", '.active').sum();
var carbs = $(".carbsSum", '.active').sum();
var protein = $(".proteinSum", '.active').sum();
var sodium = $(".sodiumSum", '.active').sum();
var chloresterol = $(".chloesterolSum", '.active').sum();
//update the total
$("#totalCalories").text(+calories.toString());
$("#totalFat").text(+fat.toString());
$("#totalSatFat").text(+satfat.toString());
$("#totalCarbs").text(+carbs.toString());
$("#totalProtein").text(+protein.toString());
$("#totalSodium").text(+sodium.toString());
$("#totalChloresterol").text(+chloresterol.toString());
}?
</script>
<style type="text/css">
ul.options li span {display:none;}
#totals {padding:20px; background:#eee;}
#totals span {font-weight:bold;}
h4,ul {margin:0 0 15px;}
</style>
</head>
<body>
<form action="" method="post" id="nutform" onsubmit="return false;">
<h2>Taqueria Nutritionals</h2>
<h4>Pick Your Meal</h4>
<!--Radio Buttons with Values -->
<ul class="options">
<li>
<input type="radio" id="wwheatt" name="meal" value="whole_wheat_tortilla"> Whole Wheat Tortilla
<!-- This class contains the values that it should add -->
<span class="caloriesSum">280</span>
<span class="fatSum">6</span>
<span class="satfatSum">0</span>
<span class="carbsSum">44</span>
<span class="proteinSum">8</span>
<span class="sodiumSum">340</span>
<span class="chloesterolSum">0</span>
</li>
<li>
<input type="radio" name="meal" value="flour_tortilla" > Flour Tortilla
<span class="caloriesSum">290</span>
<span class="fatSum">6</span>
<span class="satfatSum">2</span>
<span class="carbsSum">49</span>
<span class="proteinSum">9</span>
<span class="sodiumSum">770</span>
<span class="chloesterolSum">0</span>
</li>
<li>
<input type="radio" name="meal" value="naked" > Naked, zero nutrients
<span class="caloriesSum">0</span>
<span class="fatSum">0</span>
<span class="satfatSum">0</span>
<span class="carbsSum">0</span>
<span class="proteinSum">0</span>
<span class="sodiumSum">0</span>
<span class="chloesterolSum">0</span>
</li>
</ul>
<h4>Select Your Protein</h4>
<ul class="options">
<li>
<input type="radio" name="protein" value="steak" > Steak
<span class="caloriesSum">230</span>
<span class="fatSum">9</span>
<span class="satfatSum">3</span>
<span class="carbsSum">3</span>
<span class="proteinSum">32</span>
<span class="sodiumSum">170</span>
<span class="chloesterolSum">90</span>
</li>
<li>
<input type="radio" name="protein" value="carnitas" > Carnitas
<span class="caloriesSum">210</span>
<span class="fatSum">9</span>
<span class="satfatSum">3</span>
<span class="carbsSum">2</span>
<span class="proteinSum">29</span>
<span class="sodiumSum">490</span>
<span class="chloesterolSum">90</span>
</li>
<li>
<input type="radio" name="protein" value="chicken" > Chicken
<span class="caloriesSum">190</span>
<span class="fatSum">2</span>
<span class="satfatSum">0</span>
<span class="carbsSum">4</span>
<span class="proteinSum">35</span>
<span class="sodiumSum">560</span>
<span class="chloesterolSum">90</span>
</li>
<li>
<input type="radio" name="protein" value="tofu"> Tofu
</li>
</ul>
<h4>The Add-ins</h4>
<ul class="options">
<li>
<input type="checkbox" name="the_addins" value="white_rice"> White Rice
<span class="fatSum">9</span>
<span class="satfatSum">3</span>
<span class="carbsSum">2</span>
<span class="proteinSum">29</span>
<span class="sodiumSum">490</span>
<span class="chloesterolSum">90</span>
</li>
<li>
<input type="checkbox" name="the_addins" value="brown_rice"> Brown Rice
</li>
<li>
<input type="checkbox" name="the_addins" value="black_beans"> Black Beans
</li>
<li>
<input type="checkbox" name="the_addins" value="pinto_beans"> Pinto Beans
</li>
</ul>
<h4>Salsas</h4>
<ul class="options">
<li>
<input type="checkbox" name="salsas" value="pico_de_gallo"> Pico De Gallo
</li>
<li>
<input type="checkbox" name="salsas" value="tomatillo_salsa"> Tomatillo Salsa
</li>
<li>
<input type="checkbox" name="salsas" value="roasted_corn_salsa"> Roasted Corn Salsa
</li>
<li>
<input type="checkbox" name="salsas" value="fire_roasted_red_salsa"> Fire Roasted Red Salsa
</li>
</ul>
<h4>Add-ins</h4>
<ul class="options">
<li>
<input type="checkbox" name="addins" value="lettuce"> Lettuce
</li>
<li>
<input type="checkbox" name="addins" value="shredded_cheese"> Shredded Cheese
</li>
<li>
<input type="checkbox" name="addins" value="crema"> Crema
</li>
<li>
<input type="checkbox" name="addins" value="chipotle_crema"> Chipotle Crema
</li>
<li>
<input type="checkbox" name="addins" value="guacamole"> Guacamole
</li>
</ul>
<!-- This is where the values should display -->
<div id="totals">
<h4>Totals</h4>
<ul>
<li>Calories: <span id="totalCalories"> </span></li>
<li>Fat: <span id="totalFat"> </span>g</li>
<li>Sat. Fat: <span id="totalSatFat"> </span>g</li>
<li>Carbs: <span id="totalCarbs"> </span>g</li>
<li>Protein: <span id="totalProtein"> </span>g</li>
<li>Sodium: <span id="totalSodium"> </span>mg</li>
<li>Cholesterol: <span id="totalChloresterol"> </span>mg</li>
</ul>
</div>
<!-- #totals -->
</form>
</body>
</html>
You seem to be missing a $.sum plugin that adds the values of a jQuery collection. I dropped one in place (first hit on a Google search) and your code works fine.
http://jsfiddle.net/QM9gP/
$.fn.sum = function() {
var sum = 0;
this.each(function() {
if ( $(this).is(':input') ) {
var val = $(this).val();
} else {
var val = $(this).text();
}
sum += parseFloat( ('0' + val).replace(/[^0-9-\.]/g, ''), 10 );
});
return sum;
};
$('.options').on('change', 'input', function() {
var $self = $(this);
var inputType = $self.attr('type');
if (inputType == 'radio') {
$self.parent('li').addClass('active').siblings().removeClass('active');
} else if (inputType == 'checkbox') {
$self.parent('li').toggleClass('active');
}
runUpdate();
});
function runUpdate() {
console.log('run update');
// get the sum of the elements
var calories = $(".caloriesSum", '.active').sum();
var fat = $(".fatSum", '.active').sum();
var satfat = $(".satfatSum", '.active').sum();
var carbs = $(".carbsSum", '.active').sum();
var protein = $(".proteinSum", '.active').sum();
var sodium = $(".sodiumSum", '.active').sum();
var chloresterol = $(".chloesterolSum", '.active').sum();
// update the total
$("#totalCalories").text(+calories.toString());
$("#totalFat").text(+fat.toString());
$("#totalSatFat").text(+satfat.toString());
$("#totalCarbs").text(+carbs.toString());
$("#totalProtein").text(+protein.toString());
$("#totalSodium").text(+sodium.toString());
$("#totalChloresterol").text(+chloresterol.toString());
}

Categories

Resources