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());
}
Related
I'm working on a filtering script and I need some help.
My question is, how can I check what filters are selected (they remain checked on page reload/going back from a different page) and run the filtering script on page reload?
The page is: https://www.raw-partner.de/wer-wir-sind/team-2/
The user interaction is loading the page - clicking on 'Filter' - selecting the checkboxes/filters user desired - clicking on an entry which redirects to a different page - when going back the same filters must be applied. (note: the previously checked checkboxes remain checked once going back, so the only thing to do is to run the script again)
I can post the script as well.
Any idea on how I can achieve this? Thanks in advance!
HTML:
<ul class="filters box">
<li>
<input name="is-partner" type="checkbox" value="partner" id="partner" />
<label for="partner">Partner</label>
</li>
<li>
<input name="other-job" type="checkbox" value="berufstrager" id="berufstrager" />
<label for="berufstrager"> Berufsträger </label>
</li>
<li>
<input name="other-job" type="checkbox" value="mitarbeiter" id="mitarbeiter" />
<label for="mitarbeiter"> Mitarbeiter </label>
</li>
</ul>
<ul class="filters box">
<li style="font-weight: bold"> Standorte </li>
<li>
<input name="location" type="checkbox" value="munchen" id="munchen" />
<label for="munchen"> München </label>
</li>
<li>
<input name="location" type="checkbox" value="berlin" id="berlin" />
<label for="berlin">Berlin</label>
</li>
<li>
<input name="location" type="checkbox" value="bad-worishofen" id="bad-worishofen" />
<label for="bad-worishofen">Bad Wörishofen</label>
</li>
<li>
<input name="location" type="checkbox" value="gera" id="gera" />
<label for="gera">Gera</label>
</li>
</ul>
<ul class="filters box">
<li style="font-weight: bold"> Partner mit Team </li>
<li>
<input name="parner-team" type="checkbox" value="appelt-duile" id="appelt-duile" />
<label for="appelt-duile"> Appelt/Duile </label>
</li>
<li>
<input name="parner-team" type="checkbox" value="bley" id="bley" />
<label for="bley"> Bley </label>
</li>
<li>
<input name="parner-team" type="checkbox" value="dietrich-kogler" id="dietrich-kogler" />
<label for="dietrich-kogler"> Dietrich/Kögler </label>
</li>
<li>
<input name="parner-team" type="checkbox" value="barth" id="barth" />
<label for="barth"> Dr. Barth </label>
</li>
<li>
<input name="parner-team" type="checkbox" value="buck" id="buck" />
<label for="buck"> Dr. Buck </label>
</li>
<li>
<input name="parner-team" type="checkbox" value="drost" id="drost" />
<label for="drost"> Drost </label>
</li>
<li>
<input name="parner-team" type="checkbox" value="lux-kronig-harbauer" id="lux-kronig-harbauer" />
<label for="lux-kronig-harbauer"> Lux-Krönig/Harbauer </label>
</li>
<li>
<input name="parner-team" type="checkbox" value="metzler" id="metzler" />
<label for="metzler"> Metzler </label>
</li>
<li>
<input name="parner-team" type="checkbox" value="stegmann" id="stegmann" />
<label for="stegmann"> Stegmann </label>
</li>
</ul>
</div>
</div>
<div id="filtering">
<div class="entry" data-id="max-appelt" data-category="partner munchen berufstrager appelt-duile">
<a href="http://www.raw-partner.de/maximilian-appelt-4/" target="_blank"><p><img class="" src="/wp-content/uploads/2018/08/Appelt_P_0613_Zuschnitt.png" alt="null" /></p>
<h3 id="name"><b>Maximilian <br> Appelt</b></h3></a>
</div>
<div class="entry" data-category="partner munchen berufstrager barth">
<a href="http://www.raw-partner.de/dr-hans-guenther-barth/" target="_blank"><p><img class="" src="/wp-content/uploads/2018/08/Barth_P_0187_Zuschnitt.png" alt="null" /></p>
<h3 id="name"><b>Dr. Hans Günther Barth</b></h3></a>
</div>
<div class="entry" data-category="munchen mitarbeiter ">
<a href="http://www.raw-partner.de/katrin-bartl-3/" target="_blank"><p><img class="" src="/wp-content/uploads/2018/08/Bartl_0820_F_Zuschnitt.png" alt="null" /></p>
<h3 id="name"><b>Katrin <br> Bartl</b></h3></a>
</div>
<div class="entry" data-id="hans" data-category="bad-worishofen mitarbeiter stegmann">
<a href="http://www.raw-partner.de/alexander-baumgaertner-2/"><p><img class="" src="/wp-content/uploads/2018/08/Baumgärtner_0035_F2.png" alt="null" /></p>
<h3 id="name"><b>Alexander <br> Baumgärtner</b></h3></a>
</div>
<div class="entry" data-id="hans" data-category="bad-worishofen mitarbeiter">
<a href="http://www.raw-partner.de/margit-baur-3/"><p><img class="" src="/wp-content/uploads/2018/08/Baur_0533_F_Zuschnitt.png" alt="null" /></p>
<h3 id="name"><b>Margit <br> Baur</b></h3></a>
</div>
<div class="entry" data-id="hans" data-category="bad-worishofen mitarbeiter">
<a href="http://www.raw-partner.de/peter-harbauer-3-7/"><p><img class="" src="/wp-content/uploads/2018/08/Bernhardt_0137_Zuschnitt.png" alt="null" /></p>
<h3 id="name"><b>Yvonne <br> Bernhardt</b></h3></a>
</div>
jQuery:
(function($){
var $filterCheckboxes = $('input[type="checkbox"]');
$filterCheckboxes.on('change', function() {
var selectedFilters = {};
$filterCheckboxes.filter(':checked').each(function() {
if (!selectedFilters.hasOwnProperty(this.name)) {
selectedFilters[this.name] = [];
}
selectedFilters[this.name].push(this.value);
});
var $filteredResults = $('.entry');
$.each(selectedFilters, function(name, filterValues) {
$filteredResults = $filteredResults.filter(function() {
var matched = false,
currentFilterValues = $(this).data('category').split(' ');
$.each(currentFilterValues, function(_, currentFilterValue) {
if ($.inArray(currentFilterValue, filterValues) != -1) {
matched = true;
return false;
}
});
return matched;
});
});
$('.entry').hide().filter($filteredResults).show();
});
$(window).trigger('resize')
})(jQuery);
JSFiddle: https://jsfiddle.net/u39kmoxz/2/
Note: I have a basic understanding of jQuery, not advanced enough to use cookies, I was thinking that since the checkboxes are remaining checked when going back, the only thing that should be done is re-running the script but I can't understand how since the script is being applied on change.
Welcome!
Conceptually, you need to make the function callable from 2 events: change checkbox + page load. Therefore you need to name the function so that you can call it from these 2 events.
(function($){
var $filterCheckboxes = $('input[type="checkbox"]');
var doFiltering = function() {
var selectedFilters = {};
$filterCheckboxes.filter(':checked').each(function() {
if (!selectedFilters.hasOwnProperty(this.name)) {
selectedFilters[this.name] = [];
}
selectedFilters[this.name].push(this.value);
});
var $filteredResults = $('.entry');
$.each(selectedFilters, function(name, filterValues) {
$filteredResults = $filteredResults.filter(function() {
var matched = false,
currentFilterValues = $(this).data('category').split(' ');
$.each(currentFilterValues, function(_, currentFilterValue) {
if ($.inArray(currentFilterValue, filterValues) != -1) {
matched = true;
return false;
}
});
return matched;
});
});
$('.entry').hide().filter($filteredResults).show();
} // end of doFiltering function
$filterCheckboxes.on('change',doFiltering()); // call it with the on change
doFiltering() // call it when your parent function executes at page load (only executes once)
$(window).trigger('resize')
})(jQuery);
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);
});
});
This is my HTML:
<div id="RouterTemplates">
<div data-router-id="4" data-router-name="DF_DCM_ROUTER_1" class="jarviswidget jarviswidget-color-greenDark router-template" data-widget-colorbutton="false" data-widget-custombutton="false" >
<header>
<span class="widget-icon">
<i class="fa fa-table"></i>
</span>
<h2 >Router: AE Title: DF_DCM_ROUTER_1, Description: </h2>
<div class="widget-toolbar" id="routeronoffswitchtoobar" router_id="4">
<span class="onoffswitch">
<input type="checkbox" name="routeronoffswitch" class="onoffswitch-checkbox routerservicestatusswitch" id="routeronoffswitch" router_id="4" checked="checked">
<label class="onoffswitch-label" for="routeronoffswitch">
<span class="onoffswitch-inner" data-swchon-text="ON" data-swchoff-text="OFF"></span>
<span class="onoffswitch-switch"></span>
</label>
</span>
</div>
</header>
</div>
<div data-router-id="5" data-router-name="DISABLEDROUTER" class="jarviswidget jarviswidget-color-red router-template" data-widget-colorbutton="false" data-widget-custombutton="false" >
<header>
<span class="widget-icon">
<i class="fa fa-table"></i>
</span>
<h2 >Router: AE Title: DISABLEDROUTER, Description: Not in use</h2>
<div class="widget-toolbar" id="routeronoffswitchtoobar" router_id="5">
<span class="onoffswitch">
<input type="checkbox" name="routeronoffswitch" class="onoffswitch-checkbox routerservicestatusswitch" id="routeronoffswitch" router_id="5" >
<label class="onoffswitch-label" for="routeronoffswitch">
<span class="onoffswitch-inner" data-swchon-text="ON" data-swchoff-text="OFF"></span>
<span class="onoffswitch-switch"></span>
</label>
</span>
</div>
</header>
</div>
</div>
I'm try to get 2 things, the router_id for the section clicked and the value for the checkbox I clicked on. This is what I've tried thus far:
$('.routerservicestatusswitch').on('click', function (e)
{
var id = $(this).parent('router-template').data('router-id');
var id2 = $(this).siblings('.router-template').data('router-id');
var id3 = $(this).closest('.router-template').data('router-id');
var id4 = $(this).closest('.widget-toolbar').find('.onoffswitch-checkbox').data('router_id');
var id5 = $(this).find(':checkbox').attr('router_id');
var id6 = $(this).find(':checkbox').val();
if ($('#routeronoffswitch').is(':checked') == true)
{
SetRouter(true);
}
else
{
SetRouter(false);
}
});
I've tried different event handlers and they all return the router_id of the first section and never the id for the one I click. Can someone tell me how to get the correct data?
You have duplicated IDs: this is not possible. So you must change them to class or add a suffix in order to make them unique.
Second point: you have:
<div data-router-id="
a "data-router-id" and two: "router_id="" attribute.
You may access them using jQuery#closest and jQuery#data or jQuery#attr. For the data attributes you can use data but for the others you need to use attr:
Moreover, try to use the change event for checkboxes instead of click.
The snippet:
function SetRouter(arg1) {
console.log('SetRouter: ' + arg1)
}
$('.routerservicestatusswitch').on('change', function (e) {
var id1 = $(this).closest('.router-template').data('router-id');
var id2 = $(this).closest('.widget-toolbar').attr('router_id');
var id3 = $(this).attr('router_id');
var id4 = $(this).val();
console.log('id1: ' + id1 + ' id2: ' + id2 + ' id3: ' + id3);
if ($(this).is(':checked')) {
SetRouter(true);
} else {
SetRouter(false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="RouterTemplates">
<div data-router-id="4" data-router-name="DF_DCM_ROUTER_1" class="jarviswidget jarviswidget-color-greenDark router-template"
data-widget-colorbutton="false" data-widget-custombutton="false">
<header>
<span class="widget-icon">
<i class="fa fa-table"></i>
</span>
<h2 >Router: AE Title: DF_DCM_ROUTER_1, Description: </h2>
<div class="widget-toolbar" id="routeronoffswitchtoobar1" router_id="4">
<span class="onoffswitch">
<input type="checkbox" id="routeronoffswitch1" class="onoffswitch-checkbox routerservicestatusswitch"
router_id="4" checked="checked">
<label class="onoffswitch-label" for="routeronoffswitch1">
<span class="onoffswitch-inner" data-swchon-text="ON" data-swchoff-text="OFF"></span>
<span class="onoffswitch-switch"></span>
</label>
</span>
</div>
</header>
</div>
<div data-router-id="5" data-router-name="DISABLEDROUTER" class="jarviswidget jarviswidget-color-red router-template" data-widget-colorbutton="false" data-widget-custombutton="false" >
<header>
<span class="widget-icon">
<i class="fa fa-table"></i>
</span>
<h2 >Router: AE Title: DISABLEDROUTER, Description: Not in use</h2>
<div class="widget-toolbar" class="routeronoffswitchtoobar" router_id="5">
<span class="onoffswitch">
<input type="checkbox" id="routeronoffswitch" class="onoffswitch-checkbox routerservicestatusswitch"
router_id="5" >
<label class="onoffswitch-label" for="routeronoffswitch">
<span class="onoffswitch-inner" data-swchon-text="ON" data-swchoff-text="OFF"></span>
<span class="onoffswitch-switch"></span>
</label>
</span>
</div>
</header>
</div>
</div>
Hello Friends I have span with class .amount how can i get price from this span i have tried but i am not able to point out the exact location
Html
<li class="radio">
<input class="tmcp-field nav nav-pills fabric-layer-pattern test tm-product-image tm-epo-field tmcp-radio use_images" data-image="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png" type="radio">
<label for="tmcp_choice_14_2_39">
<img class="tmlazy radio_image" alt="Elegant" src="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png">
<span class="tc-label radio_image_label">Elegant</span>
</label>
<span class="price tc-price hidden">
<span class="amount">500</span>
</span>
</li>
Javascript
$('.fabric-layer-pattern').click(function() {
var spanEl1 = $(this).parent('li.radio').find('span.amount');
var priceee = spanEl1.text(); //Get text
console.log(price);
// this alert is coming two times empty after that price will come
alert(priceee);
});
Updated Html Code
<ul>
<li class="radio">
<input class="tmcp-field nav nav-pills fabric-layer-pattern test tm-product-image tm-epo-field tmcp-radio use_images" data-image="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png" data-imagep="" data-imagel="" tabindex="37" type="radio">
<label for="tmcp_choice_14_0_37"><img class="tmlazy radio_image" alt="Elegant" src="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png">
<span class="tc-label radio_image_label">Elegant</span></label>
<span class="price tc-price hidden"><span class="amount">500</span> </span>
</li>
<li class="radio">
<input class="tmcp-field nav nav-pills fabric-layer-pattern test tm-product-image tm-epo-field tmcp-radio use_images" type="radio">
<label for="tmcp_choice_14_1_38"><img class="tmlazy radio_image" alt="Elegant" src="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png">
<span class="tc-label radio_image_label">Elegant</span></label>
<span class="price tc-price hidden"><span class="amount">500</span> </span>
</li>
<li class="radio">
<input class="tmcp-field nav nav-pills fabric-layer-pattern test tm-product-image tm-epo-field tmcp-radio use_images" type="radio">
<label for="tmcp_choice_14_2_39"><img class="tmlazy radio_image" alt="Elegant" src="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png">
<span class="tc-label radio_image_label">Elegant</span></label>
<span class="price tc-price hidden"><span class="amount">500</span> </span>
</li>
</ul>
please suggest something...
Use parent() and find() to have specific element from multiple elements.
var spanEl = $(this).parent('li').find('span.amount');
var price = spanEl.text(); //Get text
console.log(price);
/*$('.fabric-layer-pattern').click(function() {
var spanEl = $(this).parent('li').find('span.amount');
var price = spanEl.text(); //Get text
console.log(price);
});*/
$('.fabric-layer-pattern').click(function() {
var spanEl1 = $(this).parent('li.radio').find('span.amount');
var priceee = spanEl1.text(); //Get text
console.log(priceee);
// this alert is coming two times empty after that price will come
alert(priceee);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul>
<li class="radio">
<input class="tmcp-field nav nav-pills fabric-layer-pattern test tm-product-image tm-epo-field tmcp-radio use_images" data-image="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png" data-imagep="" data-imagel="" tabindex="37" type="radio">
<label for="tmcp_choice_14_0_37"><img class="tmlazy radio_image" alt="Elegant" src="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png">
<span class="tc-label radio_image_label">Elegant</span></label>
<span class="price tc-price hidden"><span class="amount">500</span> </span>
</li>
<li class="radio">
<input class="tmcp-field nav nav-pills fabric-layer-pattern test tm-product-image tm-epo-field tmcp-radio use_images" type="radio">
<label for="tmcp_choice_14_1_38"><img class="tmlazy radio_image" alt="Elegant" src="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png">
<span class="tc-label radio_image_label">Elegant</span></label>
<span class="price tc-price hidden"><span class="amount">600</span> </span>
</li>
<li class="radio">
<input class="tmcp-field nav nav-pills fabric-layer-pattern test tm-product-image tm-epo-field tmcp-radio use_images" type="radio">
<label for="tmcp_choice_14_2_39"><img class="tmlazy radio_image" alt="Elegant" src="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png">
<span class="tc-label radio_image_label">Elegant</span></label>
<span class="price tc-price hidden"><span class="amount">700</span> </span>
</li>
</ul>
Try using siblings():
$('.fabric-layer-pattern').click(function() {
var spanEl = $(this).siblings().filter("span.amount");
var price = spanEl.text(); //Get text
});
$(this) inside the event scope is the radio input itself and span.amount is not inside it.
Demo
UPDATE
I have tried but in third alert i am getting price before that empty alert is coming
This can have different meanings. With only this comment I may figure out the price value is changed outside and you are interested in that event.
If it is so, you may refer to MutationObserver. Moreover, instead of click event you may consider to use the change event.
According to this considerations I updated the snippet.
You may use closest:
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree
The snippet:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes.length > 0) {
$('.fabric-layer-pattern').trigger('click');
}
});
});
observer.observe($('li.radio span.amount').get(0), { attributes: true, childList: true });
// later, you can stop observing
// observer.disconnect();
$('#myBtn').on('click', function(e) {
$('li.radio span.amount').text(Date.now());
});
$('.fabric-layer-pattern').on('click', function() {
var spanEl = $(this).closest('li.radio').find('span.amount');
var price = spanEl.text(); //Get text
console.log('span.amount is: ' + price);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="myBtn">Change price</button>
<ul>
<li class="radio">
<input class="tmcp-field nav nav-pills fabric-layer-pattern test tm-product-image tm-epo-field tmcp-radio use_images" data-image="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png" data-imagep="" data-imagel="" tabindex="37" type="radio">
<label for="tmcp_choice_14_0_37"><img class="tmlazy radio_image" alt="Elegant" src="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png">
<span class="tc-label radio_image_label">Elegant</span></label>
<span class="price tc-price hidden"><span class="amount">500</span> </span>
</li>
<li class="radio">
<input class="tmcp-field nav nav-pills fabric-layer-pattern test tm-product-image tm-epo-field tmcp-radio use_images" type="radio">
<label for="tmcp_choice_14_1_38"><img class="tmlazy radio_image" alt="Elegant" src="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png">
<span class="tc-label radio_image_label">Elegant</span></label>
<span class="price tc-price hidden"><span class="amount">500</span> </span>
</li>
<li class="radio">
<input class="tmcp-field nav nav-pills fabric-layer-pattern test tm-product-image tm-epo-field tmcp-radio use_images" type="radio">
<label for="tmcp_choice_14_2_39"><img class="tmlazy radio_image" alt="Elegant" src="http://localhost/mbox_server/wp-content/uploads/2016/09/pattern.png">
<span class="tc-label radio_image_label">Elegant</span></label>
<span class="price tc-price hidden"><span class="amount">500</span> </span>
</li>
</ul>
I guess this will do:
// Just to be specific
$(".fabric-layer-pattern + span.price > span.amount").text();
Try this code
$('.fabric-layer-pattern').click(function() {
var price = $('span.amount').text();
});
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 () {
});
});