I have just started with programming, so the answer may be obvious. My code has a radio button (price of a service) and a dropdown menu (quantity of orders), i want to calculate with these values. So far so good, it took me almost a day to get this short code.
My problem is now, I need the result to be shown realtime, possibly in an input tag like
<p><strong>Amount (US$)</strong>: <input type="text" name="amount" id="amount" /></p>
Maybe there is also a better way?
So, one of the two radio buttons should always be checked and show its price. When the user chooses the quantity from the dropdown menu, the result should automatically refresh.
Can anyone help me?
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<label>ABC
<input class="test" type="radio" checked="checked" name="test" value="500">
</label>
<label>DEF
<input class="test" type="radio" name="test" value="800">
</label>
<select size="1" name="dropdown" onchange='calculate(this.value);'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p><strong>Amount (US$)</strong>: <input type="text" name="amount" id="amount" /></p>
</body>
Thx for your help!
edit: Ok, even the calculation is wrong. I want to get the value of a checked radio button and turn it into an int. After this I need the int to be multiplied with the value from the checkbox. I dont know what I am missing, but its always calculating with the first radio button value, even if I check the second one.
<script>
var x = $('input[name="test"]:checked').val();
var xInt = parseInt(x, 10);
function calculate (val) {
var result = val * xInt ;
var amountPrint = document.getElementById('amount');
amountPrint.value = result;
}
$(".test").click(function(event) {
var total = 0;
$(".test:checked").each(function() {
total += parseInt($(this).val());
});
if (total == 0) {
$('#amount').val('');
} else {
$('#amount').val(total);
}
});
</script>
I still got the problem, that I need the results to be shown realtime, depending which radio button and dropdown value is checked. So I added a class "test" to the radio buttons and added the above function. Now I got the result in realtime, depending on the checked radio button, but the calculation is still wrong and i need to combine it somehow.
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<label>ABC
<input type="radio" checked="checked" name="test" value="500">
</label>
<label>DEF
<input type="radio" name="test" value="800">
</label>
<select size="1" name="dropdown" onchange='calculate(this.value);'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p><strong>Amount (US$)</strong>: <input type="text" name="amount" id="amount" value="" /></p>
</body>
<script>
var x = $('input[name="test"]:checked').val();
var xInt = parseInt(x, 10);
function calculate (val) {
var result = val * xInt ;
var amountPrint = document.getElementById('amount');
amountPrint.value = result;
}
</script>
You just need to push a new value to the amount area.
All I have done is added a value="" to the Amount input, which could be skipped but it is good practice IMO.
Then in the js beneath. Get the element by id which you provided earlier.
Then use your calculation, and with that tell it to change the value of id 'amount'
You could also add <p id='printResultsHere'></p> for example and call in much the same way.
I hope this helps. Please mark answer as accepted if so.
Based off the comments above
To convert strings to int use parseInt() as for to detecting change you need to detect to the radio buttons. Now you can go through and add onChange = or onClick = to all of them manually. With two why not but if you intend on having more and they will all change the outcome. You could just loop through them.
Add this to the bottom of the code
//Loop through the radio buttons, first find all the elements with that Name then you can
//loop through to to detect the onClick.
var radios = document.getElementsByName('test')
for (var i = 0, max = radios.length; i < max; i++) {
radios[i].onclick = function () {
console.log(parseInt(this.value));
}
}
You may need to rewrite the code a bit differently, as you are dealing with two varaiblies into the code but your function is only accepting one.
So to avoid doing another loop, easier to just give it an Id and go forward. So now everytime you change the check boxes it will re run the code with whatever the current value from dropdown is.
The below does what I think you want.
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<label>ABC
<input type="radio" checked="checked" name="test" value="500">
</label>
<label>DEF
<input type="radio" name="test" value="800">
</label>
<select size="1" id='dropdown' name="dropdown" onchange='calculate(this.value);'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p><strong>Amount (US$)</strong>: <input type="text" name="amount" id="amount" value="" /></p>
</body>
<script>
var x = $('input[name="test"]:checked').val();
var xInt = parseInt(x, 10);
//Get the input Box you want to print to
var amountPrint = document.getElementById('amount');
//All the radio boxes which you named test
var radios = document.getElementsByName('test')
function calculate(val) {
var result = val * xInt;
//var amountPrint = document.getElementById('amount');
amountPrint.value = result;
}
var radios = document.getElementsByName('test')
for (var i = 0, max = radios.length; i < max; i++) {
radios[i].onclick = function () {
xInt = parseInt(this.value, 10)
calculate(document.getElementById('dropdown').value)
}
}
</script>
Related
My task is to make a form with drop down menu for title, text input for first name, last name and email and then intrests as checkboxes.
i have succesfully made the form and have put in place messages when something isnt right on the form however now i need stop somone from being able to type in the first name if they havent selected a title or if title === --
i then need to do the same for the last name but with first name rather than title, i should be able to work round that if i know how to do the first one as the only change is the input type.
if anyone could help thatd be great :)
Verry simple example.
By default, the fields are set to "disabled". The script checks for the previous field in the list and if it has content removes the "disabled" from the next field
var list = document.getElementsByClassName('inpt');
for (let i = 0; i < list.length; i++) {
list[i].addEventListener("change", function () {
if (this.value.length > 0) {
checkInputs(this);
}
});
}
function checkInputs(x) {
for (let i = 0; i < list.length-1; i++) {
if (list[i].id === x.id) {
var z = document.getElementById(list[i + 1].id)
z.removeAttribute('disabled');
z.focus();
}
}
}
<select class="inpt" id="first">
<option value="">Select...</option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<input class="inpt" id="name" type="text" disabled>
<input class="inpt" id="surname" type="text" disabled>
<input class="inpt" id="age" type="text" disabled>
I wanted to make multiple checkboxes and every time I check one of them the value of the first input reduce by a number for example when we select checkbox1 the number in input reduces by 10 and when we select checkbox2 it reduces by 20 and when we select both of them it reduces by 30.
I have handled the first checkbox though.
<html lang="en">
<head>
</head>
<body>
<input type="number" id="input">
<input type="checkbox" onclick="one()" id="checkboxId">
<input type="checkbox" onclick="" id="checkboxId2">
<p id="par">hello</p>
<script>
function one () {
var check = document.getElementById("checkboxId");
if (check.checked) {
let input = document.getElementById("input").value;
y = input - 10;
document.getElementById("par").innerHTML = y;
} else {
document.getElementById("par").innerHTML=document.getElementById("input").value;
}
}
</script>
</body>
</html>
You can try using data-* attribute. Also, you can get the value only from the checked check boxes, sum them and deduct that from the input value.
Try the following way:
function one () {
var total = Array.from(document.querySelectorAll(':checked'))
.map(el => el.getAttribute('data-value'))
.reduce((a,c) => a+ Number(c), 0);
document.getElementById("par").textContent = Number(document.getElementById("input").value) - total;
}
<input type="number" id="input">
<input type="checkbox" onclick="one()" data-value="10" id="checkboxId">
<input type="checkbox" onclick="one()" data-value="20" id="checkboxId2">
<p id="par">hello</p>
Hi i am new to javascript and having some trouble.
I need my function to take the user input "recserv" and multiply it by the value of the selected radio button, as well as update if the value is changed or the radio button is changed.
Changing the radio buttons seems to work, but I get an error when the "recserv" value is changed.
Thank you for any help!
<script>
function yeartot(service) {
var recserv = parseFloat(document.getElementById('recserv').value);
document.getElementById("result").value = service*recserv;
}
</script>
<body>
<p>Select the frequency</p>
<input onclick="yeartot(this.value)" type="radio" name="service" value="11">Monthly<br>
<input onclick="yeartot(this.value)" type="radio" name="service" value="6" checked> Bi-Monthly<br><br>
Recurring Service Amount <input onchange="yeartot()" id="recserv" value=0><br/><br/>
Total for year <input type="text" id="result">
The reason why you are getting NaN is because in your #recserv element's inline JS, you are not passing any value into the function when calling it. Therefore, you are multiplying with undefined which gives you a NaN value.
A quick fix to your issue will simply be letting the method itself retrieve the checked value of your input, and removing the need to pass any arguments to it. This is, however, a quick fix and I would never recommend using inline JS: check the next example for a proper solution.
function yeartot() {
var recserv = +document.getElementById('recserv').value;
var checkedService = +document.querySelector('input[name="service"]:checked').value;
document.getElementById("result").value = checkedService * recserv;
}
<p>Select the frequency</p>
<input onclick="yeartot()" type="radio" name="service" value="11">Monthly<br>
<input onclick="yeartot()" type="radio" name="service" value="6" checked> Bi-Monthly<br><br> Recurring Service Amount <input onchange="yeartot()" id="recserv" value=0><br/><br/> Total for year <input type="text" id="result">
Proposed solution: I suggest that you:
Use .addEventListener to listen to changes to your input elements. You can use document.querySelectorAll([selector]) to select the inputs that you want to bind the oninput event listener to. The callback will simply invoke yeartot()
Invoke yeartot() at runtime, so that you get calculated values when the document is loaded.
function yeartot() {
var recserv = +document.getElementById('recserv').value;
var checkedService = +document.querySelector('input[name="service"]:checked').value;
document.getElementById("result").value = checkedService * recserv;
}
document.querySelectorAll('#recserv, input[name="service"]').forEach(function(el) {
el.addEventListener('change', function() {
yeartot();
});
});
// Also, might want to run the first round of computation onload
yeartot();
<p>Select the frequency</p>
<input type="radio" name="service" value="11">Monthly<br>
<input type="radio" name="service" value="6" checked> Bi-Monthly<br><br> Recurring Service Amount <input id="recserv" value=0><br/><br/> Total for year <input type="text" id="result">
simply this...
document.getElementById('my-form').addEventListener('input', function () {
this.result.textContent = parseFloat(this.recserv.value) * parseInt(this.service.value)
})
<form id="my-form" onsubmit="return false">
<p>Select the frequency</p>
<input type="radio" name="service" value="11">Monthly
<br>
<input type="radio" name="service" value="6" checked> Bi-Monthly
<br><br>
Recurring Service Amount <input name="recserv" value="0">
<br /><br />
Total for year <output name="result"></output>
</form>
-- adding a form makes things easier if each entry (or output) has a name.
-- using a form element, you do not need to use any ID, and you do not need to see which radio button is checked, you directly take the selected value
-- and do not use a change event but use input event
const setup = () => {
const serviceInputs = document.querySelectorAll('input[name="service"]');
serviceInputs.forEach(e => e.addEventListener('click', yeartot));
const recserv = document.querySelector('#recserv');
recserv.addEventListener('change', yeartot);
}
const yeartot = (service) => {
const checkedInput = document.querySelector('input:checked');
const recserv = document.querySelector('#recserv');
const serviceNumber = parseFloat(checkedInput.value, 10);
const recservNumber = parseFloat(recserv.value, 10);
const result = document.querySelector('#result');
result.value = serviceNumber * recservNumber;
}
//load
window.addEventListener('load', setup);
<body>
<p>Select the frequency</p>
<input type="radio" name="service" value="11">Monthly<br>
<input type="radio" name="service" value="6" checked> Bi-Monthly<br><br>
Recurring Service Amount <input id="recserv" value="0"><br/><br/>
Total for year <input type="text" id="result">
</body>
yeartot method has a parameter and when you use yeartot() in onchange property of input cause undefined value in service parameter.undefined value is not a number and take error.
Change your script into this
<script>
const input = document.getElementById("recserv");
const result = document.getElementById("result");
function yeartot(service) {
const checkedService = document.querySelector(":checked");
var recserv = Number(document.getElementById("recserv").value);
document.getElementById("result").value =
Number(checkedService.value) * Number(input.value);
}
</script>
I have 2 set of input types of text boxes. 2 fields on each. I am trying to calculate and compare each set individually in single page.
The input types have different ids.
<input type="text" id="tmcp_textfield_1" name="blueberry"
placeholder="blueberry" value="0" onkeydown="calculate()"
onkeyup="calculate()">
<input type="text" id="tmcp_textfield_2" name="plums" placeholder="plums" value="0"
onkeydown="calculate()" onkeyup="calculate()">
<input type="text" id="a3" name="a3" placeholder="a3" value="0">
<br>second set below<br>
<input type="text" id="tmcp_textfield_3" name="blueberry"
placeholder="blueberry" value="0" onkeydown="calculate()"
onkeyup="calculate()">
<input type="text" id="tmcp_textfield_4" name="plums" placeholder="plums" value="0"
onkeydown="calculate()" onkeyup="calculate()">
<input type="text" id="a3`" name="a3" placeholder="a3" value="0">
My javascript in header:
For First set:
<script type="text/javascript">
calculate = function() {
var blueb = parseFloat($('#tmcp_textfield_1').val());//document.getElementById('blueberry').value;
var plumsb = parseFloat($('#tmcp_textfield_2').val());//document.getElementById('plums').value;
var thetotal = /*document.getElementById('a3').value =*/ parseInt(blueb)+parseInt(plumsb);
if (thetotal > 6) {
$('#tmcp_textfield_2').val('');
$('#tmcp_textfield_1').val('');
alert('Combination must be below 6');
}
}
</script>
For Second Set:
<script type="text/javascript">
calculate = function() {
var blueb = parseFloat($('#tmcp_textfield_3').val());//document.getElementById('blueberry').value;
var plumsb = parseFloat($('#tmcp_textfield_4').val());//document.getElementById('plums').value;
var thetotal = /*document.getElementById('a3').value =*/ parseInt(blueb)+parseInt(plumsb);
if (thetotal > 12){
$('#tmcp_textfield_4').val('');
$('#tmcp_textfield_3').val('');
alert('Combination must be below 12');
}
}
</script>
The problem only the first set of calculation work. When i remove the first set of javascript then the second set only work and vise versa.
How could i differentiate the sets in javascript so that both the set of inputs work together in one single html page.
Problem:
You are having same name functions "calculate()" for both sets that's why only 1 is working at a time.
Solution:
Rename the function name to different names like calculateOne() and calculateTwo() then both will work.
Hope this helps
Need to do:
1) If user forget/miss one or more field then should show errors when click submit button.
2) Show those input/selected the result below the submit button.
What I did:
1) In the first and last name field I used html5 tag "required" to show error.
2) I added javascript code for next 4 field. Actually, it works but it works for first radio field only. But if i delete for that specific radio field code then it will works next field select option code only...Similarly is happen next two field.
Don't understanding why not showing all errors at same time?
3) For showing result, I coded for first name, last name and gender but it is not working. And I don't understanding how to code for selected option value and checked box for showing result.
Any help?
function showInput() {
// No:1 For radio button code
var elem = document.forms["formSurvey"].elements['sex'];
len = elem.length-1;
chkvalue = "";
for(i=0; i<=len; i++) {
if(elem[i].checked)chkvalue = elem[i].value;
}
if(chkvalue=="") {
document.getElementById("errorg1").innerHTML = "NO button Checked";
return false;
} else {
var gendershow = document.getElementById("gendershow1").value;
document.getElementById("gendershow1").innerHTML = gendershow;
return true;
}
// No:2 For select option button code
if(document.getElementById("choose").value=="") {
document.getElementById("errorChoose").innerHTML = "Please select session!";
return false;
} else {
var sessionShow1 = document.getElementById("selectSession").value;
document.getElementById("selectSession").innerHTML = sessionShow1;
return true;
}
// No:3 For Check button code
var allchecked = 0;
if(document.getElementById("int").checked)allchecked = 1;
if(document.getElementById("sch").checked)allchecked = 1;
if(document.getElementById("cur").checked)allchecked = 1;
if(allchecked == 0) {
document.getElementById("errorg2").innerHTML = "Please check the value";
return false;
} else {
var checkIt = document.getElementById("checkButton").value;
document.getElementById("checkButton").innerHTML = checkIt;
return true;
}
// No:4 Show the input/selected result
var first_name = document.getElementById("fname").value;
document.getElementById("display_fname").innerHTML = first_name;
var last_name = document.getElementById("lname").value;
document.getElementById("display_lname").innerHTML = last_name;
var tellGender = document.getElementByName("sex").value;
document.getElementById("gendershow1").innerHTML = tellGender;
}
<!DOCTYPE html>
<html>
<head>
<title>CSE </title>
</head>
<body>
<div class="content">
<!-- Enter information about CSE Center -->
<p>
<form name="formSurvey" onsubmit="return showInput()" action="index.html" method="post">
<p>First name: <input type="text" name="fname" id="fname" required> </p>
<p>Last name: <input type="text" name="lname" id="lname" required></p>
<br>
<h4> Gender:</h4>
<p><input type="radio" name="sex" value="Male" id="gender1"> Male</p>
<p><input type="radio" name="sex" value="Female" id="gender2" > Female</p>
<p><input type="radio" name="sex" value="Prefer" id="gender3" > Prefer not to include</p>
<p><span style="color:red;" id="errorg1"></span></p>
<br>
<h4> Which semester do you plan on attending?</h4>
<select id="choose">
<option value="">Choose a session</option>
<option value="summer">Summer 2015</option>
<option value="fall">Fall 2015</option>
<option value="spring">Spring 2016</option>
</select>
<p><span style="color:red;" id="errorChoose"></span></p>
<br>
<h4>How did you hear about PSU?</h4>
<p><span style="color:red;" id="errorg2"></span></p>
<p><input type="checkbox" name="pt" value="Internet" id="int"> Internet Site</p>
<p><input type="checkbox" name="pt" value="School Fair" id="sch" > While attending school fair.</p>
<p><input type="checkbox" name="pt" value="Current Student" id="cur"> Current Student of PSU</p><br>
<input type="submit" value="Submit">
<br>
</form>
<p><span id="display_fname"></span></p>
<p><span id="display_lname"></span></p>
<p><span id="gendershow1"></span></p>
<p><span id="selectSession"></span></p>
<p><span id="checkButton"></span></p>
</p>
</div>
<script src="script.js"></script>
</body>
</html>
From a quick lookover it seems that the reason why it's not showing all the errors at the same time is because of two reasons:
You use an if/elseif/else statement which will only allow for one to be true.
You are returning every time you find something wrong. This will not allow the other statements to run before you return.
So changing the first thing to multiple if statements and then not returning as soon as you find an error will most likely solve your problem.