Adding values from checkbox and dropdown select option - javascript

I would like to add the values from checkboxes and a dropdown menu using JavaScript (no JQuery).
My first question is how best to do this... my code is bellow.
Second question is are there disadvantages to using anonymous functions to do this?
Thank you!
https://jsfiddle.net/Buleria28/4ysvgkz8/
HTML
<label class="checkbox" for="Checkbox1">
<input value="50" type="checkbox" class="sum" > box 1
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum" > box 2
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum" > box 3
</label>
<br/><br/>
<select id="select" name ="select">
<option class="sum"></option>
<option value="1" class="sum">option 1</option>
<option value="2" class="sum">option 2</option>
<option value="5" class="sum">option 3</option>
</select>
<br/><br/>
Total: $<span id="payment-total">0</span>
JavaScript
/*To get checkbox values*/
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var checkAdd = this.value * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + checkAdd;
}
}
/*To get select values*/
var dropdown= document.getElementById("select");
for(j=0; j<dropdown.options.length;j++){
dropdown[j].onchange = function() {
if (dropdown[i].options.checked){
var selectAdd = dropdown.options[dropdown.selectedIndex].value;
total.innerHTML = parseFloat(total.innerHTML) + selectAdd;
}
}
}

Some things I want to point out:
Use addEventListener to bing event handlers
You can use anonymous functions but it's clearer when you declare it and give it a meaningful name
Don't keep total sum in the HTML element. Keep it in the variable and then insert it into HTML.
I would do it like that:
var checkboxes = document.querySelectorAll('.sum')
var select = document.querySelector('#select')
var total = document.querySelector('#payment-total')
var checkboxesTotal = 0
var selectTotal = 0
checkboxes.forEach(function(input) {
input.addEventListener('change', onCheckboxSelect)
})
select.addEventListener('change', onSelectChange)
function onCheckboxSelect(e) {
var sign = e.target.checked ? 1 : -1
checkboxesTotal += sign * parseInt(e.target.value, 10)
renderTotal()
}
function onSelectChange(e) {
var value = parseInt(e.target.value, 10)
if (!isNaN(value)) {
selectTotal = value
renderTotal()
}
}
function renderTotal() {
total.innerHTML = checkboxesTotal + selectTotal
}
<label class="checkbox" for="Checkbox1">
<input value="50" type="checkbox" class="sum"> box 1
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum"> box 2
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum"> box 3
</label>
<br/>
<br/>
<select id="select" name="select">
<option class="sum"></option>
<option value="1" class="sum">option 1</option>
<option value="2" class="sum">option 2</option>
<option value="5" class="sum">option 3</option>
</select>
<br/>
<br/> Total: $<span id="payment-total">0</span>

Here is a correction for JS regarding select element, I added inline comments, please check them for clarification:
/*To get select values*/
var dropdown = document.getElementById("select");
dropdown.onchange = function() {
var value = parseInt(this.value); // gets the selected value from "select" and tries to convert it to int
if(!isNaN(value)) { // if conversion is OK, i.e. it was a number
total.innerHTML = parseFloat(total.innerHTML) + value; // this line is copied from your previous code
}
}

Related

JS: Make checkboxes disabled if select is default value?

I have a set of checkboxes from
<input type="checkbox" name="parts_hoses" id="parts-cb1" value="1">
through id="parts-cb6"
I have a select box of #send-product
<select name="send_product" id="send-product">
<option value="wall-mounted" selected>Wall-mounted (Default)</option>
<option value="freestanding">Freestanding</option>
<option value="third_party">Third Party</option>
</select>
that when it is on its default value, "wall-mounted", the checkboxes are enabled (as they are by default), but when I switch that to another option in the list... I'd like to disable the checkboxes.
Here is my JS so far (doesn't work):
function switchProduct() {
var checkBoxes = document.querySelectorAll('input[type="checkbox"][id^="parts-cb"]');
var selectBox = document.getElementById('send-product');
if (selectBox.value == 'wall-mounted') {
checkBoxes.disabled = false;
} else {
checkBoxes.disabled = true;
}
}
document.getElementById('send-product').addEventListener('change', switchProduct);
What am I doing wrong? Any help is appreciated!
Here's a fiddle: https://jsfiddle.net/cwkgsuq1/
You're missing to loop your checkboxes Array collection.
plain JS is not jQuery, therefore "checkBoxes.disabled = false;" will not work.
Instead:
for(var i=0; i<checkBoxes.length; i++) {
checkBoxes[i].disabled = false;
}
So your code simplified could look like:
function switchProduct() {
var checkBoxes = document.querySelectorAll('input[type="checkbox"][id^="parts-cb"]');
var selectBox = document.getElementById('send-product');
for(var i=0; i<checkBoxes.length; i++) {
checkBoxes[i].disabled = selectBox.value == 'wall-mounted';
}
}
document.getElementById('send-product').addEventListener('change', switchProduct);
switchProduct();
<select name="send_product" id="send-product">
<option value="wall-mounted" selected>Wall-mounted (Default)</option>
<option value="freestanding">Freestanding</option>
<option value="third_party">Third Party</option>
</select><br><br>
<input type="checkbox" id="parts-cb1" value="1">
<br>
<input type="checkbox" id="parts-cb2" value="1">
<br>
<input type="checkbox" id="parts-cb3" value="1">

Change the select option value based on input field

I really don't know how to do it. Is it possible to do this process?
I want to change the select option value based on the user input on the quant field
<input type="number" name="quant" id="quant" /> // for example I enter 2
<select name="shipment" disable>
<option value="100"> 100 per 1 item </option>
<option value="150"> 150 per 2 item </option> //this must be selected
</select>
My actual code in php
<select name="shipment" id="">
<?php
foreach($shipment as $num => $price)
{
if($num != NULL || $price !=NULL)
{
?>
<option value="<?php echo "{$price}"?>">
<?php echo "{$price}"." for "."{$num}"." item";?></option>
<?php
}
}
?>
</select>
<h4 style="padding:0px;margin:0px;float:left;margin-top:10px;" class="col-md-3" >Quantity: </h4>
<div class="col-md-9" style="padding-left:0px;"><input type="number" name="quant" onblur="multiply.call(this,this.form.elements.price.value,this.form.elements.quant.value)"
min="1" max="10" placeholder="2" style="height:2em;margin:3px;"></div>
I have to make a simple calculation this is the price of the item:
<h4 style="padding:0px;margin:0px;float:left;" class="col-md-12" >Sale Price: ₱<font color='red'><?php $price= number_format(intval($shop_item_orig_price-($shop_item_orig_price*($shop_item_sale/100)))); echo $price;?> </font> </h4>
I will multiply it based on the quantity
<input type="number" name="quant" onblur="multiply.call(this,this.form.elements.price.value,this.form.elements.quant.value);myFunction(this.value)"
min="1" max="10" placeholder="2" style="height:2em;margin:3px;">
And then add the shipping fee based on the selected value.
I am showing you the simple demo for your question below:
UPDATE
function myFunction(quantValue)
{
var shipmentOption = document.getElementById("shipmentSelect");
shipmentOption.selectedIndex = quantValue - 1;
}
<input type="number" name="quant" placeholder="2" onblur="myFunction(this.value)"/>
<select name="shipment" id="shipmentSelect">
<option value="100"> 100 per 1 item </option>
<option value="150"> 150 per 2 item </option> //this must be selected
</select>
Explanation: The demo is with very simple logic of selectedIndex. So assuming that your entries would be searialized options. So if 1 is the input than select first option, 2 is the input select the second option,.... and so on.
Second Update:
JSFiddle:Demo
Hope that it help you.
HTML
<input type="number" name="quant" id="quant" />
<select name="shipment" disable>
<option value=""></option>
<option value="100"> 100 per 1 item </option>
<option value="150"> 150 per 4 item </option>
<option value="150"> 150 per 5 item </option>
<option value="150"> 150 per 2 item </option>
<option value="150"> 150 per 3 item </option>
</select>
JavaScript
document.getElementById('quant').addEventListener("change", function(){
multiply(this.form.elements.price.value,this.form.elements.quant.value);
var value = parseInt(this.value, 10),
selectEle = document.getElementsByTagName('select')[0],
options = selectEle.options,
selectedNum = 0;
for(var i = 0; i < options.length; i++) {
//checking the exact string with spaces (" " + value + " ")
if(options[i].textContent.indexOf(" " + value + " ") > -1) {
selectedNum = i;
}
}
selectEle.selectedIndex = selectedNum ? selectedNum : 0;
}, false);
Using jQuery:
$(function() {
$('#quant').keyup(function() {
var text = $(this).val();
var select = $('select[name="shipment"]');
var option = select.find(':contains(' + text + ')');
if (option.length) {
select.val(option.attr('value'));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="quant" id="quant" />
<select name="shipment" disable>
<option value="100"> 100 per 1 item </option>
<option value="150"> 150 per 2 item </option>
</select>
Sorry, don't know vanilla js solution.
An alternative
Create one attribute data-quantity in <option> tag. Give 1,2,3... value to it. And, in <script>, use change() or keyup() function.
<select name="shipment" id='selectbox'>
<option value="100" data-quantity="1"> 100 per 1 item </option>
<option value="150" data-quantity="2"> 150 per 2 item </option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.quantity').change(function(){
var quant= $('.quantity').val();
$("#selectbox").find("option[data-quantity=" + quant + "]").attr('selected', 'selected').siblings().removeAttr('selected');
});
});
</script>

How to display selected checkboxes' values in select dropdown?

here's the jsfiddle : https://jsfiddle.net/a1gsgh11/9/
For some reason , the javascript not working in js fiddle. My concern is, when I select multiple checkboxes, the values displays correctly and immediately without having to submit any button.
How do I display these selected values inside the box that currently listed out all the programming languages?
How do I alter below script into what I want?
function moveAll(from, to) {
$('#'+from+' option').remove().appendTo('#'+to);
}
function moveSelected(from, to) {
$('#'+from+' option:selected').remove().appendTo('#'+to);
}
function selectAll() {
$("select option").attr("selected","selected");
}
I want to display the selected checkboxes values inside select dropdown below:
<form name="selection" method="post" onSubmit="return selectAll()">
<select multiple size="10" id="from">
<option value="html">Html</option>
<option value="css">Css</option>
<option value="google">Google</option>
<option value="javascript">Javascript</option>
<option value="jquery">Jquery</option>
<option value="regex">Regex</option>
<option value="php">Php</option>
<option value="mysql">Mysql</option>
<option value="xml">Xml</option>
<option value="json">Json</option>
</select>
<div class="controls">
>>
>
<
<< </div>
<select multiple id="to" size="10" name="topics[]"></select>
<form>
this line displays all the values selected in the checkboxes:
<output>0 are checked<p>No Values</p></output>
Any help appreciated.. Thanks in advance.
Please see the fiddle, it is working fine now: https://jsfiddle.net/a1gsgh11/16/
I change the way the events were called:
$(".moveAll1").click(function(){
$('#from option').remove().appendTo($('#to'));
});
$(".moveAll2").click(function(){
$('#to option').remove().appendTo($('#from'));
});
$(".moveSelected1").click(function(){
$('#from option:selected').remove().appendTo('#to');
});
$(".moveSelected2").click(function(){
$('#to option:selected').remove().appendTo('#to');
});
var checked, checkedValues = new Array();
$("input[type=checkbox]").change(function(e) {
var selectedtext = ($(this).next().text());
if($(this).is(':checked'))
{
$("#from").append('<option value="' + selectedtext + '">' + selectedtext +'</option>');
}else{
$('option[value*="' + selectedtext + '"]').remove();
}
});
Html :
<input type="checkbox" name="level" id="level" value="1"><label>Primary</label><br/>
<input type="checkbox" name="level" id="level" value="2"><label>Upper Secondary</label><br/>
<input type="checkbox" name="level" id="level" value="3"><label>University</label><br/>
</div>
<div class="small-12 medium-6 large-6 columns">
<input type="checkbox" name="level" id="level" value="4"><label>Lower Secondary</label><br/>
<input type="checkbox" name="level" id="level" value="5"><label>Pre University</label><br/>
<input type="checkbox" name="level" id="level" value="6"><label>Skills/Languages</label><br/>
<div class="controls">
<a class="moveAll1">>></a>
<a class="moveSelected1">></a>
<a class="moveSelected2"><</a>
<a class="moveAll2" href="#"><<</a>
</div>
Is this the behavior you wanted?
var ele = $(this);
var from = $('select#from');
if (ele.prop('checked')) {
var opt = $("<option></option>")
.attr("value", ele.val())
.attr('id', 'op' + ele.val())
.text(ele.val());
from.append(opt);
} else {
var opt = $('#op' + ele.val());
opt.remove();
}
fiddle

Check if an item is not selected from a dropdown [duplicate]

This question already has answers here:
JavaScript - a way check if an option of the <select> tag is selected
(3 answers)
Closed 8 years ago.
I have a dropdown list that is generating dynamically using PHP. Its rendered HTML is something similar to below markup -
<select size="8" id="email" name="email">
<option value="6" data-userId="uid6">kamala#gmail.com</option>
<option value="8" data-userId="uid8">tk#g.com</option>
<option value="3" data-userId="uid3">myexample.com</option>
<option value="7" data-userId="uid7">samadhi#gmail.com</option>
<option value="2" data-userId="uid2">facebook.com</option>
<option value="4" data-userId="uid4">lankainstitute.com</option>
</select>
Using this markup, just I want to check whether item is selected or not using JavaScript. If it is not selected an item, then I need to get an alert message.
I tried it something like this. But I can not get it to work.
JavaScript -
var email = document.getElementById("email");
var selectedValue = email.options[email.selectedIndex].value;
if (selectedValue == '') {
alert("Please select a email");
}
Hope somebody may help me out.
Thank you.
You should listen to the change event of the select element and then parse the value of the selected option as an integer (parseInt(email.options[email.selectedIndex].value, 10)):
Example Here
var email = document.getElementById("email");
email.addEventListener('change', function (e) {
var selectedValue = parseInt(email.options[email.selectedIndex].value, 10);
if (selectedValue === 7) {
alert("Please select a email");
}
});
var email = document.getElementById("email");
email.addEventListener('change', function (e) {
var selectedValue = parseInt(email.options[email.selectedIndex].value, 10);
if (selectedValue === 7) {
alert("Please select a email");
}
});
<select size="8" id="email" name="email">
<option value="6" data-userId="uid6">kamala#gmail.com</option>
<option value="8" data-userId="uid8">tk#g.com</option>
<option value="3" data-userId="uid3">myexample.com</option>
<option value="7" data-userId="uid7">samadhi#gmail.com</option>
<option value="2" data-userId="uid2">facebook.com</option>
<option value="4" data-userId="uid4">lankainstitute.com</option>
</select>
... since you're validating whether an option is selected, you would use something more along these lines:
Example Here
var email = document.getElementById("email"),
validationButton = document.getElementById('validationButton');
validationButton.addEventListener('click', function (e) {
var selectedValue = email.options[email.selectedIndex] ? email.options[email.selectedIndex].value : null;
if (!selectedValue) {
alert("Please select a email");
}
});
var email = document.getElementById("email"),
validationButton = document.getElementById('validationButton');
validationButton.addEventListener('click', function (e) {
var selectedValue = email.options[email.selectedIndex] ? email.options[email.selectedIndex].value : null;
if (!selectedValue) {
alert("Please select a email");
}
});
<select size="8" id="email" name="email">
<option value="6" data-userId="uid6">kamala#gmail.com</option>
<option value="8" data-userId="uid8">tk#g.com</option>
<option value="3" data-userId="uid3">myexample.com</option>
<option value="7" data-userId="uid7">samadhi#gmail.com</option>
<option value="2" data-userId="uid2">facebook.com</option>
<option value="4" data-userId="uid4">lankainstitute.com</option>
</select>
<button id="validationButton">Check if selected</button>

Calculate hidden fields with jquery

I have a form that i'm trying to calculate some monetary value based on 2 dropdowns then show the total amount only the total in a textbox called GrandTotal which is read only.
Page loads and gets pricing data from DB into hidden fields.
InitialPrice = 660 (Mandatory)
EQup1Price = 550
EQup2Price = 440
2 Drop downs (EQup1, EQup2) Values 1-5.
Buy greater than 1 and get one free for EQup1 and EQup2.
The calculation is whats doing my head in.
<p>InitialPrice -: <strong>$660.00</strong></p>
<form name="Edit" method="post" action="mypageprocess">
<p><label for="EQup1">How many Branches?</label><br /><select name="EQup1" onblur="calc(this.form)" id="EQup1"/>
<option value="0">Please select</option>
<option value="1" >One</option>
<option value="2" >Two</option>
<option value="3" >Three</option>
<option value="4" >Four</option>
<option value="5" >Five</option>
</select> x <strong>$550.00</strong>
</p>
<p><label for="EQup2">How many Satellits?</label><br /><select name="EQup2" onblur="calc(this.form)" id="EQup2"/>
<option value="0">Please select</option>
<option value="1" >One</option>
<option value="2" >Two</option>
<option value="3" >Three</option>
<option value="4" >Four</option>
<option value="5" >Five</option>
</select> x <strong>$440.00 </strong>
</p>
<input type="text" onfocus="this.blur();" name="GrandTotal" size="10" readonly="readonly"/>
<input type="hidden" name="InitialPrice" value="660" />
<input type="hidden" name="EQup1Price" value="550" />
<input type="hidden" name="EQup2Price" value="440" />
</form>
<script>
function calc(theForm) {
// console.log("calc(theForm)");
var myEquip1 = document.Edit.EQup1.value;
var myEquip2 = document.Edit.EQup2.value;
Var myFixedPrice = document.Edit.InitialPrice.value;
Var myEquip1Price = document.Edit.EQup1Price.value;
Var myEquip2Price = document.Edit.EQup2Price.value;
if (myEquip1 > 1)
{
var myEquip1Total = (myEquip1*myEquip1Price) - (myEquip1Price)
}
else
{
var myEquip1Total = (myEquip1*myEquip1Price) - (myEquip1Price)
}
if (myEquip2 > 1)
{
var myEquip2Total = (myEquip2*myEquip2Price) - (myEquip2Price)
}
else
{
var myEquip2Total = (myEquip2*myEquip2Price) - (myEquip2Price)
}
theForm.GrandTotal.value = (myEquip2Total + myEquip1Total + myFixedPrice)
}
</script>
to calculate hidden fields in jquery
$(":hidden").length
$("#GrandTotal").val(Number($("#EQup1").val()) + Number($("#EQup1").val()));

Categories

Resources