Select option value based on input value - javascript

I have a form selling lengths of cable, there is one price for lengths (5 - 95m) and a second for (100-200m). Based on the length put in the input field I would like the correct price option selected in the drop down menu. What javascript would I need for this.
<select id="leaveCode" name="leaveCode">
<option value="0" selected="selected">Price Option</option>
<option value="5.83">5 to 95m - £5.83</option>
<option value="5.00">100 to 200m - £5.83</option>
</select>
Length required:
<input type="number" id="length" size="4" maxlength="5" min="5" max="200" step="5">
<input type="button" value="Calculate">
Any help would be appreciated.
Thanks

I've added a function in my demo to calculate on change and on button click. Best of luck!
http://jsfiddle.net/vL1a4sdu/
<select id="leaveCode" name="leaveCode">
<option value="0" selected="selected">Price Option</option>
<option value="5.83">5 to 95m - £5.83</option>
<option value="5.00">100 to 200m - £5.83</option>
</select>
Length required:
<input type="number" id="length" size="4" maxlength="5" min="5" max="200" step="5">
<input id="calculate" type="button" value="Calculate">
<div id="cost"></div>
<script>
$('#leaveCode').change(function(){
var price = $(this).val();
var length = $("#length").val();
if ( length ) {
var cost = calculate(price, length);
$("#cost").text(cost);
}
});
$('#calculate').click(function(){
var price = $( "#leaveCode" ).val();
var length = $("#length").val();
if ( price !== null && length !== null ) {
var cost = calculate(price, length);
$("#cost").text(cost);
}
});
function calculate(price,length) {
var cost = price*length;
return cost;
}
</script>

Managed to sort it this way
<select id="dropdown" name="dropdown">
<option value="0" selected="selected">Price Option</option>
<option value="5.83">5 to 95m - £5.83</option>
<option value="5.00">100 to 200m - £5.83</option>
</select>
Length required:
<input type="number" id="length" size="4" maxlength="5" min="5" max="200" step="5" onblur="quickSelect()">
<input type="button" value="Calculate" onClick="quickSelect()">
Javascript
<script type="text/javascript">
function quickSelect() {
var len = Number($("#length").val());
if (len >= 5 && len <= 95) {
document.form.dropdown[1].selected = "1"
}
if (len >= 100 && len <= 200) {
document.form.dropdown[2].selected = "1"
}
}
</script>

See http://jsfiddle.net/mpv1e72j/ to solve this with jQuery
$(document).ready(function(){
$("#length").change(function(){
var len = Number($("#length").val());
if (len >= 5 && len <= 95) $("#leaveCode").val("5.83");
if (len >= 100 && len <= 200) $("#leaveCode").val("5.00");
});
});

Related

javascript - && statement between input text and input select

I want to get output based on text input and select input, the value of strength will be determined by nvalue and type(select)
my current code:
function findStrength() {
var n = document.getElementById('nvalue');
if ($(".select-box option[value='clay']").attr('selected') && $(n.value == '30')) {
document.getElementById('soil_strength').value = 'HARD';
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="nvalue" name="nvalue" min="0" max="50" required />
<select class="select-box" name="soil_type" id="soil_type2">
<option value="" disabled selected hidden>Type</option>
<option value="clay">CLAY</option>
<option value="silt">SILT</option>
<option value="sand">SAND</option>
<option value="gravel">GRAVEL</option>
</select>
<input type="text" id="soil_strength" name="soil_strength" placeholder="Strength" />
You should not mix jQuery and DOM access. Here I delegate from form and any change to the fields will update the strength
Also you had typos in the max and required attributes
Lastly why not use a number field?
const soilForm = document.getElementById('soilForm');
soilForm.addEventListener("input", function() {
const n = +this.nvalue.value; // cast to number
const soil = this.soil_type.value;
if (soil === "clay" && n === 30) {
this.soil_strength.value = 'HARD';
}
else this.soil_strength.value = "";
})
<form id="soilForm">
<input type="number" id="nvalue" name="nvalue" min="0" max="50" required />
<select class="select-box" name="soil_type" id="soil_type2">
<option value="" disabled selected hidden>Type</option>
<option value="clay">CLAY</option>
<option value="silt">SILT</option>
<option value="sand">SAND</option>
<option value="gravel">GRAVEL</option>
</select>
<input type="text" id="soil_strength" name="soil_strength" placeholder="Strength" />
</form>
jQuery version
$('#soilForm').on('input', function() {
const n = +$('#nvalue').val(); // cast to number
const soil = $('#soil_type2').val(); // why name="soil_type" and id="soil_type2" ?
let strength = "";
if (soil === 'clay' && n === 30) {
strength = 'HARD';
}
$('#soil_strength').val(strength);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="soilForm">
<input type="number" id="nvalue" name="nvalue" min="0" max="50" required />
<select class="select-box" name="soil_type" id="soil_type2">
<option value="" disabled selected hidden>Type</option>
<option value="clay">CLAY</option>
<option value="silt">SILT</option>
<option value="sand">SAND</option>
<option value="gravel">GRAVEL</option>
</select>
<input type="text" id="soil_strength" name="soil_strength" placeholder="Strength" />
</form>
You can use jQuery more effectively.
<script>
$(document).ready(function() {
$('#nvalue, #soil_type2').on('change',function(){
let type = $('#soil_type2').val();
let nvalue = $('#nvalue').val();
if (type == 'clay' && nvalue == '30') {
$('#soil_strength').val('HARD');
} else {
$('#soil_strength').val('EASY');
}
});
});
</script>

Sum input and return values in div with JavaScript and jQuery

I'm trying to return the sum of input values in real time, but it just adds up the whole value and doesn't add up the cents. I would like to add the cents too, what can I do?
Currently, the script returns something like: 100.00
But it was supposed to return: 100.85
I think it's a simple thing to solve, but I'm new to JavaScript.
Here is my code:
$('.cardAccordion').on("change", function() {
var lts = $(this).find("#lts").val();
var fuelPrice = $(this).find("#fuelPrice").val();
var calc = lts * fuelPrice;
var sum = calc.toLocaleString("pt-BR", {
style: "currency",
currency: "BRL"
});
$(this).find("#ltsValue").val(calc)
})
var res = 0.00;
$('#addToCart').click(function() {
var val = $(this).parents('.cardAccordion').find('#ltsValue').val();
if(val == 0){
$("#lts").css({
borderColor: "#f27474"
})
}else{
var qnt = $(this).parents('.fuelCard').find('#qntField').val();
$(this).parents('.cardAccordion').find('#ltsValue').each(function () {
res += ~~$(this).val() * qnt;
});
var sum = res.toLocaleString("pt-BR", {
style: "currency",
currency: "BRL"
});
$("[name=result]").val(res);
$("h3[name=resultText]").text(sum)
}
})
<div class="card fuelCard">
<input type="number" value="1" id="qntField" name="quantity" class="form-control quantityField" disabled>
<div class="cardAccordion">
<input type="hidden" value="6.39" id="fuelPrice" />
<label>Litros</label>
<select class="form-control" id="lts">
<option value="0">Selecione</option>
<option value="5">5 Lts</option>
<option value="10">10 Lts</option>
<option value="15">15 Lts</option>
<option value="20">20 Lts</option>
</select>
<input type="text" class="form-control" id="ltsValue" value="0" disable />
<button class="btn" id="addToCart">Adicionar ao carrinho</button>
<input type="hidden" value="0.00" name="result" />
<h3 name="resultText">R$ 0,00</h3>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Integer arithmetic rounds down. Use parseFloat instead.
I done some changes to your code here is the working demo.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="card fuelCard">
<input type="number" value="1" id="qntField" name="quantity" class="form-control quantityField" disabled>
<div class="cardAccordion">
<input type="hidden" value="6.39" id="fuelPrice" />
<label>Litros</label>
<select class="form-control" id="lts">
<option value="0">Selecione</option>
<option value="5">5 Lts</option>
<option value="10">10 Lts</option>
<option value="15">15 Lts</option>
<option value="20">20 Lts</option>
</select>
<input type="text" class="form-control" id="ltsValue" value="0" disable />
<button class="btn" id="addToCart">Adicionar ao carrinho</button>
<input type="hidden" value="0.00" name="result" />
<h3 name="resultText">R$ 0,00</h3>
</div>
</div>
<script>
$('.cardAccordion').on("change", function() {
var lts = $(this).find("#lts").val();
var fuelPrice = $(this).find("#fuelPrice").val();
var calc = lts * fuelPrice;
var sum = calc.toLocaleString("pt-BR", {
style: "currency",
currency: "BRL"
});
$(this).find("#ltsValue").val(calc)
})
var res = 0.00;
$('#addToCart').click(function() {
var val = $(this).parents('.cardAccordion').find('#ltsValue').val();
if(val == 0){
$("#lts").css({
borderColor: "#f27474"
})
}else{
var qnt = $(this).parents('.fuelCard').find('#qntField').val();
$(this).parents('.cardAccordion').find('#ltsValue').each(function () {
res += parseFloat($(this).val()) * qnt;
});
var sum = res.toLocaleString("pt-BR", {
style: "currency",
currency: "BRL"
});
$("[name=result]").val(parseFloat(res));
$("h3[name=resultText]").text(sum)
}
})
</script>
</body>
</html>

Multiply input value with select option data attribute

I have the following code that is not working the way i want it to, apparently, am trying to multiply select option data attributes with input text area values but instead select option value are being used. I need to figure out why its so.
Here is my code;
<input id="count" min="1" value="1" class ="txtMult form-control" type="number" name="txtEmmail" />
<input type="text" value="" class ="txtMult" name="txtEmmail"/>
<span class="multTotal"></span>
<select class="selectpicker">
<option value="1" data-cubics='1'>multiply with 1</option>
<option value="5" data-cubics='5'>multiply with 5</option>
</select>
<span id="grandTotal">250</span>
$(function(){
$('.txtMult').change(function(){
var p=$(this).parent().parent()
var m=p.find('input.txtMult')
var mul=parseInt($(m[0]).val()*$(m[1]).val()).toFixed(2)
var res=p.find('.multTotal')
res.html(mul);
var total=0;
$('.multTotal').each(function(){
total+=parseInt($(this).html());
})
parseInt(total).toFixed(2);
$('#grandTotal').html(parseInt(total).toFixed(2));
});
})
$('.selectpicker').change(function() {
calcVal();
});
function calcVal(){
$(this).data('cubics')*$('.multTotal').html();
$("#grandTotal").html($(this).data('cubics')*$('.multTotal').html())
}
// call on document load
calcVal();
Don't use .html() to get the values, use .text() instead.
You need to get the selected option using this:
$("#grandTotal").html($(this).children(':checked')
$(function() {
$('.txtMult').change(function() {
var p = $(this).parent().parent()
var m = p.find('input.txtMult')
var mul = parseInt($(m[0]).val() * $(m[1]).val()).toFixed(2)
var res = p.find('.multTotal')
res.html(mul);
var total = 0;
$('.multTotal').each(function() {
total += parseInt($(this).text());
})
parseInt(total).toFixed(2);
$('#grandTotal').html(parseInt(total).toFixed(2));
});
})
$('.selectpicker').change(calcVal);
function calcVal() {
$("#grandTotal").html($(this).children(':checked').data('cubics') * $('.multTotal').text().trim())
}
// call on document load
calcVal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<input id="count" min="1" value="1" class="txtMult form-control" type="number" name="txtEmmail" />
<input type="text" value="" class="txtMult" name="txtEmmail" />
<span class="multTotal"></span>
<select class="selectpicker">
<option value="1" data-cubics='1'>multiply with 1</option>
<option value="5" data-cubics='5'>multiply with 5</option>
</select>
<span id="grandTotal">250</span>
</div>
</div>

Doing Calculations with multiple options in Javascript

I'm quite new to Javascript and have started to do simple calculations, but have run into a barrier with <select>.
I want the code to get what the user has selected in the drop-down menu and multiply the number in the "How many nights?" box. The answer will be displayed in the textbox below. The options in the select menu all have prices tied to them.
< script language = "javascript" >
function calculate() {
var val1 = parseInt(document.getElementById("Nights").value);
var val1 = parseInt(document.getElementById("House").value);
var House1 = 100;
var House2 = 175;
var House3 = 150;
var House4 = 135;
var House5 = 150;
var House6 = 120;
var House7 = 180;
var House8 = 120;
var House9 = 80;
var House10 = 105;
var ansD = document.getElementById("answer");
ansD.value = House * Nights;
}
} < /script>
<html>
<head>
<title>Calculate cost</title>
</head>
<body>
<select required class="textfield" name="House" id="House">
<option value="">None</option>
<option value="House1">House 1</option>
<option value="House2">House 2</option>
<option value="House3">House 3</option>
<option value="House4">House 4</option>
<option value="House5">House 5</option>
<option value="House6">House 6</option>
<option value="House7">House 7</option>
<option value="House8">House 8</option>
<option value="House9">House 9</option>
<option value="House10">House 10</option>
</select>
<br />
<br />How many nights?
<input type="text" id="Nights" name="Nights" value="1" />
<input type="button" name="Submit" value="Cost" onclick="javascript:addNumbers()" />
<br />
<br />Your stay will cost £
<input type="text" id="answer" name="answer" value="" />
</body>
</html>
With setting the value for the houses inside the select dropdown, you help yourself quite a lot. You can see that the javascript part is greatly reduced, and that it is actually quite simple to sum the values together
Also, it is important that your button is not of type submit, as it would then submit your script, and well, you don't see the result of your calculate function then ;)
function calculate() {
var houseEl = document.getElementById('houseType'),
nightEl = document.getElementById('nightsCount'),
resultEl = document.getElementById('result');
if (houseEl.selectedIndex < 0 || parseInt(nightEl.value) < 0) {
resultEl.innerHTML = 'n/a';
return;
}
resultEl.innerHTML = parseInt(houseEl.options[houseEl.selectedIndex].value) * parseInt(nightEl.value);
}
window.addEventListener('load', function() {
document.getElementById('btnCalculate').addEventListener('click', calculate);
});
<select id="houseType">
<option value="0">None</option>
<option value="100">House 1</option>
<option value="150">House 2</option>
</select>
<input type="number" min="1" value="1" id="nightsCount" />
<button type="button" id="btnCalculate">Calculate</button>
<div>
The total amount for your stay would be <span id="result"></span> €
</div>
I suggest you to use an Object that keeps "key"-"value" pairs.
a is an Object, it contains keys such as House1, House2 and prices as values.
a[val2] will give you a price for staying one night in the hotel.
if None value (or other not available in the Map value) comes from the form,
isNaN() check will give true and No price message will be printed out.
<html>
<head>
<title>Calculate cost</title>
<script language = "javascript">
function calculate() {
var val1 = parseInt(document.getElementById("Nights").value);
var val2 = document.getElementById("House").value;
var a={};
var prices = [ 100, 175, 150, 135, 150, 120, 180, 120, 80, 105 ];
for (var i = 1; i < 11; i++)
{
a["House"+i] = prices[i];
}
var ansD = document.getElementById("answer");
if (isNaN(a[val2]))
ansD.value="No price!";
else
ansD.value = val1 * a[val2];
}
</script>
</head>
<body>
<select required class="textfield" name="House" id="House">
<option value="">None</option>
<option value="House1">House 1</option>
<option value="House2">House 2</option>
<option value="House3">House 3</option>
<option value="House4">House 4</option>
<option value="House5">House 5</option>
<option value="House6">House 6</option>
<option value="House7">House 7</option>
<option value="House8">House 8</option>
<option value="House9">House 9</option>
<option value="House10">House 10</option>
</select>
<br />
<br />How many nights?
<input type="text" id="Nights" name="Nights" value="1" />
<input type="button" name="Submit" value="Cost" onclick="calculate()" />
<br />
<br />Your stay will cost £
<input type="text" id="answer" name="answer" value="" />
</body>
</html>

selecting dropdown list and change step attribute of input

i want when choosed A option , input value will be 10,20,30 ...
for B option, input value 5,10,15,20
that code didnt work what is wrong
<select onchange="changeValue(this);" id="size" name="attribute_size">
<option selected="selected" value="">choose option…</option>
<option class="active" value="A">A</option>
<option class="active" value="B">B</option>
</select>
<input min="1" step="1" id="quantity" value="1" title="quantity" class="input-text qty text" size="4" type="number">
function changeValue() {
var option2 = document.getElementById('size').options[document.getElementById('size').selectedIndex].id;
if (option2 == "A") {
document.getElementById('quantity').setAttribute('step', "10");
}
else (option2 == "B")
{
document.getElementById('quantity').setAttribute('step', "5");
}
}
You have a missed if after else which was causing console error,
else if (option2 == "B")
Change the min attribute to '0',
<input min="0" step="1" id="quantity" value="0" title="quantity" class="input-text qty text" size="4" type="number">
And Javascript,
function changeValue(that) {
var option2 =that.options[that.selectedIndex].text;
var inputElm = document.getElementById('quantity');
inputElm.value = 0;
if (option2 == 'A') {
inputElm.setAttribute('step', '10');
} else if (option2 == 'B') {
inputElm.setAttribute('step', '5');
}
}
DEMO
Also, you can use the this onject passed in the parameter when operating on the current object.
You have several errors in your code. (For example typo in else if, wrong method of getting select option value and not using your argument in changeValue method)
I corrected them and put them together to working example:
<select onchange="changeValue(this);" id="size" name="attribute_size">
<option selected="selected" value="">choose option...</option>
<option class="active" value="A">A</option>
<option class="active" value="B">B</option>
</select>
<input min="1" step="1" id="quantity" value="1" title="quantity" class="input-text qty text" size="4" type="number">
<script>
function changeValue(elem) {
var input = document.getElementById('quantity');
if (elem.value == "A") {
input.setAttribute('step', "10");
}else if (elem.value == "B") {
input.setAttribute('step', "5");
}
}
</script>

Categories