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>
Related
I can't seem to figure out how to sum the values of various field types in a form. I have some select fields like this:
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
And some radio buttons:
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
But how would I add the selections all up? I can find solutions for adding values of just inputs, or just radios, or just selects. But not all together.
I'd use jQuery if I have to.
[EDIT] I should have said, I'd like to output the total value to the user, perhaps inside a element.
Could clean this up a bit, but an example of using the FormData interface to add up all values in a form: https://developer.mozilla.org/en-US/docs/Web/API/FormData
function getValues() {
let myForm = document.getElementById('myForm');
let formData = new FormData(myForm);
let total = 0;
for (var value of formData.values()) {
total += parseInt(value);
}
document.getElementById("total").innerHTML = total;
console.log(total);
}
<form id="myForm" name="myForm">
<div>
<label for="age">What is your age?</label>
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
</div>
<div>
<label for="riskSmoke">Do you smoke?</label>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
</div>
</form>
<button onclick="getValues()">Get Values</button>
<p>Total:</p>
<div id="total"></div>
You can use constructor FormData.
An HTML <form> element — when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.
You could add a key/value pair to this using FormData.append:
formData.append('username', 'Chris');
I assume that you mean adding the values of the selected elements and that you use some trigger in this case I use a button. To make it work select options that have values
Please try this option
const button = document.querySelector("button");
button.addEventListener("click", () => {
const age = document.querySelector("select");
const riskSmoke = document.querySelector('input[name="riskSmoke"]:checked');
if (age && age.value && riskSmoke) {
const ageValue = +age.value;
const riskSmokeValue = +riskSmoke.value;
console.log(ageValue + riskSmokeValue);
}
});
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label><input type="radio" name="riskSmoke" value="2" /> Yes</label><br />
<label><input type="radio" name="riskSmoke" value="0" /> No</label>
<button>Click</button>
Without jQuery and for selecting specific values:
function getValues() {
var ageValue = Number(document.querySelector("select[name=age]").value);
console.log('age value: ' + ageValue);
var smokeValue = Number(document.querySelector('input[name="riskSmoke"]:checked').value);
console.log('smoke value: ' + smokeValue);
console.log('age + smoke: ' + (ageValue + smokeValue));
}
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<p>
<button onclick="getValues()">Get Values</button>
jQuery seems to be a bit of a overkill. In order to get the sum of the options and inputs, you may first get the value of the option in the select tag, and then add to the value of the selected radio input as such:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Title Here</title>
</head>
<body>
<select name="age" id="someId">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label><br>
<button onclick="CalculateValue()">Calculate</button>
<script>
let ageRangePicker = null, riskSmokeOptions = null;
function CalculateValue(){
ageRangePicker = document.getElementById("someId");
if(ageRangePicker.value !== ""){
let sum = Number(ageRangePicker.value);
riskSmokeOptions = document.getElementsByName("riskSmoke")
for(i = 0; i < riskSmokeOptions.length; i++) {
if(riskSmokeOptions[i].checked)
sum += Number(riskSmokeOptions[i].value);
}
alert("Your risk is: " + sum);
}
else{
alert("Select an age range");
}
}
</script>
</body>
</html>
I wrap in a form with an ID and sum on all input, making sure only to count checked radios and checkboxes
const sumValues = () => {
let val = 0;
$("#myForm :input").each(function() {
if (this.type === "radio" || this.type === "checkbox")
val += this.checked ? +this.value : 0;
else val += +this.value; // cast to number
})
$("#total").text(val)
};
$(function() {
$("#myForm").on("change", sumValues).change(); //when page loads
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="" selected>30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" checked name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<br/>Total: <span id="total" />
</form>
Plain JS
const sumValues = () => {
let val = 0;
[...document.getElementById("myForm").querySelectorAll("input, select, textarea")].forEach(function(elem) {
if (elem.type === "radio" || elem.type === "checkbox")
val += elem.checked ? +elem.value : 0;
else val += +elem.value; // cast to number
})
document.getElementById("total").textContent = val;
};
window.addEventListener("load", function() {
document.querySelector("#myForm").addEventListener("change", sumValues)
sumValues()
})
<form id="myForm">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="" selected>30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" checked name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<br/>Total: <span id="total" />
</form>
With jQuery, you can listen for the change event and use both the jQuery .serializeArray() and the array .reduce() method to get the total:
$('form').on('change', function() {
let totalScore = $(this).serializeArray().reduce((a, f) => a += +f.value, 0);
//output to a predefined element
$('#output').text( totalScore );
})
.change();
Here is how you may define an output element:
<div class="output">
<label>Total Score: </label>
<span id="output"></span>
</div>
Note that this will give a running total and there's no need to click any button or to trigger any event other then the actions needed to make choices on the various form elements.
$('form').on('change', function() {
let totalScore = $(this).serializeArray().reduce((a, f) => a += +f.value, 0);
//console.log( totalScore );
$('#output').text( totalScore );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
</form>
<div class="output">
<label>Total Score: </label>
<span id="output"></span>
</div>
Put a button below at the bottom of your HTML and make a function something like this:
const radioControls = document.querySelectorAll('.radio-btn');
const selectControl = document.querySelectorAll('.select');
let dataTransferObject = {
radioValue: 0,
selectValue: 0
};
let sum = 0;
function collectValues() {
for(let control of radioControls) {
if (control.checked) {
dto.radioValue = control.value
}
}
dto.selectValue = selectControl[0].value;
for(let attr of Object.values(dto)) {
sum += parseInt(attr);
}
}
Then your button simply calls this function, I would imagine this would all be contained in a form of some sort:
<button onclick="collectValues()">Submit</button>
Now the variable sum holds the accumulated value.
I'm trying to calculate several values from an option selected.
<label>Processor</label> </br>
<form action="3.php" method="POST">
<select id="proSelect" name="processor" onchange="proSelectValue()">
<option value="0">Pilih Processor</option>
<?php echo $pro_option;?>
</select>
<input type="text" id="proPrice" readonly placeholder="0"></br></br>
<label>Motherboard</label></br>
<select id="moboSelect" name="motherboard" onchange="moboSelectValue()">
<option value="0">Pilih Motherboard</option>
<?php echo $mobo_option;?>
</select>
<input type="text" id="moboPrice" readonly placeholder="0"></br></br>
There the options is show, and if the option selected then the value of the options is shown in the id="proPrice" and id="moboPrice".
And the javascript for the value on the id="proPrice" is
function proSelectValue() {
var selObj = document.getElementById("proSelect");
var selValue = selObj.options[selObj.selectedIndex].value;
document.getElementById("proPrice").value = selValue;
}
function moboSelectValue() {
var selObj = document.getElementById("moboSelect");
var selValue = selObj.options[selObj.selectedIndex].value;
document.getElementById("moboPrice").value = selValue;
}
Now I wanted to calculate all of the value and show in this input
<label>Total Harga</label>
<input type="text" id="totalPrice" readonly>
How do i calculate the all of the value?
You can create another function to calculate the total and call that function inside both the event handler function.
Demo:
function proSelectValue() {
var selObj = document.getElementById("proSelect");
var selValue = selObj.options[selObj.selectedIndex].value;
document.getElementById("proPrice").value = selValue;
total();
}
function moboSelectValue() {
var selObj = document.getElementById("moboSelect");
var selValue = selObj.options[selObj.selectedIndex].value;
document.getElementById("moboPrice").value = selValue;
total();
}
function total(){
var total = Number(document.getElementById("proPrice").value) + Number(document.getElementById("moboSelect").value);
document.getElementById("totalPrice").value = total;
}
<label>Processor</label> <br>
<form action="3.php" method="POST">
<select id="proSelect" name="processor" onchange="proSelectValue()">
<option value="0">Pilih Processor</option>
<option value="1">Pilih Processor 2</option>
<option value="2">Pilih Processor 3</option>
</select>
<input type="text" id="proPrice" readonly placeholder="0"><br> <br>
<label>Motherboard</label><br>
<select id="moboSelect" name="motherboard" onchange="moboSelectValue()">
<option value="0">Pilih Motherboard </option>
<option value="1">Pilih Motherboard 2</option>
<option value="2">Pilih Motherboard 3</option>
</select>
<input type="text" id="moboPrice" readonly placeholder="0"> <br><br>
<label>Total Harga</label>
<input type="text" id="totalPrice" readonly />
</form>
i am trying to find SUM of some number based on check box and select option .
here is my code
<div class="container">
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label>
<input type="checkbox" value="10">10
</label>
</div>
<input id="total" placeholder="total" />
And my script is
function updateTotal(){
var total = 0;
$(".container input[type='checkbox']").each(function(){
if($(this).is(":checked")){
var multiplier = Number($(this).parent().prev().val());
var checkboxAmount = Number($(this).val());
total += multiplier * checkboxAmount;
}
});
$("#total").val(total);
}
$("select, input[type='checkbox']").on("change", updateTotal);
The above script is just working fine give html code . But when keep my checkbox first and select option next , then this script will not give any output
i wanted my HTML code like this , then script should be work fine for this
<div class="container">
<label>
<input type="checkbox" value="10">10
</label>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<input id="total" placeholder="total" />
any help , code coppied from here
Try this one-
function updateTotal() {
var total = 0;
$(".container").each(function () {
var checkbox = $(this).find("input[type='checkbox']");
var select = $(this).find("select");
if (checkbox.is(":checked")) {
total += Number($(this).find("input[type='checkbox']").val()) * Number(select.val());
}
});
}
Demo
Trying to change the input ID: List from A to B, but its not changing.
I am planning on creating many datalist with PHP from MySQL,
Select Company name, and see their employees in next list.
HTML:
change List:
<input type="text" id="List" list="A">
<br>
<br>
<input type="text" id="A" value="B">
<br>
<button onclick="change()">
Change List
</button>
<datalist id="A">
<option value="None">
<option value="1">
<option value="2">
</datalist>
<datalist id="B">
<option value="3">
<option value="4">
</datalist>
JAVASCRIPT:
function change() {
console.log("Started");
var x = document.getElementById('A').value;
document.getElementById('List').list = x;
var check = document.getElementById('List').list
if (check === x) {
console.log("Complete");
} else {
console.log("Failed");
}
}
Thank you, its now working.
Working
According to the Mozilla Developer Network docs, the list attribute is read-only and actually returns a reference to a DOM element (like a <datalist>):
list [Read only]
HTMLElement object: Returns the element pointed by the list attribute.
The property may be null if no HTML element found in the same tree.
Thus, you need to use setAttribute to set the list by id, and then use element.list.id to retrieve the correct value for check.
function change() {
console.log("Started")
var x = document.getElementById('A').value
document.getElementById('List').setAttribute('list', x)
var check = document.getElementById('List').list.id
if (check === x) {
console.log("Complete");
} else {
console.log("Failed");
}
}
change List:
<input type="text" id="List" list="A">
<br>
<br>
<input type="text" id="A" value="B">
<br>
<button onclick="change()">
Change List
</button>
<datalist id="A">
<option value="None">
<option value="1">
<option value="2">
</datalist>
<datalist id="B">
<option value="3">
<option value="4">
</datalist>
Since list is not a standard attribute, direct refering with the dot notation won't work. Use getAttribute and setAttribute functions instead.
function change() {
console.log("Started");
var x = document.getElementById('C'),
list = document.getElementById('List'),
check = list.getAttribute(list);
list.setAttribute('list', x);
if (check === x.getAttribute('list')) {
console.log("Complete");
} else {
console.log("Failed");
}
}
<input type="text" id="List" list="A">
<br>
<br>
<input type="text" id="C" value="B">
<br>
<button onclick="change()">
Change List
</button>
<datalist id="A">
<option value="None">
<option value="1">
<option value="2">
</datalist>
<datalist id="B">
<option value="3">
<option value="4">
</datalist>
Javascript
function change() {
document.getElementById('List').setAttribute('list', document.getElementById('A').id);
}
You need to set the value property on the dom element
document.getElementById('List').value = x;
var check = document.getElementById('List').value
if (check === x) {
console.log("Complete");
} else {
console.log("Failed");
console.log(check);
}
}
I've created a form with 5 inputs:
Service type
Number of days
Number of children
Number of adults
and I would like to change the value of a button based on these variables using JavaScript.
So Far This is what i got.
JS
$(document).ready(function(){
$('#button').click(function(e) {
var servicetype = $("#servicetype").val();
var service = $("#service").val();
var adults = $("#adults").val();
var children = $("#children").val();
var days = $("#days").val();
window.open("https://secure.sample.com/service.aspx?&days="+days"&service="+service"&adults="+adults"&children="+children"&servicetype="+servicetype , '_blank');
});
});
HTML
<select type="hidden" name="service_type" id="servicetype">
<option type="hidden" value="">Select service</option>
<option type="hidden" value="AK">Service 1</option>
<option type="hidden" value="BK">Service 2</option>
<option type="hidden" value="IK">Service 3</option>
<option type="hidden" value="HK">Service 4</option>
</select>
<input type="number" name="days" min="1" id="days">
<input type="number" name="service" min="1" id="serviceamount">
<input type="number" min="1" name="adult" id="adults">
<input type="number" min="0" name="children" id="children">
<button type="button" id="button">Click Me!</button>
I'm pretty new at this so any help would be great. Sorry for the mishap earlier.
Thanks so much guys!
Here you go. Your mistake was:
1) your variables should read "+foo+" and not just "+foo";
2) the first argument in window.open (i.e. the link) should end with an apostrophe, the same way it started.
tested and working.
$('#button').click(function() {
var servicetype = $("#servicetype").val();
var service = $("#service").val();
var adults = $("#adults").val();
var children = $("#children").val();
var days = $("#days").val();
window.open("https://secure.sample.com/service.aspx?&days="+days+"&service="+service+"&adults="+adults+"&children="+children+"&servicetype="+servicetype+"", "_blank");
});