Store input radio selections when submit is clicked - javascript

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.

Related

addEventListener: click just one element of a bunch of elements

I'm beginner and have trouble with something in JS that might be simple to solve.
I made a quiz based on a NetNinja Udemy course, and I want the submit button to be enabled just when the user clicks on any answer option, and not before, so that he/she can't send a totally empty quiz.
The quiz has 4 questions with 2 options each, and I found this way...
const input_a = document.getElementById("q1a");
const input_b = document.getElementById("q1b");
button.disabled = true;
input_a.addEventListener('click', () => {
button.disabled = false;
});
input_b.addEventListener('click', () => {
button.disabled = false;
});
...to enable the button when the user clicks on any of the two options of the first question (ids: q1a & q1b) Following this logic, there'd also be q2a, q2b, q3a, q3b, q4a & q4b..
As there is a way to include all the answers in one JS element, what should I do in the event function to say "when you click any of this 8 options, enable the button"? Because everything I tried only makes the function work if I click all the buttons, which is obviously impossible in a Quiz .
Thank you! :)
In the solution below, when any of the radio buttons is clicked, the submit button is activated.
let result = [false, false, false, false];
let submitButton = document.getElementById('submitButton');
/* Returns true if all tests have been completed. */
function isValid(){
for(let i = 0 ; i < result.length ; ++i)
if(result[i] != true)
return false;
return true;
}
/* If all tests are completed, the submit button is activated. */
function send(){
result[this.value] = true;
if(isValid()){
submitButton.disabled = false;
console.log("The form can be submitted!");
}
}
/* The send() method is called when the change event of <input> elements whose type is "radio" is fired. */
document.querySelectorAll('input[type="radio"]').forEach((element) => {
element.addEventListener("change", send);
});
<form action="#">
<input type="radio" id="html" name="test1" value="0">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="test1" value="0">
<label for="css">CSS</label><br><br>
<input type="radio" id="js" name="test2" value="1">
<label for="html">JavaScript</label><br>
<input type="radio" id="c#" name="test2" value="1">
<label for="css">C#</label><br><br>
<input type="radio" id="c" name="test3" value="2">
<label for="html">C</label><br>
<input type="radio" id="c++" name="test3" value="2">
<label for="css">C++</label><br><br>
<input type="radio" id="python" name="test4" value="3">
<label for="html">Python</label><br>
<input type="radio" id="ruby" name="test4" value="3">
<label for="css">Ruby</label><br><br>
<button id="submitButton" type="submit" disabled>Submit</button>
</form>

form action to toggle a function?

<form action="" method="get" >
<input type="radio" name="gender" id="male_sub">male<br>
<input type="radio" name="gender" id="female_sub">female<br>
<input type="submit" value="Let's Start!" id="start"><br>
<form>
I have the following radio form and when I hit submit, I would like it to toggle some function in my js script. However, if I do something like:
document.getElementById("start").addEventListener('click',function ()...
Nothing works. I think I need something for the action tag, but I can only find examples that link to other websites/pages, which isn't what I want. Is toggling a function possible to do using the forms?
Thanks!
You're on the right track:
document.getElementById("start").addEventListener('click', function(e) {
e.preventDefault();
console.log('start!!');
const selected = document.querySelector('input[name="gender"]:checked');
console.log('you selected: ' + (selected ? selected.nextSibling.textContent : 'null'));
// your code here
});
<form>
<input type="radio" name="gender" id="male_sub">male<br>
<input type="radio" name="gender" id="female_sub">female<br>
<input type="submit" value="Let's Start!" id="start"><br>
<form>
You don't need an action or a method attribute. Make sure to use e.preventDefault() to prevent the form from submitting (redirecting the page) if you want to handle the form's values yourself.
You can define the submit function on form tag using onsubmit, Also this solution is accurate if you have multiple form tags on the same page.
function submitForm(form, event) {
event.preventDefault();
var val;
var radios = form.elements['gender'];
// loop through list of radio buttons
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) { // radio checked?
val = radios[i].value; // if so, hold its value in val
alert(val);
break; // and break out of for loop
}
}
alert("nothing selected");
return false;
}
<form onsubmit="return submitForm(this,event)">
<label><input type="radio" name="gender" id="male_sub" value="male">male</label><br>
<label><input type="radio" name="gender" id="female_sub" value="female">female</label><br>
<input type="submit" value="Let's Start!" id="start"><br>
</form>

Changing onClick value through radio buttons

I am quite new to all this and wondering if someone can help with something. I have the code below which when the button is clicked is references a javascript file and populates a random english word. I am wanting to change it to add a radio button. The radio button will allow the user to select an english word or french word. How can I change my onClick command to use the value of the selected radio button?
<FORM NAME="Generator">
<INPUT TYPE=TEXT NAME="WordBox" id="wordbox"><BR>
<INPUT TYPE=BUTTON VALUE="Generate" onClick="English(document.WordForm);" id="button">
</FORM>
I guess that you've a function English that take the form as a only parameter, you don't have to change anything just add the radio and get the value from the form inside your function, like :
<FORM NAME="Generator">
<INPUT TYPE="TEXT" NAME="WordBox" id="wordbox">
<BR>
<INPUT TYPE="RADIO" NAME="language" value="ENGLISH">ENGLISH
<INPUT TYPE="RADIO" NAME="language" value="FRENCH">FRENCH
<BR>
<INPUT TYPE=BUTTON VALUE="Generate" onClick="English(document.WordForm);" id="button">
</FORM>
Then get the value :
function English(form){
var language = form.language.value;
}
Hope this helps.
I'm not sure if I fully understand what it is that you're trying to achieve, but is it something along the lines of what I've created in this fiddle?
https://jsfiddle.net/pq6eh1jk/5/
HTML:
<input id="word" type="text"/>
<input id="english" type="radio" name="language" checked="checked"> English
<input type="radio" name="language" value="english"> French
<input type="button" onclick="generateText()" value="Generate Text"/>
JS:
var englishWordBank = [ 'Animal', 'Bank', 'City' ];
var frenchWordBank = [ 'Avion', 'Bonjour', 'Chat' ];
var generateText = function() {
var wordInput = document.getElementById('word');
var randomIndex = Math.round(Math.random()*2); //Between 0-2
if (document.getElementById('english').checked)
wordInput.value = englishWordBank[randomIndex];
//French:
else
wordInput.value = frenchWordBank[randomIndex];
};

Serializing and deserializing a form with its current state

I have this form
<form id=my_form>
<input id=mt type=text><input id=mc type=checkbox><textarea id=mta />
</form>
I want to have a button somewhere else, that can serialize the form WITH its state, that is, if the textarea has a content, or the text has a content or the checkbox is pressed, I want that information to be stored somehow in the string. Later, I would like to restore the information in the form using that string.
I tried with .innerHTML and it didn't work, I always got the original HTML.
I also looked at the serialize method of jQuery, but I was not able to deserialize it "inside" the form.
Thank you in advance!
Kurt
I've made examples for you. Tested - working fine.
You need jQuery library
First here goes the form:
<form id="my_form">
<input id="formText" type="text" name="formText" />
<br />
<label><input id="formCheck" type="checkbox" name="formCheck" /> check 1</label>
<br />
<label><input id="formCheck2" type="checkbox" name="formCheck2" /> check 2</label>
<br />
<textarea name="formTextarea" id="formTextarea" cols="20" rows="3"></textarea>
<br />
<label><strong>Time unit</strong>:</label>
<p>
<label><input type="radio" name="dataView" value="week" checked="checked" /> Week</label>
<label><input type="radio" name="dataView" value="month" /> Month</label>
<label><input type="radio" name="dataView" value="year" /> Year</label>
</p>
<input type="button" value="Serialize" onclick="serializeForm()" />
<input type="button" value="Unserialize" onclick="restoreForm()" />
</form>
After clicking buttons, corresponding function are called in js
And here is the js:
Serialized data is stored in formData variable, and if needed you can store it in cookie, in database etc... And later load it, regarding your requirements
<script type="text/javascript">
var formData;
function serializeForm() {
formData = $('#my_form').serialize();
}
function restoreForm() {
var obj = unserializeFormData(formData);
// Restore items one by one
if(obj.hasOwnProperty('formTextarea')) {
$('#formTextarea').val(obj.formTextarea);
}
if(obj.hasOwnProperty('formText')) {
$('#formText').val(obj.formText);
}
// Radio buttons
if(obj.hasOwnProperty('dataView'))
$('input[value="'+obj.dataView+'"]').attr('checked', true);
// Restore all checkbox. You can also iterate all text fields and textareas together, because the have same principle for getting and setting values by jQuery
$('#my_form input[type="checkbox"]').each(function(){
var checkName = $(this).attr('name');
var isChecked = false;
if(obj.hasOwnProperty(checkName))
isChecked = true;
$(this).attr('checked',isChecked);
});
}
function unserializeFormData(data) {
var objs = [], temp;
var temps = data.split('&');
for(var i = 0; i < temps.length; i++){
temp = temps[i].split('=');
objs.push(temp[0]);
objs[temp[0]] = temp[1];
}
return objs;
}
</script>

Javascript adding values to radio buttons to input price

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.

Categories

Resources