Javascript adding values to radio buttons to input price - javascript

Im trying to create a javascript block inside of a webpage im working on. I havent done javascript since highschool and it doesnt seem to want to come back to me :(
In this block of code i want to have 4 sets of radio buttons, each time a selection is picked,
a price will be inputed to a variable for each radio group. i.e
var firstPrice = $25
var secondPrice = $56
var thirdPrice = $80
var fourthPrice = $90
then after each radio group has one selection there will be a function attached to the submit button that adds up each price to display the final amount inside of a hidden field
var totalPrice = (firstPrice + secondPrice + thirdPrice + fourthPrice)
My question is, how do i attach a number value to a radio button within a group, same name but id is different in each group. Then do i just create a function that adds all the price groups up and then set the submit button to onClick = totalPrice();
Here is an example of one set of radio buttons:
<label>
<input type="radio" name="model" value="radio" id="item_0" />
item 1</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_1" />
item2</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_2" />
item3</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_3" />
Item4</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_4" />
item5</label>
</form>
then my script looks something like:
function finalPrice90{
var selectionFirst = document.modelGroup.value;
var selectionSecond = document.secondGroup.value;
var selectionThird = document.thirdGroup.value;
var selectionFourth = document.fourthGroup.Value;
var totalPrice = (selectionFirst + selectionSecond + selectionThird + selectionFourth);
}

Try this fiddle
http://jsfiddle.net/tariqulazam/ZLQXB/

Set the value attribute of your radio inputs to the price each radio button should represent.
When it's time to calculate, simply loop through each group and get the value attribute if the checked radio.
Because the value attribute is a string representation of a number, you'll want to convert it back to a number before doing any math (but that's a simple parseInt or parseFloat).
Here's a working fiddle using pure JavaScript: http://jsfiddle.net/XxZwm/
A library like jQuery or Prototype (or MooTools, script.aculo.us, etc) may make this easier in the long run, depending on how much DOM manipulation code you don't want to re-invent a wheel for.

Your requirements seem pretty simple, here's an example that should answer most questions. There is a single click listener on the form so whenever there is a click on a form control, the price will be updated.
<script type="text/javascript">
//function updatePrice(el) {
function updatePrice(event) {
var el = event.target || event.srcElement;
var form = el.form;
if (!form) return;
var control, controls = form.elements;
var totalPrice = 0;
var radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if ((control.type == 'radio' || control.type == 'checkbox') && control.checked) {
totalPrice += Number(control.value);
}
// Deal with other types of controls if necessary
}
form.totalPrice.value = '$' + totalPrice;
}
</script>
<form>
<fieldset><legend>Model 1</legend>
<input type="radio" name="model1" value="25">$25<br>
<input type="radio" name="model1" value="35">$35<br>
<input type="radio" name="model1" value="45">$45<br>
<input type="radio" name="model1" value="55">$55<br>
</fieldset>
<fieldset><legend>Model 2</legend>
<input type="radio" name="model2" value="1">$1<br>
<input type="radio" name="model2" value="2">$2<br>
<input type="radio" name="model2" value="3">$3<br>
<input type="radio" name="model2" value="4">$4<br>
<fieldset><legend>Include shipping?</legend>
<span>$5</span><input type="checkbox" value="5" name="shipping"><br>
</fieldset>
<input name="totalPrice" readonly><br>
<input type="reset" value="Clear form">
</form>
You could put a single listener on the form for click events and update the price automatically, in that case you can get rid of the update button.

Related

Multiplying a text input by selected radio button

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>

Store input radio selections when submit is clicked

I need to store in my js file which radio option for each radio name was selected as well as store the Username that was entered. Here is my form
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input type="radio" name="class"/>Archer
<input type="radio" name="class"/>Mage
<input type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input type="radio" name="race"/>Orc
<input type="radio" name="race"/>Elf
<input type="radio" name="race"/>Human
<input type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
EDIT:
When I try to target the submit button for a click function it causes my page to reload instead of making the form fadeOut
var userInput;
var classInput;
var raceInput;
$('input[type=submit]').click(function(){
$('#newPlayer').fadeOut(500);
userInput = $('input[name="user"]').val();
classInput = $('input[name="class"]:checked').val();
raceInput = $('input[name="race"]:checked').val();
});
Maybe this helps. First, you will have to put values on those inputs
<form id="newPlayer">
Username:<br>
<input type="text" name="user"/><br>
Please Choose a Class: <br>
<input value="archer" type="radio" name="class"/>Archer
<input value="mage" type="radio" name="class"/>Mage
<input value="warrior" type="radio" name="class"/>Warrior
<br>
Please Choose a Race: <br>
<input value="orc" type="radio" name="race"/>Orc
<input value="elf" type="radio" name="race"/>Elf
<input value="human" type="radio" name="race"/>Human
<input value="worg" type="radio" name="race"/>Worg
<br>
<input type="submit" value="Submit">
</form>
Then, using jQuery, a simple .val() will do the job:
var class_val = $('input[name="class"]:checked').val();
var race = $('input[name="race"]:checked').val();
var user = $('input[name="user"]').val();
After that, you just need to put in localStorage
localStorage.setItem('class', class_val);
localStorage.setItem('race', race);
localStorage.setItem('user', user);
To access those values in the future, you do that
var stored_class = localStorage.getItem('class');
var stored_race = localStorage.getItem('race');
var stored_user = localStorage.getItem('user');
To make things happens on submit, you add an submit event to the form, like that:
$('form').on('submit', function() {
// Get values
var class_val = $('input[name="class"]:checked').val();
...
// Store values
localStorage.setItem('class', class_val);
...
// Avoid form submit
return false;
});
Hope it helps :)
I think I would use localStorage.
For example:
//Make sure to set the selection variable to a object that contains the selections made by the user.
function save() {
//This will save the current settings as an object to the localStorage.
localStorage.selections = JSON.stringify(selections) ;
}
function load() {
if (!localStorage.selections) {
alart("No saves found.") ;
return false ;
}
selections = JSON.parse(localStorage.selections) ;
}
Read more about localStorage here.

How to get the text of the checked radio button? [duplicate]

This question already has answers here:
How do I get the label of the selected radio button using javascript
(3 answers)
Closed 8 years ago.
I have a group of radio buttons and want to get the checked radio button, then alert the text, not only the value of it. To explain more, when the user clicks the first radio button, and then submits the form, I want the browser to alert "Desktop Case." And I want to achieve this without jQuery.
<form action="" name="form1">
<label for="radio400">Desktop Case</label>
<input type="radio" name="rad_case" value="400" id="radio400"/>
<label for="radio401">Mini Tower</label>
<input type="radio" name="rad_case" value="401" id="radio401"/>
<label for="radio402">Full Tower</label>
<input type="radio" name="rad_case" value="402" id="radio402"/>
<input type="button" value="Submit" name="btn_submit" onclick="update_order_onclick()"/>
</form>
The following works for your example. It uses CSS selectors to target the checked input. Based on its id, the appropriate label is found:
function update_order_onclick() {
var value= 'Nothing selected',
selected= document.querySelector('input[name="rad_case"]:checked'),
selection= document.querySelector('#selection');
if(selected) {
value= document.querySelector('label[for="'+selected.id+'"]').innerHTML;
}
selection.innerHTML= value;
}
<form action="" name="form1">
<label for="radio400">Desktop Case</label>
<input type="radio" name="rad_case" value="400" id="radio400"/>
<br>
<label for="radio401">Mini Tower</label>
<input type="radio" name="rad_case" value="401" id="radio401"/>
<br>
<label for="radio402">Full Tower</label>
<input type="radio" name="rad_case" value="402" id="radio402"/>
<br>
<input type="button" value="Submit" name="btn_submit" onclick="update_order_onclick()"/>
</form>
<div id="selection"></div>
First, we create a function to loop through the radio buttons group we have, and checks if it is checked or not.
function get_radio_val(form, name)
{
var val;
var radios = form.elements[name];
for (var i =0; i < radios.length; i++)
{
if (radios[i].checked)
{
val = radios[i];
break;
}
}
return val;
}
Then we write the function that will be executed on onclick event.
function update_order_onclick()
{
var val = get_radio_val(document.form1, 'rad_case');
var val_id = val.id;
var selector = 'label[for=' + val_id + ']';
var label = document.querySelector(selector);
var label_text = label.innerHTML;
alert(label_text);
}
The thing that helped us here, is that the label for attribute has to be the same value as the radio button id and that's how we selected it in the function above.
simply do the following:
var checked = document.querySelector('input:checked');
var id = checked?checked.id:'bla';
var lab = document.querySelector('label[for='+id+']');
var lab_text = lab?lab.textContent:'';

check all other radio button using one radio button

i am fetching roll numbers here which have two radio buttons in 'php'.there will be multiple number of roll numbers so i want to check all the radio buttons whose value are 'yes' at once using a particular radio button or check box.although i didn't write that button in this code as i don't know what to write.please give me a solution using java script.
while($row=mysqli_fetch_assoc($result))
{
echo"<tr><td>{$row['roll']}</td>
</td><td></td><td></td><td></td><td>
<td><input type='radio' name='present[$i]' value='Yes'>YES</td>
</td><td></td><td></td><td>
<td><input type='radio' name='present[$i]' value='No'>NO</td></tr>";
$i++;
}
This type of interaction should be using a Javascript implementation since it is a client-side operation.
HTML:
<form>
<input type="radio" name="radio1" value="yes"/>Yes
<input type="radio" name="radio1" value="no"/>No
<br />
<input type="radio" name="radio2" value="yes"/>Yes
<input type="radio" name="radio2" value="no"/>No
<br />
<input type="radio" name="radio3" value="yes"/>Yes
<input type="radio" name="radio3" value="no"/>No
<br />
<input type="button" value="Select All" onclick="selectAll('radio',true);"/>
<input type="button" value="Deselect All" onclick="selectAll('radio',false);"/>
</form>
Javascript:
function selectAll( prefix, set ) {
var form = document.forms[0], //Get the appropriate form
i = 0,
radio;
while( radio = form[prefix + ++i] ) //Loop through all named radio# elements
for( var j = 0; j < radio.length; j++ ) //Loop through each set of named radio buttons
if( radio[j].value == (set ? "yes" : "no") ) //Selector based on value of set
radio[j].checked = true; //Check that radio button!
}
JSFiddle

Enable/disable a form element after checking radio button checked states

I have ten or so questions with radio buttons. They all need to be set to true, before a user can move on to another level. If and only if these ten questions have be answered to true, I'd like to have one of the elements on the form be enabled for further editing. This, I can do on the server side, but don't know how to do it in JavaScript. Any help? Much appreciated. Thanks.
<div>
<label> First Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
<div>
<label> Second Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][researched]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][researched]" type="radio" value="false" />No</label>
</div>
<div>
<label> Third Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
This code extends to several more of questions.
I've been able to select radios by doing so:
var first_ten = $(':radio[name="project[person_attributes][is_complete_and_works]"][value=true], :radio[name="project[person_attributes][researched]"][value=true], etc…);
Now, I have no idea how to iterate over each and when I click on each radio, whether yes or no, I'd like to see the result for the element to be enabled. Any thoughts much appreciated.
Something like the following will do the job:
<script type="text/javascript">
function proceed(form) {
var el, els = form.getElementsByTagName('input');
var i = els.length;
while (i--) {
el = els[i];
if (el.type == 'checkbox' && !el.checked) {
form.proceedButton.disabled = true;
return;
}
}
form.proceedButton.disabled = false;
}
</script>
<form onclick="proceed(this);">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="submit" name="proceedButton" disabled>
</form>
Note that this is considered bad design as if javascript is not available or enabled, the user can never click the button. Better to deliver the form in a useful state and the, when submitted, use script to validate that the buttons are all checked and cancel the submit if they aren't.
Then at the server you can also check the state and only show the next page if the current one passes validation. If it doesn't, return the user to the first page.
That way neither you or the user care if the script works or not, the page still functions. Of course it might be a better experience if the script does work, but at least the choice isn't binary and it also gives you a simple fallback to support a very wide array of browsers with minimal effort.
So a better solution is:
<form onsubmit="reurn validate(this);" ...>
...
</form>
Then in the function:
function validate(form) {
// if validateion fails, show an appropriate message and return false,
// if it passes, return undefined or true.
}
And always validate at the server since you really have no idea what happened on the client.
Edit
Form controls don't need a name and ID, just use a name. In a radio button set, only one control can be checked, you can't check all of them.
It seems to me that what you are trying to do is to see if at least one radio button has been checked in each set. You can do that based on the code above and selecting each set as you encounter it, e.g.
function validateForm(form) {
// Get all the form controls
var control, controls = form.elements;
var radios = {};
var t, ts;
// Iterate over them
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
// If encounter a radio button in a set that hasn't been visited
if (control.type == 'radio' && !radios.hasOwnProperty(control.name)) {
ts = form[control.name];
radios[control.name] = false;
// Check the set to see if one is checked
for (var j=0, jLen=ts.length; j<jLen; j++) {
if (ts[j].checked) {
radios[control.name] = true;
}
}
}
}
// Return false if any set doesn't have a checked radio
for (var p in radios) {
if (radios.hasOwnProperty(p)) {
if (!radios[p]) {
alert('missing one');
return false;
}
}
}
}
</script>
<form onsubmit="return validateForm(this);">
<input type="radio" name="r0">
<input type="radio" name="r0">
<br>
<input type="radio" name="r1">
<input type="radio" name="r1">
<br>
<input type="reset"><input type="submit">
</form>
Note that your form should include a reset button, particularly when using radio buttons.

Categories

Resources