i just changed my question to show my attempt at it. This is what im trying to do. The XPlevels have a set value, and using that i wanna calculate and display the price
function setprice() {
var val;
var type = document.getElementByName("XP")
if (type[0].checked)
{
var val = 200;
}
else if (type[1].checked)
{
var val = 150;
}
else if (type[2].checked)
{
var val = 100;
}
}
function Calculate() {
var FName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var Tprice = val * numppl;
window.alert(FName + ", the membership amount is: R " + BasePrice);
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="Calculate"/>
You can use onclick event on the Calculate Fee Button to call a JavaScript Function that checks which radio button is selected.
const calculateFee = () => {
let radioButtons = document.querySelectorAll("input");
for(let i=0; i<3; i++){
if(radioButtons[i].checked){
console.log(`Checked Radio Button is : ${radioButtons[i].value}`);
}
}
}
<input type="radio" name="XP" value="Novice" />Novice
<input type="radio" name="XP" value="Intermediate" checked />Intermediate
<input type="radio" name="XP" value="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculateFee()"/>
This is an edit of your JS code
function setprice() {
var type = document.querySelectorAll('[name="XP"]');
if (type[0].checked) {
var val = 200;
}
else if (type[1].checked) {
var val = 150;
}
else if (type[2].checked) {
var val = 100;
}
return val;
}
function calculate() {
var fName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var val = setprice();
var tprice = val * numppl.value;
// window.alert(FName + ", the membership amount is: R " + BasePrice);
console.log(tprice);
}
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculate()" />
This example a more correct approach to what you want
On each radio button, the value is the number (unit price) to be calculated. I have added a data attribute from which to take "Type"
The input named member must be set to a minimum value so that the user cannot set a negative value.
Try this code and if you have any questions I will supplement my answer!
var radio = document.querySelectorAll('.radio');
var number = document.querySelector('.number');
var button = document.querySelector('.button');
var getval;
var datainf;
button.addEventListener('click', function () {
radio.forEach(function (el) {
if (el.checked) {
getval = +el.value;
datainf = el.getAttribute('data');
}
});
var result = getval * number.value;
console.log( 'Quantity: ' + number.value + ' / Type: ' + datainf + ' / The membership amount is: ' + result);
});
<input type="radio" class="radio" name="XP" value="200" data="Novice" />Novice
<input type="radio" class="radio" name="XP" value="150" data="Intermediate" checked />Intermediate
<input type="radio" class="radio" name="XP" value="100" data="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" class="number" name="Members" size="2" value="1" min="1" />
<input type="button" class="button" value="Calculate fee" />
I have a small form designed to calculate a score based on the answers given. Everything works, the variables are shown in the variables and also shown in the html for a split second. However, after a split second, the function resets and the resulting var is also removed. In trying to understand, I think it has to do with the scope of the var or form behavior? Here is a snippet:
</head>
<body>
<form id="calculateChangeForm" name="calculateChangeForm">
<p><strong>1. To what extend does the change impact the organization?</strong></p>
<input id="q1a1" name="q1" type="radio" value="2"> <label for="q1a1">A specific department or a working group</label><br><input id="q1a2" name="q1" type="radio" value="6"> <label for="q1a2">One department </label><br><input id="q1a3" name="q1" type="radio" value="7"> <label for="q1a3">Several departments</label><br><input id="q1a4" name="q1" type="radio" value="8"> <label for="q1a4">Whole organization</label><br><input id="q1a5" name="q1" type="radio" value="8"> <label for="q1a5">Cross entities</label><br><input id="q1a6" name="q1" type="radio" value="9"> <label for="q1a6">Regional Impact</label><br><input id="q1a7" name="q1" type="radio" value="10"> <label for="q1a7">Group Impact</label><hr class="mb-5 mt-5">
<p><strong>2. How many employees are impacted? </strong></p>
<input id="q2a1" name="q2" type="radio" value="1"> <label for="q2a1"> < 10 </label><br><input id="q2a2" name="q2" type="radio" value="4"> <label for="q2a2">10 - 50 </label><br><input id="q2a3" name="q2" type="radio" value="7"> <label for="q2a3">51 - 100</label><br><input id="q2a4" name="q2" type="radio" value="8"> <label for="q2a4">101 - 200</label><br><input id="q2a5" name="q2" type="radio" value="9"> <label for="q2a5">201 - 500</label><br><input id="q2a6" name="q2" type="radio" value="10"> <label for="q2a6"> > 500 </label><br><br><button id="calculateChangeButton" class="button">Submit</button>
<script> document.getElementById("calculateChangeButton").onclick = function() {calculateChange();}; </script>
</form><hr class="mb-5 mt-5"></div>
<p>Your score is: <span id="changeScore"></span></p>
<script>
var changescore = 0;
function calculateChange(){
var val1 = 0;
for( i = 0; i < document.calculateChangeForm.q1.length; i++ ){
if( document.calculateChangeForm.q1[i].checked == true ){
val1 = document.calculateChangeForm.q1[i].value;
alert("The value of Question 1 answer is: " + val1);
}
}
var val2 = 0;
for( i = 0; i < document.calculateChangeForm.q2.length; i++ ){
if( document.calculateChangeForm.q2[i].checked == true ){
val2 = document.calculateChangeForm.q2[i].value;
alert("The value of Question 2 answer is: " + val2);
}
}
var changescore = parseInt(val1) + parseInt(val2);
alert("The total score: " + changescore);
document.getElementById("changeScore").innerHTML = changescore;
}
</script>
</body>
Thank you,
After input from user t348575, it was clear that the button should be changed to a an input type="button" in order to stop the form from being submitted:
I am trying to make a Js to search & filter items in JSON
so I use many radio in the "form" , the result will be [X,X,X,X,X,X]
I will set 50tags x 3(choose), I can feel my function will be large.
What ways can I change my function to be simpler?
function myFunction() {
var elements1 = document.getElementsByName("chair"),
elements2 = document.getElementsByName("car"),
elements3 = document.getElementsByName("house"),
elements4 = document.getElementsByName("tree"),
elements5 = document.getElementsByName("flower"),
elements6 = document.getElementsByName("grass");
var i;
for (var a = "", i = elements1.length; i--;) {
if (elements1[i].checked) {
var a = elements1[i].value;
break;
}
};
for (var b = "", i = elements2.length; i--;) {
if (elements2[i].checked) {
var b = elements2[i].value;
break;
}
};
for (var c = "", i = elements3.length; i--;) {
if (elements3[i].checked) {
var c = elements3[i].value;
break;
}
};
for (var d = "", i = elements4.length; i--;) {
if (elements4[i].checked) {
var d = elements4[i].value;
break;
}
};
for (var e = "", i = elements5.length; i--;) {
if (elements5[i].checked) {
var e = elements5[i].value;
break;
}
};
for (var f = "", i = elements6.length; i--;) {
if (elements6[i].checked) {
var f = elements6[i].value;
break;
}
};
var o2 = document.getElementById("output2");
o2.value = "[" + a + "," + b + "," + c + "," + d + "," + e + "," + f + "]";
o2.innerHTML = o2.value;
}
<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
<input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
<input type="radio" id="chair-1" name="chair" class="chair" value="-1">
<input type="radio" id="car1" name="car" class="car" value="1">
<input type="radio" id="car0" name="car" class="car" value="0" checked>
<input type="radio" id="car-1" name="car" class="car" value="-1">
<input type="radio" id="house1" name="house" class="house" value="1">
<input type="radio" id="house0" name="house" class="house" value="0" checked>
<input type="radio" id="house-1" name="house" class="house" value="-1">
<input type="radio" id="tree1" name="tree" class="tree" value="1">
<input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
<input type="radio" id="tree-1" name="tree" class="tree" value="-1">
<input type="radio" id="flower1" name="flower" class="flower" value="1">
<input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
<input type="radio" id="flower-1" name="flower" class="flower" value="-1">
<input type="radio" id="grass1" name="grass" class="grass" value="1">
<input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
<input type="radio" id="grass-1" name="grass" class="grass" value="-1">
<div> <input type="button" value="Search" id="filter" onclick="myFunction()" /> </div>
</form>
<div id="output2"></div>
Give the form an id, and you can refer to it as an object.
function myFunction() {
var form = document.getElementById("myForm");
var parts = [
form.chair.value,
form.car.value,
form.house.value,
form.tree.value,
form.flower.value,
form.grass.value
];
var o2 = document.getElementById("output2");
o2.innerHTML = '[' + parts.join(',') + ']';
}
And this is an even simpler solution using a FormData object. It supports an arbitrary number of named form fields without having to actually name them in the function:
function myFunction() {
var myForm = document.getElementById('myForm');
var formData = new FormData(myForm);
var parts = Array.from(formData.values());
var o2 = document.getElementById("output2");
o2.innerHTML = '[' + parts.join(',') + ']';
}
Use document.querySelector() to directly select the value of the checked radio button based on element names.
function myFunction() {
var chair = document.querySelector('input[name="chair"]:checked').value;
var car = document.querySelector('input[name="car"]:checked').value;
var house = document.querySelector('input[name="house"]:checked').value;
var tree = document.querySelector('input[name="tree"]:checked').value;
var flower = document.querySelector('input[name="flower"]:checked').value;
var grass = document.querySelector('input[name="grass"]:checked').value;
var o2 = document.getElementById("output2");
o2.value = "[" + chair + "," + car + "," + house + "," + tree + "," + flower + "," + grass + "]";
o2.innerHTML = o2.value;
}
Use arrays!
function myFunction() {
var elem_ids = [ "chair", "car", "house", "tree", "flower", "grass"];
var elems = elem_ids.map(id => document.getElementById(id));
var elems_check_values = elems.map(el => {
// el is kind of an array so
for(var i = 0; i < el.length; ++i)
if(el[i].checked)
return el[i].value;
return undefined;
}).filter(value => value == undefined) // to filter undefined values;
var output = "[" + elems_check_values.join(",") + "]";
var o2 = document.getElementById("output2");
o2.innerHTML = output
}
Your issue can be generalized to: how can I aggregate values for all fields in a given form?
The solution is a function that can be merely as long as 5 lines, and work for any amount of inputs with any type. The DOM model for <form> elements provides named keys (eg, myform.inputName) which each have a value property. For radio buttons, eg myform.tree.value will automatically provide the value of the selected radio button.
With this knowledge, you can create a function with a simple signature that takes a form HTMLElement, and an array of field names for the values that you need, like below: (hit the search button for results, and feel free to change the radio buttons).
function getFormValues(form, fields) {
var result = [];
for (var i = 0; i < fields.length; i++) {
result.push(form[fields[i]].value);
}
return result;
}
document.getElementById('filter').addEventListener('click', function(e) {
var o2 = document.getElementById("output2");
o2.innerHTML = getFormValues(document.forms[0], ['chair','car','house','tree','flower','grass']);
});
<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
<input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
<input type="radio" id="chair-1" name="chair" class="chair" value="-1">
<input type="radio" id="car1" name="car" class="car" value="1">
<input type="radio" id="car0" name="car" class="car" value="0" checked>
<input type="radio" id="car-1" name="car" class="car" value="-1">
<input type="radio" id="house1" name="house" class="house" value="1">
<input type="radio" id="house0" name="house" class="house" value="0" checked>
<input type="radio" id="house-1" name="house" class="house" value="-1">
<input type="radio" id="tree1" name="tree" class="tree" value="1">
<input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
<input type="radio" id="tree-1" name="tree" class="tree" value="-1">
<input type="radio" id="flower1" name="flower" class="flower" value="1">
<input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
<input type="radio" id="flower-1" name="flower" class="flower" value="-1">
<input type="radio" id="grass1" name="grass" class="grass" value="1">
<input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
<input type="radio" id="grass-1" name="grass" class="grass" value="-1">
<div> <input type="button" value="Search" id="filter"/> </div>
</form>
<div id="output2"></div>
The thing you need to do is break the code up into reusable chunks. So make a method to get the value. That will reduce a lot of code. After than, you should look at a way to reduce how many elements you need to list. Finally, find an easy way to fetch all the values.
So below is code that does this. It uses a helper method to get the elements, find the value. Than it uses an array to know what element groups to look for. And finally it uses map to iterate over the list so you do not have to code multiple function calls.
function getSelected (radioBtnGroup) {
// get the elements for the radio button group
var elms = document.getElementsByName(radioBtnGroup)
// loop over them
for(var i=0; i<elms.length; i++) {
// if checked, return value and exit loop
if (elms[i].checked) {
return elms[i].value
}
}
// if nothing is selected, return undefined
return undefined
}
// list the groups you want to get the values for
var groups = ['rb1', 'rb2', 'rb3', 'rb4']
// call when you want to get the values
function getValues () {
// use map to get the values of the rabio button groups.
// map passes the index value as the first argument.
// code is map(function(k){return getSelected(k)})
var results = groups.map(getSelected)
//displat the results
console.log(results);
}
document.querySelector('#btn').addEventListener('click', getValues);
<form>
<fieldset>
<legend>Item 1</legend>
<label><input type="radio" name="rb1" value="1-1"> One</label>
<label><input type="radio" name="rb1" value="1-2"> Two</label>
<label><input type="radio" name="rb1" value="1-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 2</legend>
<label><input type="radio" name="rb2" value="2-1"> One</label>
<label><input type="radio" name="rb2" value="2-2"> Two</label>
<label><input type="radio" name="rb2" value="2-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 3</legend>
<label><input type="radio" name="rb3" value="3-1"> One</label>
<label><input type="radio" name="rb3" value="3-2"> Two</label>
<label><input type="radio" name="rb3" value="3-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 4</legend>
<label><input type="radio" name="rb4" value="4-1"> One</label>
<label><input type="radio" name="rb4" value="4-2"> Two</label>
<label><input type="radio" name="rb4" value="4-3"> Three</label>
</fieldset>
<button type="button" id="btn">Get Results</button>
</form>
Personally I would not store the values in an array, I would use an object with key value pairs.
var results = groups.reduce(function (obj, name) {
obj[name] = getSelected(name)
return obj
}, {});
I am making a website page that is a survey of sorts. I have one section mostly working but I can't get the second half. I used the same code as the first section and expanded. I can't get it to work though. I don't understand why it won't write the score when I hit submit. When I press submit it should write over "this is the answer" and should calculate the number of points from the value of the questions so for example, if they press the first radio button for each question it should print 2.
This is the base JavaScript I used in case it helps.
function answer(total) {
var score = 0;
if (document.getElementById('exp_no').checked) {
score++;
}
if (document.getElementById('chg_no').checked) {
score++;
}
if (document.getElementById('sus_no').checked) {
score++;
}
document.getElementById('totalScore').innerHTML = score;
}
This is the JavaScript I am using.
function answer2(total) {
var score2 = 0;
if (document.getElementById('arr_1').checked) {
score2++;
}
else if (document.getElementById('arr_2').checked) {
score2 + 2;
}
else if (document.getElementById('arr_3').checked) {
score2 + 3;
}
else if (document.getElementById('arr_4').checked) {
score2 + 4;
}
else (document.getElementById('arr_5').checked) {
score2 + 5;
}
if (document.getElementById('been1').checked) {
score2++;
}
else if (document.getElementById('been2').checked) {
score2 + 2;
}
else if (document.getElementById('been3').checked) {
score2 + 3;
}
else if (document.getElementById('been4').checked) {
score2 + 4;
}
else if (document.getElementById('been5').checked) {
score2 + 5;
}
if (score2 == 2) {
document.getElementById('finalScore').innerHTML = score2;
} else if (score2 == 4){
document.getElementById('finalScore').innerHTML = score2;
} else if (score2 == 4){
document.getElementById('finalScore').innerHTML = score2;
} else if (score2 == 6){
document.getElementById('finalScore').innerHTML = score2;
} else if (score2 == 8){
document.getElementById('finalScore').innerHTML = score2;
} else if (score2 == 10){
document.getElementById('finalScore').innerHTML = score2;
}
}
This is my HTML
<button onclick = "toggletab()" id="tabButton"><h3>first results</h3>
</button>
<form>
<div id="first" >
<fieldset>
<label>
<legend>Is your arrest record a:</legend>
<input id="arr_1" type="radio" name="field4" value="1"
onclick="getscores4(this)"/>
IC 35-38-9-1
</label>
<label>
<input id="arr_2" type="radio" name="field4" value="2"
onclick="getscores4(this)"/>
IC 35-38-9-2
</label>
<label>
<input id="arr_3" type="radio" name="field4" value="3"
onclick="getscores4(this)"/>
IC 35-38-9-3
</label>
<label>
<input id="arr_4" type="radio" name="field4" value="4"
onclick="getscores4(this)"/>
IC 35-38-9-4
</label>
<label>
<input id="arr_5" type="radio" name="field4" value="5"
onclick="getscores4(this)"/>
IC 35-38-9-5
</label>
</fieldset>
<fieldset>
<label>
<legend>Has it been:</legend>
<input id="been1" type="radio" name="field5" value="1"
onclick="getscores5(this)"/>
1 Year From Date of Arrestor earlier if the Prosecutor
agrees
</label>
<label>
<input id="been2" type="radio" name="field5" value="2"
onclick="getscores5(this)"/>
5 Years From Date of Arrestor earlier if the Prosecutor
agrees
</label>
<label>
<input id="been3" type="radio" name="field5" value="3"
onclick="getscores5(this)"/>
8 YearsFrom Date of Arrestor earlier if the Prosecutor
agrees
</label>
<label>
<input id="been4" type="radio" name="field5" value="4"
onclick="getscores5(this)"/>
8/3 Years The Later of 8 Years from Date of Conviction
or 3 years from completion of the sentence or earlier if the Prosecutor
agrees
</label>
<label>
<input id="been5" type="radio" name="field5" value="5"
onclick="getscores5(this)"/>
10/5 Years The Later of 10 Years from Date of
Conviction or 5 years from completion of the sentence or earlier if the
Prosecutor agrees
</label>
</fieldset>
</div>
<fieldset id="submitbutton" class="article">
<input type="button" id="submit" value="submit" onclick='answer2()' />
<p id="finalScore">this is answer </p>
</fieldset>
</form>
</div>
</div>
<script src="backtest.js"></script>
<script src="backtest2.js"></script>
<script src="toggle.js"></script>
In function answer2(total) you have declared variable with name 'score2' but in all your logic you are using variable with name 'score'. Change score to score2 then it will work. And I also think that there is no need for argument 'total' in answer2() function because you are not using it anywhere.
I am trying to make a dog race.
Basically what I want is to check what radio the user checked,
compare it to a random number between 1 - 5 and see if he won.
My question is... How do I compare them?
This is my code so far.
function chooser(){
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
document.getElementById("winner").innerHTML = rand;
if(pick == rand)
{document.getElementById("winner").innerHTML =("win!");}
else {
document.getElementById("winner").innerHTML =("loose");
}
}
HTML:
<form id="pick" action="rand">
<input type="radio" name="dog" id="dog1">Dog1<br>
<input type="radio" name="dog" id="dog2">Dog2<br>
<input type="radio" name="dog" id="dog3">Dog3<br>
<input type="radio" name="dog" id="dog4">Dog4<br>
<input type="radio" name="dog" id="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" value="Gamble" onclick="chooser();">
<br>
<p id="winner"> </p>
A jQuery and Native JavaScript Approach. Take your pick.
$("#submitjq").click(function() {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = $("input[type=radio][name='dog']:checked").val();
if(pick == rand)
{
$("#winner").html("jQuery: Won!");
}
else {
$("#winner").html("jQuery: Lost!");
}
});
document.getElementById('submitjs').onclick = function () {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = document.pick.dog.value;
console.log(pick);
if(pick == rand)
{
document.getElementById("winner").innerHTML = "JavaScript: Won!" ;
}
else {
document.getElementById("winner").innerHTML = "JavaScript: Lost!" ;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="pick" name="pick" action="rand">
<input type="radio" name="dog" value="dog1">Dog1<br>
<input type="radio" name="dog" value="dog2">Dog2<br>
<input type="radio" name="dog" value="dog3">Dog3<br>
<input type="radio" name="dog" value="dog4">Dog4<br>
<input type="radio" name="dog" value="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" id="submitjs" value="Gamble Native JavaScript" />
<input type="submit" id="submitjq" value="Gamble jQuery" />
<br>
<p id="winner"> </p>
You need to give each radio button a value, and then getElementsByName, iterating through to find the one that's checked. See similar thread...