I have the following html code:
I want to calculate the price associated with each checked box and display it in a text area after i click order (button). Pls help!
<div>
<form>
<fieldset > <legend>Resturant Menu:</legend>
<input type="checkbox" id = "menu" value="300">
<label> Chicken-------------------------- 300 AFN</label> <br>
<input type="checkbox" id = "menu" value="200">
<label> Chicken Baryani --------------- 200 AFN</label> <br>
<input type="checkbox" id = "menu" value="250">
<label> Chicken Kabab ----------------- 250 AFN</label> <br>
<input type="checkbox" id = "menu" value="100">
<label> Juice ----------------------------- 100 AFN</label> <br>
<input type="submit" id = "submit_btn" onclick = "calculate()">
</fieldset>
</form>
</div>
This is usually not how it works on StackOverflow, you have to try fixing it yourself. However, I'm bored so here is a solution with HTML + Javascript.
It is bad practice to declare multiple ids with the same name, use classes instead. I changed your code a little bit. You said you want to display the code in another field, so using a form for this is not necessary.
var menuItems = document.getElementsByClassName('menuItem');
var orderButton = document.getElementById('order_btn');
var totalArea = document.getElementById('total');
var afn = 0;
orderButton.addEventListener('click', function(e) {
e.preventDefault();
for (var i = 0; i < menuItems.length; i++) {
if (menuItems[i].checked) {
afn += +menuItems[i].value;
}
}
totalArea.innerHTML = "Total: " + afn + " AFN";
afn = 0;
});
<div>
<fieldset>
<legend>Resturant Menu:</legend>
<input type="checkbox" class="menuItem" value="300">
<label>Chicken-------------------------- 300 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="200">
<label>Chicken Baryani --------------- 200 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="250">
<label>Chicken Kabab ----------------- 250 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="100">
<label>Juice ----------------------------- 100 AFN</label>
<br>
<button id="order_btn">Order</button>
</fieldset>
<p id="total">Total: 0 AFN</p>
</div>
function calculate(){
var allMenuItem = $('#menuItem input[type=checkbox]');
var totalPrice = 0;
$.each(allMenuItem, function(key, element){
if($(this).is(":checked")){
totalPrice += parseFloat($(this).val());
}
});
alert("You order price is: "+ totalPrice + " Rs");
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form>
<fieldset > <legend>Resturant Menu:</legend>
<div id="menuItem">
<input type="checkbox" id = "menu" value="300">
<label> Chicken-------------------------- 300 AFN</label> <br>
<input type="checkbox" id = "menu" value="200">
<label> Chicken Baryani --------------- 200 AFN</label> <br>
<input type="checkbox" id = "menu" value="250">
<label> Chicken Kabab ----------------- 250 AFN</label> <br>
<input type="checkbox" id = "menu" value="100">
<label> Juice ----------------------------- 100 AFN</label> <br>
<input type="button" value="Order" id = "submit_btn" onclick = "calculate()">
</div>
</fieldset>
</form>
Related
I want user to choice one from each of the two radio buttons and this change the variable to display by button function.
How can I achieve this?
So far I have done the following -
function ok() {
if (document.getElementById("vanilla").checked = true;)
var flavor = "vanilla";
if (document.getElementById("chocolate").checked = true;)
var flavor = "chocolate";
if (document.getElementById("cone").checked = true;)
var vessel = "cone";
if (document.getElementById("bowl").checked = true;)
var vessel = "bowl";
if (document.getElementById("sprinkles").checked = true;)
var toppings = "sprinkles";
if (document.getElementById("peanuts").checked = true;)
var toppings = "peanuts";
document.getElementById("par").innerHTML = "I'd like two scoops of " + flavor + " ice cream in a " + vessel + " with " + toppings + "."
}
<h1>choice your Ice Cream</h1>
<div>
<h4>Please select a flavor:</h4>
<input type="radio" id="vanilla" name="flavor" value="vanilla">
<label for="vanilla">vanilla</label><br>
<input type="radio" id="chocolate" name="flavor" value="chocolate">
<label for="chocolate">chocolate</label>
<br>
<h4>Please select a vessel:</h4>
<input type="radio" id="cone" name="vessel" value="cone">
<label for="cone">cone</label><br>
<input type="radio" id="bowl" name="vessel" value="bowl">
<label for="bowl">bowl</label>
<br>
<h4>Please select a toppings:</h4>
<input type="radio" id="sprinkles" name="toppings" value="sprinkles">
<label for="sprinkles">sprinkles</label><br>
<input type="radio" id="peanuts" name="toppings" value="peanuts">
<label for="peanuts">peanuts</label>
<p id="par"></p>
<button onClick="ok()">ok</button>
</div>
Try this:
function ok() {
var flavor = document.querySelector("[name='flavor']:checked").value;
var vessel = document.querySelector("[name='vessel']:checked").value;
var toppings = document.querySelector("[name='toppings']:checked").value;
document.getElementById("par").innerHTML = "I'd like two scoops of " + flavor + " ice cream in a " + vessel + " with " + toppings + "."
}
<h1>choice your Ice Cream</h1>
<div>
<h4>Please select a flavor:</h4>
<input type="radio" id="vanilla" name="flavor" value="vanilla">
<label for="vanilla">vanilla</label><br>
<input type="radio" id="chocolate" name="flavor" value="chocolate">
<label for="chocolate">chocolate</label>
<br>
<h4>Please select a vessel:</h4>
<input type="radio" id="cone" name="vessel" value="cone">
<label for="cone">cone</label><br>
<input type="radio" id="bowl" name="vessel" value="bowl">
<label for="bowl">bowl</label>
<br>
<h4>Please select a toppings:</h4>
<input type="radio" id="sprinkles" name="toppings" value="sprinkles">
<label for="sprinkles">sprinkles</label><br>
<input type="radio" id="peanuts" name="toppings" value="peanuts">
<label for="peanuts">peanuts</label>
<p id="par"></p>
<button onClick="ok()">ok</button>
</div>
I need some guidance in how to add my selection list to my total. I am still new to javascript so i did what i could but for some reason, i cannot figure out how to add the selection list to my total. the textboxes with 0.00 are there for me to see if the radios, checkboxes and selection are adding up properly.
``
`
function customerInfo(cName){
var dinerName = document.getElementById(cName).value;
document.getElementById('cust_name').innerHTML = dinerName;
}
// format val to n number of decimal places
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0,pt) + "." + str.slice(pt);
}
function getRadioVal(form, name) {
var radios = form.elements[name];
var val;
for (var i=0, len=radios.length; i<len; i++) {
if ( radios[i].checked == true ) {
val = radios[i].value;
break;
}
}
return val;
}
function getToppingsTotal(e) {
var form = this.form;
var val = parseFloat( form.elements['tops_tot'].value );
if ( this.checked == true ) {
val += parseFloat(this.value);
} else {
val -= parseFloat(this.value);
}
form.elements['tops_tot'].value = formatDecimal(val);
updatePizzaTotal(form);
}
function getSizePrice(e) {
this.form.elements['sz_tot'].value = parseFloat( this.value );
updatePizzaTotal(this.form);
}
function getDeliveryPrice(e){
selectElement = document.querySelector('#pick_delivery');
output = selectElement.options[selectElement.selectedIndex].value;
console.log(output);
}
function updatePizzaTotal(form) {
var sz_tot = parseFloat( form.elements['sz_tot'].value );
var tops_tot = parseFloat( form.elements['tops_tot'].value );
form.elements['total'].value = formatDecimal( sz_tot + tops_tot );
}
// removes from global namespace
(function() {
var form = document.getElementById('pizzaForm');
var el = document.getElementById('pizza_toppings');
// input in toppings container element
var tops = el.getElementsByTagName('input');
for (var i=0, len=tops.length; i<len; i++) {
if ( tops[i].type === 'checkbox' ) {
tops[i].onclick = getToppingsTotal;
}
}
var sz = form.elements['size'];
for (var i=0, len=sz.length; i<len; i++) {
sz[i].onclick = getSizePrice;
}
// set sz_tot to value of selected
form.elements['sz_tot'].value = formatDecimal( parseFloat( getRadioVal(form, 'size') ) );
updatePizzaTotal(form);
})(); // end remove from global namespace and invoke
<form name="pizzaOrder" method="post" id="pizzaForm" enctype="text/plain">
<fieldset style="width: 60%;">
<legend>Create Your Pizza</legend>
<h3>Customer's Name:</h3>
<p>
<input type="text" name="client_name" id="client_name" value="First and Last Name" size="30" value="" />
<input type="button" onclick="customerInfo('client_name')" value="Enter"></button>
</p>
<h3>Pick Your Size:</h3>
<p>
<label><input type="radio" name="size" value="8" /> Small</label>
<label><input type="radio" name="size" value="10" /> Medium</label>
<label><input type="radio" name="size" value="12" /> Large</label>
<label><input type="radio" name="size" value="14" checked/> Extra Large</label>
<input type="text" name="sz_tot" value="0.00" />
</p>
<h3>Pick Your Toppings</h3>
<p id="pizza_toppings">
<label><input type="checkbox" name="Pineapple" value="1.50" /> Pineapple</label>
<label><input type="checkbox" name="Onions" value="1.50" /> Onions </label>
<label><input type="checkbox" name="Ham" value="1.50" /> Ham</label>
<label><input type="checkbox" name="Sausage" value="1.50" /> Sausage</label>
<label><input type="checkbox" name="Pepperoni" value="1.50" /> Pepperoni</label>
<input type="text" name="tops_tot" value="0.00" />
</p>
<h3>Delivery Or Pick Up</h3>
<p>
<select class="delivery" id="pick_delivery" size="2">
<option value="0">Pick Up: Free</option>
<option value="2">Delivery: $2</option>
</select>
<input type="button" onclick="getDeliveryPrice()" id="delivery_pick" value="enter" /></button>
</p>
<p>
<label>Total: $ <input type="text" name="total" class="num" value="0.00" readonly="readonly" /></label>
</p>
<p>
<input type="button" value="Confirm" />
<input type="button" value="Cancel">
</p>
</fieldset>
</form>
<div>
<h2>Your Order:</h2>
<p>
<h4>Your Name: <span id="cust_name"> </span></h4>
<h4>Your Pizza Size:</h4>
<h4>Toppings Selected:</h4>
</p>
</div>
</fieldset>
</form>```
On the bottom of the page the results should look similar to this:
Your Name: Pam Love
Pizza Size Selected: Extra Large
Toppings Selected: Bacon, Pineapple, Ham
Total: 20.50
When clicked on confirm order, the onclick button should redirect the page to a new tab that says:
Your order will be ready in 20 minutes.
or if cancelled then the user clicks the cancel button also redirected to a new tab:
Your order is cancelled.
You can just use some css selectors to accomplish most of this.
Here is how you can get your selected size:
document.querySelector('input[type="radio"][name="size"]:checked').value
And here is how you can get the list of toppings:
[...document.querySelectorAll('input[type="checkbox"][name="topping"]:checked')].map((t) => t.value).join(', ')
The remaining things should be pretty easy to find using querySelector or getElementById
I prefer to get checked checkboxes from a specific checkbox group, depending on which button I have clicked, I used $('input[name="' + groupName + '"]:checked'). This will ensure that the checked checkboxes from only the coffee or animals checkbox group are selected. But it's not working as I expected.
<body>
<div>
<input type="checkbox" value="Lion" name="animals" checked />Lion<br>
<input type="checkbox" value="Tiger" name="animals" />Tiger<br>
<input type="checkbox" value="Elephant" name="animals" />Elephant<br>
<input type="checkbox" value="Girafee" name="animals" />Girafee<br>
<input type="submit" id="__mainAnimals" />
<br><br><br><br><br><br>
<input type="checkbox" value="Coffe" name="drinks" checked />Coffe<br>
<input type="checkbox" value="Tea" name="drinks" />Tea<br>
<input type="checkbox" value="Milk" name="drinks" />Milk<br>
<input type="checkbox" value="Mocha" name="drinks" />Mocha<br>
<input type="submit" id="__mainDrinks" />
</div>
<div id="__DIVresult"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#__mainAnimals').click(function () {
getSelectedCheckBoxes('animals');
});
$('#__mainDrinks').click(function () {
getSelectedCheckBoxes('drinks');
});
var getSelectedCheckBoxes = function (groupName) {
var result = $('input[name="' + groupName + '"]:checked');
if (result.length > 0) {
var resultString = result.length + " checkboxe(s) checked<br/>";
result.each(function () {
resultString += $(this).val() + "<br/>";
});
$('__DIVresult').html(resultString);
}
else {
$('__DIVresult').html("No checkbox checked");
}
};
});
</script>
</body>
1st id selector is # so $('__DIVresult') should be $('#__DIVresult')
2nd An ID should start with a letter for compatibility
Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
REF: https://developer.mozilla.org/en/docs/Web/HTML/Global_attributes/id
3rd some small update, added two result div, one for animal one for drink:
<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>
Then target them dynamically with $('#DIVresult'+groupName).html(resultString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" value="Lion" name="animals" checked />Lion
<br>
<input type="checkbox" value="Tiger" name="animals" />Tiger
<br>
<input type="checkbox" value="Elephant" name="animals" />Elephant
<br>
<input type="checkbox" value="Girafee" name="animals" />Girafee
<br>
<input type="submit" id="mainAnimals" />
<br>
<br>
<br>
<br>
<br>
<br>
<input type="checkbox" value="Coffe" name="drinks" checked />Coffe
<br>
<input type="checkbox" value="Tea" name="drinks" />Tea
<br>
<input type="checkbox" value="Milk" name="drinks" />Milk
<br>
<input type="checkbox" value="Mocha" name="drinks" />Mocha
<br>
<input type="submit" id="mainDrinks" />
</div>
<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#mainAnimals').click(function() {
getSelectedCheckBoxes('animals');
});
$('#mainDrinks').click(function() {
getSelectedCheckBoxes('drinks');
});
var getSelectedCheckBoxes = function(groupName) {
var result = $('input[name="' + groupName + '"]:checked');
if (result.length > 0) {
var resultString = result.length + " checkboxe(s) checked<br/>";
result.each(function() {
resultString += $(this).val() + "<br/>";
});
$('#DIVresult'+groupName).html(resultString);
} else {
$('#DIVresult'+groupName).html("No checkbox checked");
}
};
});
</script>
In your drink and animal section you are not separating the two so when you use your click function it doesn't discriminate between the tow sections. Once you add each one to a class then the button will only call the checked items that are actually checked.
<html>
<form>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Lion" />Lion</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Tiger" />Tiger</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Elephant" />Elephant</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Girafee" />Girafee</br>
<input type="button" id="save_value" name="save_value" value="Save" /></br>
<textarea id="t"></textarea>
</form>
<script>
function updateTextArea() {
var allVals = [];
$('.ads_Checkbox:checked').each(function() {
allVals.push($(this).val());
});
$('#t').val(allVals);
}
$('#save_value').click(function(){
$('.ads_Checkbox:checked').each(function(){
updateTextArea();
});
});
Inside this code I have named each animal and placed them in a class so I could recall them from an array. I hoped this helped.
I have a small script that checks for selected boxes and ads them up.
Some boxes are worth two some are worth one.
I can get them to add up, but only if I select one of two pointers first or vice versa.
Html
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="one">Some blah blah text</label>
</div>
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="two">Text</label>
</div>
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="one">text</label>
</div>
The Javascript
$(".two").change(function() {
var classes = $("input[type='checkbox'].two:checked").map(function() {
return this.className;
}).get().length * 2;
document.getElementById("program_management2").innerHTML = " Score:" + " " + Math.floor(classes) ;
$(".one").change(function() {
var classes2 = $("input[type='checkbox'].one:checked").map(function() {
return this.className;
}).get().length;
document.getElementById("program_management").innerHTML = " Score:" + " " + Math.floor(classes2 + classes) ;
});
});
If you only want to add the value of each checked checkbox, you should use the value attribute.
Since the value is a string, you have to parse it to an integer to use it in an addition.
$("input[type='checkbox']").click(function(){
var result = 0;
$("input[type='checkbox']:checked").each(function(){
result += parseInt($(this).val());
});
$("#total").html(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1">This box value is 1<br>
<input type="checkbox" value="2">This box value is 2<br>
<input type="checkbox" value="5">This box value is 5<br>
<br>
<br>
The checked total is: <span id="total">0</span>
EDIT
I added a "checked class" count.
$("input[type='checkbox']").click(function(){
var result = 0;
var classOne = 0;
var classTwo = 0;
$("input[type='checkbox']:checked").each(function(){
result += parseInt($(this).val());
if( $(this).hasClass("one") ){
classOne++;
}
if( $(this).hasClass("two") ){
classTwo++;
}
$("#totalOne").html(classOne);
$("#totalTwo").html(classTwo);
});
$("#total").html(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="one">This box value is 1<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<input type="checkbox" value="1" class="one">This box value is 1<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<br>
<br>
The checked total value is: <span id="total">0</span><br>
Class "one" checked total : <span id="totalOne">0</span><br>
Class "two" checked total : <span id="totalTwo">0</span><br>
I have few checkboxes and I want to convert them into dropdown list. I tried something but don't know at the end what to do?
<form id="form-wysija-2" class="widget_wysija" action="#wysija" method="post">
<p class="wysija-checkbox-label">Select list(s):</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="1" name="wysija[user_list][list_id][]">
General Antiques
</label>
</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="3" name="wysija[user_list][list_id][]">
Antique & Collectible Tools
</label>
</p>
</form>
and i tried following jQuery to convert these checkboxes into dropdown list. but don't getting to how to done this successfully.
jQuery(document).ready(function($){
var extra, checkBoxesName,
checkBoxlabel,
checkBoxes = $('.wysija-checkbox-paragraph');
var checkBoxesLabel = $('.wysija-checkbox-label');
checkBoxesName = checkBoxes.find('input').prop('name');
checkBoxlabel = checkBoxes.find('label').text();
checkBoxesLabel.append('<select name="'+checkBoxesName+'">'+extra+'</select>');
$('.wysija-checkbox-paragraph').each(function(n){
var dataText = $(this).find('label').text();
$('select[name='+checkBoxesName+']').append('<option value="'+n+'">'+dataText+'</option>');
});
//checkBoxes.remove();
});
Try this:
var checkBoxes = $('.wysija-checkbox-paragraph'),
checkBoxesLabel = $('.wysija-checkbox-label'),
checkBoxesName = checkBoxes.find('input').prop('name')
$select = $('<select name="' + checkBoxesName + '"></select>').appendTo(checkBoxesLabel);
checkBoxes.each(function (n) {
var dataText = $(this).find('label').text();
var dataValue = $(this).find('input').val();
$select.append('<option value="' + dataValue + '">' + dataText + '</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form-wysija-2" class="widget_wysija" action="#wysija" method="post">
<p class="wysija-checkbox-label">Select list(s):</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="1" name="wysija[user_list][list_id][]" /> General Antiques
</label>
</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="3" name="wysija[user_list][list_id][]" /> Antique & Collectible Tools
</label>
</p>
</form>
Note, that since checkboxes allow to select multiple values, you might want to add multiple attribute to selectbox, in order to allow the same behavior.
jQuery(document).ready(function($){
var extra, checkBoxesName,
checkBoxlabel,
checkBoxes = $('.wysija-checkbox-paragraph');
var checkBoxesLabel = $('.wysija-checkbox-label');
checkBoxesName = checkBoxes.find('input').prop('name');
checkBoxlabel = checkBoxes.find('label').text();
checkBoxesLabel.append('<select name="'+checkBoxesName+'">'+extra+'</select>');
$('.wysija-checkbox-paragraph').each(function(n){
var dataText = $(this).find('label').text();
$('.wysija-checkbox-paragraph').append('<select name="'+checkBoxesName+']" > <option value="'+n+'">'+dataText+'</option></select>');
});
//checkBoxes.remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form-wysija-2" class="widget_wysija" action="#wysija" method="post">
<p class="wysija-checkbox-label">Select list(s):</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="1" name="wysija[user_list][list_id][]">
General Antiques
</label>
</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="3" name="wysija[user_list][list_id][]">
Antique & Collectible Tools
</label>
</p>
</form>