javascript to update price of 4 dropdown & 2 check box button. - javascript

The above code is not working the way I want. The user should be able to select one option from each drop down menu & as soon as he selects a option price should be updated (at this point an alert box will do). User should be able to re-select any drop down menu if he/she wants and proper calculations needs to be done accordingly.
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="file.css">
<script type="text/javascript">
function dropdown() {
var drp = document.getElementById("numberlist");
var optn = document.createElement("OPTION");
optn.text="3";
optn.value="3";
drp.add(optn);
}
function Add() {
var e = document.getElementById('numberlist');
var txt = e.options[e.selectedIndex].text;
var txt_int = parseInt(txt);
var final_txt = show(txt_int);
//return final_txt;
//alert(txt_int);
}
function show(price) {
if(document.my_form.but1.checked == true) {
//alert("Box1 is checked");
price += 10;
}
else if(document.my_form.but2.checked == true) {
//alert("Box 2 is checked");
price += 15;
}
//return price;
alert(price);
}
</script>
</head>
<body onload="dropdown();">
<form name="my_form">
<select id="numberlist" onchange="Add()">
<option>Select</option>
<option>12</option>
<option>24</option>
<option>36</option>
</select>
<select id="numberlist" onchange="Add()">
<option>Select</option>
<option>12</option>
<option>24</option>
<option>36</option>
</select>
<select id="numberlist" onchange="Add()">
<option>Select</option>
<option>12</option>
<option>24</option>
<option>36</option>
</select>
<select id="numberlist" onchange="Add()">
<option>Select</option>
<option>12</option>
<option>24</option>
<option>36</option>
</select>
<br /> <p>
<input type="checkbox" name=but1 onchange="show()"> Gift Wrap $10 <br />
<input type="checkbox" name=but2 onchange="show()"> Express Shipping $15<br /> <p>
</form>
</body>
</html>

There are a couple of issues I see right of the bat.
Your select elements all have the same id attribute. This is a definite no-no. The use of document.getElementById() will only return one element.
If you want to get a handle on all of the select fields in your Add() and dropdown() functions, you should use the name attribute instead of the id attribute and query for these elements with document.getElementsByName(nameValue). This will return an array of all of your select elements which you would want to iterate over with a for loop.
The other issue is with your show() function. You have the parameter "price" defined in the function, buy you are not calling the function with a "price" argument. You can define a global price variable that will be accessible by all the functions with the window.
//Define a global price variable that will be visible to every function
var price;
//Add extra option to 'numberlist' select elements
function initDropdownOptions() {
//Grab all select elements by their name attribute
var selectElements = document.getElementsByName("numberlist");
//Initialize/Define for loop conditions variables
var numberOfDropdowns = selectElements.length;
var i;
//Define a reusable temp option variable to be reused
var optn;
//Iterate over select elements
for( i = 0; i < numberOfDropdowns; i++ ){
//Create a new option element and save it to the optn variable
optn = document.createElement("OPTION");
//Set the text of the option
optn.text="3";
//Set the value of the option
optn.value="3";
//Add the option to the ith select element
selectElements[i].add( optn );
}
}
function calculatePrice() {
//Grab all select elements by their name attribute
var selectElements = document.getElementsByName("numberlist");
//Initilize/Define for loop conditions variables
var i;
var numberOfDropdowns = selectElements.length;
//Define a temp holder for the select values
var tmpSelectValue;
//Initialize the global price variable to 0
price = 0;
for( i = 0; i < numberOfDropdowns; i++ ){
//Extract the value from the select element
tmpSelectValue = selectElements[i].options[ selectElements[i].selectedIndex ].value
//Parse the tmpSelectValue into a number and add it to the global price
price += parseFloat( tmpSelectValue );
}
//Add additional Charges if they are applicable
var giftWrapChecked = (document.my_form.but1.checked == true);
var expressShippingChecked = (document.my_form.but2.checked == true);
if( giftWrapChecked ) {
//Add aditional 10$
price += 10;
}
if( expressShippingChecked ) {
//Add additional 15$
price += 15;
}
//Output the price to the currentPrice div
document.getElementById("currentPrice").innerHTML = price;
}
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="file.css">
</head>
<body onload="initDropdownOptions();">
<form name="my_form">
<select name="numberlist" onchange="calculatePrice()">
<option value='0'>Select</option>
<option value='12'>12</option>
<option value='24'>24</option>
<option value='36'>36</option>
</select>
<select name="numberlist" onchange="calculatePrice()">
<option value='0'>Select</option>
<option value='12'>12</option>
<option value='24'>24</option>
<option value='36'>36</option>
</select>
<select name="numberlist" onchange="calculatePrice()">
<option value='0'>Select</option>
<option value='12'>12</option>
<option value='24'>24</option>
<option value='36'>36</option>
</select>
<select name="numberlist" onchange="calculatePrice()">
<option value='0'>Select</option>
<option value='12'>12</option>
<option value='24'>24</option>
<option value='36'>36</option>
</select>
<br />
<p>
<input type="checkbox" name=but1 onchange="calculatePrice()"> Gift Wrap $10 <br />
<input type="checkbox" name=but2 onchange="calculatePrice()"> Express Shipping $15<br />
<p>
<div id='currentPrice'></div>
</form>
</body>
</html>

This can be easily done using jQuery:
Try it:
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="file.css" />
</head>
<body>
<form name="my_form">
<select id="numberlist1" class="dropdown">
<option value="0">Select</option>
<option value="12">12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
<select id="numberlist2" class="dropdown">
<option value="0">Select</option>
<option value="12">12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
<select id="numberlist3" class="dropdown">
<option value="0">Select</option>
<option value="12">12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
<select id="numberlist4" class="dropdown">
<option value="0">Select</option>
<option value="12">12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
<br />
<p>
<input type="checkbox" name="but1" value="10" />
Gift Wrap $10 <br />
<input type="checkbox" name="but2" value="15" />
Express Shipping $15<br />
<p>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$('input:checkbox, select.dropdown').change(function(){
var price = 0;
$('input:checkbox, select.dropdown').each(function(){
// Your Show function
if($(this).is('input:checkbox') )
{
if($(this).is(':checked'))
price += parseInt($(this).val());
}
else
price += parseInt($(this).val());
});
alert(price);
});
</script>
</body>
</html>

Related

Make 2 <select> statements work and dont crash the script

Im putting multiples select in my code that are hidden and got a principal select that makes visible the other selec depending in the value selected, but when you choose a value in the second select it changes the second visible select to another, how can I prevent that to happen
Its a catalog in a static html that interacts with a SQL Server via php, so I need the select to compare it with the ID´s and make inserts and updates
This is the script:
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
$(this).find("option:selected").each(function(){
var optionValue = $(this).attr("value");
if(optionValue){
$(".box").not("." + optionValue).hide();
$("." + optionValue).show();
} else{
$(".box").hide();
}
});
}).change();
});
function myFuction(){
//Getting Value
//var selValue = document.getElementById("singleSelectDD").value;
var selObj = document.getElementById("MENU");
var selValue = selObj.options[selObj.selectedIndex].value;
//Setting Value
document.getElementById("valorsel").value = selValue;
}
</script>
And this are the examples:
<select name="MENU" id="MENU" onchange="myFuction()">
<option value="" selected></option>
<option value="1">Area</option>
<option value="2">Bancos</option>
<option value="3">CFDI</option>
<option value="4">Departamentos</option>
<option value="5">Empresa</option>
<option value="6">Giro Comercial</option>
<option value="7">Negocio</option>
</select><br><br>
<p>Texto Global</p>
<input type="text" name="GLOBAL" id="GLOBAL" value="" placeholder="Texto global">
</div>
<div class="1 box">
<p>Seleccione el Area deseada</p>
<input type="text" name="Txt_Area" id="Txt_Area" value="" placeholder="AREA">
<select name="AREA" id="AREA" placeholder="Seleccione Area deseada>
<option value="" selected></option>
<option value="1">AREA 1</option>
<option value="2">AREA 2</option>
<option value="3">AREA 3</option>
</select>
I want to be able of having both select on screen to insert or update the information
Instead of having $("select").change(function(){, it's better that you have $("#MENU").change(function() { because otherwise it will detect all the select menus that are changing instead of just the first one like you want.
$(document).ready(function() {
$("#MENU").change(function() {
$(this).find("option:selected").each(function() {
var optionValue = $(this).attr("value");
if (optionValue) {
$(".box").not("." + optionValue).hide();
$("." + optionValue).show();
} else {
$(".box").hide();
}
});
}).change();
});
function myFuction() {
var selObj = document.getElementById("MENU");
var selValue = selObj.options[selObj.selectedIndex].value;
//Setting Value
//document.getElementById("valorsel").value = selValue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select name="MENU" id="MENU" onchange="myFuction()">
<option value="" selected></option>
<option value="1">Area</option>
<option value="2">Bancos</option>
<option value="3">CFDI</option>
<option value="4">Departamentos</option>
<option value="5">Empresa</option>
<option value="6">Giro Comercial</option>
<option value="7">Negocio</option>
</select><br><br>
<p>Texto Global</p>
<input type="text" name="GLOBAL" id="GLOBAL" value="" placeholder="Texto global">
</div>
<div class="1 box">
<p>Seleccione el Area deseada</p>
<input type="text" name="Txt_Area" id="Txt_Area" value="" placeholder="AREA">
<select name="AREA" id="AREA" placeholder="Seleccione Area deseada">
<option value=" " selected></option>
<option value="1 ">AREA 1</option>
<option value="2 ">AREA 2</option>
<option value="3 ">AREA 3</option>
</select>

How to change select's option based on a selected option's value?

I have select tag below:
<select name="selID" id="selID" data-mini="true"">
<option value="1" selected="selected">Tithes</option>
<option value="2">Offering</option>
<option value="3">Designated</option>
<option class="selOptAddMore" value="0">Add More...</option>
</select>
I want to change value when one of the options is selected except for "Add More..."
Sorry I'm a newbie. Thanks in advance.
You can try this:
The HTML:
<body>
Result: <p id="result"></p>
<select name="selID" id="selID" data-mini="true" onchange="test()">
<option value="1" selected="selected">Tithes</option>
<option value="2">Offering</option>
<option value="3">Designated</option>
<option class="selOptAddMore" value="0">Add More...</option>
</select>
<script src="test.js"></script>
</body>
test.js:
function test() {
let listVal = document.getElementById("selID").value;
if (listVal != "0") {
document.getElementById("result").innerHTML = listVal;
}
else {
listVal = 1; // this is value for "Tithes"
document.getElementById("selID").value = listVal;
document.getElementById("result").innerHTML = listVal;
}
}

Showing select options on different select options

I want when someone selects a country out of my list the province in that country show up in the second select bar is this possible within html? And if not how do I do it with javascript.
<!DOCTYPE html>
<html>
<head>
<title>Gegevens</title>
</head>
<body>
<center>
<h1>Gegevens</h1>
</center>
Land:
<select id="countries">
<option value="Holland">Holland</option>
<option value="Denmark">Denmark</option>
<option value="England">England</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
</select><br>
Provincie:
<select> OPTIONS FOR HOLLAND
<option value="Gelderland">Gelderland</option>
<option value="Utrecht">Utrecht</option>
</select>
<select> OPTIONS FOR ENGLAND ETC...
<option value="Schotland">Schotland</option>
<option value="Wales">Wales</option>
</select>
<footer>Ga terug</footer>
</body>
</html>
You'll probably have to do this using JavaScript. I've edited your HTML a bit to make the selection process easier. There might be a way with HTML form elements, but try this:
var countrySelect = document.getElementById('countries'); //the main select
var countryClass = document.getElementsByClassName('country'); //the other selects
countrySelect.onchange = function(){
var selected = this.children[this.selectedIndex].value; //this is the value of the country select;
for(var i = 0; i < countryClass.length; i++)
countryClass[i].style.display = countryClass[i].id === selected ? 'block' : 'none';
}
<body>
<center>
<h1>Gegevens</h1>
</center>
Land:
<select id="countries">
<option disabled selected>Select Country</option>
<option value="Holland">Holland</option>
<option value="Denmark">Denmark</option>
<option value="England">England</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
</select><br>
Provincie:
<select class="country" id="Holland" style="display:none;">
<option disabled selected>Select Location</option>
<option value="Gelderland">Gelderland</option>
<option value="Utrecht">Utrecht</option>
</select>
<select class="country" id="England" style="display:none;">
<option disabled selected>Select Location</option>
<option value="Schotland">Schotland</option>
<option value="Wales">Wales</option>
</select>
</body>
I am not sure about the html way but the jquery way is pretty easy.
Handle option selected of countries. Based on the country selected hide/show provinces:
$(document).ready(function(){
$('#countries').on('change',function(){
var selectedCountry = $(this).find('option:selected').text();
switch (selectedCountry){
case 'Holland':
// hide show provice
break;
//etc
}
});
});
You need to use JS and play with elements display property.
After user selects a country hide province select (code snippet below hides all selects sharing toggle class), then identify which country was selected and show the province select for that country. Voilà!
<!DOCTYPE html>
<html>
<head>
<title>Gegevens</title>
</head>
<body>
<center>
<h1>Gegevens</h1>
</center>
Land:
<select id="countrySelect" onchange="toggleCountry()">
<option value="Holland">Holland</option>
<option value="England">England</option>
</select><br>
Provincie:
<select id="provinceHolland" class="toggle">
<option value="Gelderland">Gelderland</option>
<option value="Utrecht">Utrecht</option>
</select>
<select id="provinceEngland" class="toggle" style="display:none">
<option value="Schotland">Schotland</option>
<option value="Wales">Wales</option>
</select>
<footer>Ga terug</footer>
<script>
function toggleCountry() {
var list = document.getElementsByClassName("toggle");
for (var i = 0; i < list.length; i++) {
list[i].style.display = "none";
}
var sub = "province" + document.getElementById("countrySelect").value;
document.getElementById(sub).style.display = "inline";
}
</script>
</body>

Using Javascript to check form elements and enabling/disabling the search button

I need your help,
Using javascript, how could I add some sort of data form validation that would be two-fold:
1st Event, [OnKeyUp] attached to all of the input boxes
2nd Event, [OnChange] attached to all of the select boxes
Typical User Scenarios
If there is any data present in any of the input boxes and no selected option values then { enable the search button } else { keep the search button disabled }
If there are any selected option values who’s option value is not null and no data present in all of then { enable the search button } else { keep the search button disabled }
<!DOCTYPE html>
<html>
<head></head>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
</html>
var car=$('#car'); var fruits=$('#fruits');
var veggie=$('#veggie'); var number = $('#number');
$('select').change(function(){
validate();
});
$('input').keyup(function(){
validate();
});
function validate(){
if(($(veggie).val()!='' || $(number).val()!='') &&
$(car).val()=='' && $(fruits).val()==''){
$('#search').prop('disabled',false);
}else if($(veggie).val()=='' && $(number).val()=='' &&
($(car).val()!='' || $(fruits).val()!='')){
$('#search').prop('disabled',false);
}else{
$('#search').prop('disabled',true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
I'm not 100% sure, but it looks like you want to enable the button if only one of the select elements has a value or one of the input elements has a value, but not if both (or neither) do.
If that's the case then this should work, and it allows you you add as many elements to it as you need by adding IDs to the arrays at the top.
https://jsfiddle.net/j7by6bsz/
var selectInputIds = ['fruits', 'car'];
var textInputIds = ['veggie', 'number'];
function setButtonState() {
var hasVal = function(arr) {
for(var i = 0; i < arr.length; i++) {
if(document.getElementById(arr[i]).value) {
return true;
}
}
return false;
};
var hasSelectValue = function () {
return hasVal(selectInputIds);
}
var hasTextValue = function () {
return hasVal(textInputIds);
}
var theButton = document.getElementById('search');
var s = hasSelectValue();
var t = hasTextValue();
theButton.disabled = ((s && t) || (!t && !s)); // you can do this bit smarter, but this is explicit
}
(function attachStuff (arr, evt) {
function listenIn(arr, evt) {
for(var i = 0; i < arr.length; i++) {
document.getElementById(arr[i]).addEventListener(evt, setButtonState);
}
}
listenIn(selectInputIds, 'change');
listenIn(textInputIds, 'keyup');
}())
Your requirements could use some clarification around what happens if both input types have values though.

Changing one form value based on onChange of another with javascript

I can't seem to get this function to work out. I'm trying to change the "business" input value of my form based on an amount selected in the "amount" dropdown. What am I missing!!! I've been trying this for an hour.
<script type="text/javascript">
function chPy()
{
var businessvar = "paypals#ramatico.com";
if (document.forms['5'].amount.value > 11){
businessvar = "paypall#ramatico.com"
}
document.forms['5'].business.value = businessvar;
}
</script>
<form name="5">
<select name="amount" OnChange="chPy()">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input name="business" type="text" value="">
</form>
Ok. The next step. I have about 100 of these forms on a page. Instead of creating one for each form, I'd like to have one script that changes based on which form is being changed with "onChange". Each of the forms on the page have values of the same name (but not ID) (they are for paypal). I think it will be ok if I can change the"formname" in the following: "document.forms['formname']" based on a variable populated by something like chPy("formname") etc..... I can't seem to get that to work either.
Removing the form reference would take care of both of your items.
<script type="text/javascript">
function chPy(oSelect)
{
var businessvar = "paypals#ramatico.com";
if (oSelect.form.amount.value > 11){
businessvar = "paypall#ramatico.com"
}
oSelect.form.business.value = businessvar;
}
</script>
<form name="5">
<select name="amount" OnChange="chPy(this)">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input name="business" type="text" value="">
</form>
Problem is that you are using a number as form name.
Add some letters to the name and it will work:
<script type="text/javascript">
function chPy()
{
var businessvar = "paypals#XYZ.com";
if (document.forms['form5'].amount.value > 11){
businessvar = "paypall#XYZ.com"
}
document.forms['form5'].business.value = businessvar;
}
</script>
<form name="form5">
<select name="amount" OnChange="chPy()">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input name="business" type="text" value="">
</form>
HTML:
<form name="form5">
<select name="amount">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input type="text" name="business">
</form>
JavaScript:
var form5 = document.forms['form5'];
form5.amount.onchange = function() {
form5.business.value =
(this.value > 11 ? 'paypall' : 'paypals') + '#ramatico.com';
}
Live demo: http://jsfiddle.net/Fx7zh/
For multiple forms, you can use this JavaScript code:
for (var i = 0, l = document.forms.length; i < l; i++) {
document.forms[i].amount.onchange = function(i) {
this.form.business.value =
(this.value > 11 ? 'paypall' : 'paypals') + '#ramatico.com';
}
}
Live demo: http://jsfiddle.net/Fx7zh/2/

Categories

Resources