html form - getting value from selected radio button - javascript

I have created a form and I am looking to get the data the user entered. The javascript I have, so far pulls in all the data. I am having an issue with pulling the data of the selected radio button. I read some articles and they say the 'name' needs to be the sames but this doesn't work and if I give it unique 'ID's then selecting one or the other radio buttons doesn't work. Also I can't use jQuery
js
var myNodeList = document.getElementsByName('cf');
var myArray = []; // empty Array
for (var i = 0; i < myNodeList.length; i++) {
if(i<4)
for ( i; i < 3; i++) {
var self = myNodeList[i].value;
myArray.push(self);
}
else if(i==4)
myArray.push(document.getElementById('status').value);
else if(i==5)
myArray.push(document.getElementById('subscribe').value);
else if(i==6)
myArray.push(document.getElementsByName('support')[i]);
else if(i==7)
for ( i; i < myNodeList.length; i++) {
var self = myNodeList[i].value;
myArray.push(self);
}
}
console.log(myArray)
html
<!DOCTYPE html>
<html>
<head>
<title>Contact Me</title>
<link rel="stylesheet" type="text/css" href="contactform_Lab8.css">
</head>
<body>
<form id="contactus">
<fieldset>
<label for="name">Name:</label>
<input id="name" type="text" name="cf" autofocus required>
<label for="email">Email:</label>
<input id="email" type="email" name="cf" required>
<label for="phone">Phone:</label>
<input id="phone" type="tel" name="cf" required>
<label for="status">Status:
<select id="status" name="cf" required>
<option value="client">Client</option>
<option value="partner">Partner</option>
<option value="vendor">Vendor</option>
</select>
</label>
<label for="subscribe">
<input id="subscribe" type="checkbox" name="cf" value="check" checked>
Send me your newsletter</label>
<label for="sales">
<label for="support">
<input id="sales" type="radio" name="slsSupport" value="sales" checked>Sales
<input id="support" type="radio" name="slsSupport" value="support">Support
</label>
</label>
<label for="msg">Message:</label>
<textarea id="msg" name="cf" rows="10" cols="30" required></textarea>
</fieldset>
<fieldset>
<button type="submit">Send</button>
<button type="reset">Reset</button>
</fieldset>
</form>
<script src="contactform_Lab8.js"></script>
</body>
</html>

ID names are unique and should not be used twice in the same page. You can get the value from only checked radio buttons like this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'radio') {
if (inputs[i].checked){
alert('Checked radio buttons value is:' + inputs[i].value);
}
}
}

In Jquery
$("input[name=slsSupport]:checked").val();
In plain js you would want to find all the radio buttons, give each radio button an Id then select them one by one:
function GetSelected() {
for(var i=0;i<2;i++) {
var element = document.getElementById('radio'+i);
if (element.checked === true)
return element
}
}

An ID must be unique in all the HTML document. To group inputs (radio for exemple) you have to give them the same name (not ID).
To find the value with JQuery look this question and for pure JS solution look this other question.

Related

Display required fields on click with Javascript

I'm trying to display required fields on click with javascript. I have large form and inside of that form I have some required fields. Idea is to have button so that user can click (like toggle) and see only required fields?
So far my approach is something like this:
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {} else document.getElementById('ifYes').remove();
}
<button onclick="javascript:yesnoCheck();" id="yesCheck">Click</button>
<div id="ifYes">
<input type="text" name="usrname" required>
</div>
<div>
<input type="text" name="company" required>
</div>
What is the best way to this?
In case you really want to toggle the optional fields, you could just hide all optional elements in form (like in this example).
Keep in mind that yu may want to change the css selector to have more control what elements you want to hide.
eg:
form input:not([required]),
form select:not([required]),
form textarea:not([required]), ....
You may also want to not just hiden those fields but style them differently (opacity or something like that).
function toggleOptionalFields() {
document.querySelectorAll('form > :not([required])').forEach(field => field.hidden = !field.hidden);
}
<form>
<input required value="i am required" />
<input />
<select required>
<option value="1">required! :)</option>
</select>
<input />
<input />
<input required value="i am required too" />
</form>
<button onclick="toggleOptionalFields()">Toggle optional fields</button>
Also this function will not in IE because querySelectorAll().forEach and the arrow function are not supportet.
You could easily change that by using a regular function instead of the arrow-function and iterate differenttly thru the elementlist (eg, for(;;) or [].forEach.call(document.querySelectorAll(), function(element) {...});, ...).
Show and hide optional fields using button click
function toggleOptional(event){
var button = event.currentTarget;
var action = button.getAttribute('data-action');
//var optionalFields = document.querySelectorAll("form input:not([required])");
var optionalFields = document.querySelectorAll("form :not([required])");
if(action == "hide"){
optionalFields.forEach(function(value){
value.style.display = "none";
});
button.setAttribute('data-action','show');
button.innerText = "Show Optional ";
} else {
optionalFields.forEach(function(value){
value.style.display = "inline-block";
});
button.setAttribute('data-action','hide');
button.innerText = "Hide Optional";
}
}
input,textarea,select {
width : 70vw;
}
<button onclick="toggleOptional(event)" data-action="hide" >Hide Optional</button>
<form>
<input type="text" name="usrname" placeholder="usrname" required>
<input type="text" name="phone" placeholder="phone" required >
<input type="text" name="company" placeholder="company" >
<select name="birthyear" required >
<option value="">Select Year of Birth</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
</select>
<textarea required name="description" placeholder="description" ></textarea>
</form>
If you want to do it in javascript then here is a simple solution
Javascript
function yesnoCheck() {
var x = document.getElementById("ifYes");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
CSS
#ifYes{
display: block;
}
You can take a boolean variable and toggle its value and show or hide your elements based on it.
var toggleIfYes=false;
function yesnoCheck() {
toggleIfYes=!toggleIfYes
if (toggleIfYes) {
//show the elements
} else{
//hide the elements
}
}
<button onclick="javascript:yesnoCheck();" id="yesCheck">Click</button>
<div id="ifYes">
<input type="text" name="usrname" required>
</div>
<div>
<input type="text" name="company" required>
</div>
You could wrap all fields in the container like <div> or <form>
HTML
<div class="container">
<input required />
<input />
<input required />
</div>
then your toggle button function should toggle a class in the container
Javascript
function yesnoCheck() {
let container = document.querySelector('.container')
container.classList.toggle('only-required')
}
now you can use CSS to hide the non-required field if the container has a class only-required
CSS
.container.only-required input:not([required]) {
display: none;
}
You're using document.getElementById('ifYes').remove() which removes the element from the DOM. This way you won't be able to recover your element when you click the toggle button again. Also, you're verifying a <button/> element as if it were an <input type="checkbox" /> so you might want to use a checkbox instead.
You'd be better off using document.getElementById('ifYes').style.display = 'none' as it fits best in this situation:
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'none';
}
else {
document.getElementById('ifYes').style.display = '';
}
}
<input type="checkbox" onclick="javascript:yesnoCheck();" id="yesCheck">Click</input>
<div id="ifYes">
<input type="text" name="usrname" required>
</div>
<div>
<input type="text" name="company" required>
</div>

Getting value from radio button with Javascript

I am trying to check if the radio button is checked or not, and also I am trying to get the value but I do not know why it does not work. I saw a lot of post, video on internet and also some on this site, but nothing. So helpless I am posting this on the site.
This is my HTML file
function getValue(){
var checkAge = false;
for(var i=0; i<4; i++){
if(document.getElementById("age"+i).checked){
checkAge = true;
}
}
}
function loadFunctions() {
getValue();
}
window.onload = loadFunctions;
<!DOCTYPE html>
<html>
<head>
<title>Tutorial</title>
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<form id="form">
<section id="age_question">
<h2>How old are you?</h2>
<label for="age-one">1-25</label>
<input type="radio" name="ageRange" id="age1" value="0"/>
<label for="age-two">26-40</label>
<input type="radio" name="ageRange" id="age2" value="5" />
<label for="age-three">41-60</label>
<input type="radio" name="ageRange" id="age3" value="8" />
<label for="age-four">60+</label>
<input type="radio" name="ageRange" id="age4" value="10" />
</section>
<section id="bmi">
<h2>What is your BMI?</h2>
<label for="bmi-level"><span>0-25</span></label>
<input type="radio" name="bmi_range" id="" value="0"/>
<label for="bmi-level"><span>26-30</span></label>
<input type="radio" name="bmi_range" id="" value="0" />
<label for="bmi-level"><span>31-35</span></label>
<input type="radio" name="bmi_range" id="" value="9" />
<label for="bmi-level"><span>35+</span></label>
<input type="radio" name="bmi_range" id="" value="10" />
</section>
<section id="family_history">
<h2>Does anybody in your family have Diabetes?</h2>
<label for="history"><span>No</span></label>
<input type="radio" name="f_history" id="history" value="0"/>
<label for="history"><span>Grandparent</span></label>
<input type="radio" name="f_history" id="history" value="7" />
<label for="history"><span>Sibling</span></label>
<input type="radio" name="f_history" id="history" value="15" />
<label for="history"><span>Parent</span></label>
<input type="radio" name="f_history" id="history" value="15" />
</section>
<section id="diet">
<h2>How would you describe your diet?</h2>
<label for="diet"><span>Low sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="0"/>
<label for="diet"><span>Normal sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="0" />
<label for="diet"><span>Quite high sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="7" />
<label for="diet"><span>High sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="10" />
</section>
<button onclick="getValue()">Get You BMI</button>
<p id="message"></p>
</form>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
The first thing I'll suggest you do is to clear your browser cache, or launch the dev tools using F12 and check "Disable cache" on the "Network" tab.
Edit: Changed the button type, and made checkAge global.
Okay, the button does submit the form, making all changes to the variable lost after reload. To fix that, change the button type to just button, as:
<button type="button" onclick="getValue()">Get You BMI</button>
That way, it won't reload everytime you press the button. Another thing to do is make the checkAge variable global. that way is defined as false by default.
The "age"+i thing you did was starting the iteration with i=0, therefore giving the elementId as age0. This was making the element null.
To fix that, you can change the for-loop to for(var i=1; i<=4; i++) or using the same loop you've defined, but adding i by 1 before using it.
And the code would be like so:
var checkAge = false;
function getValue(){
for(var i=0; i<4; i++){
var index = i + 1
var element = document.getElementById("age"+index)
if(element.checked){
checkAge = true;
alert("The value is"+element.value)
}
}
}
Thanks.
Make the starting index be 1 instead of 0, since your ID selectors start from 1:
function getValue() {
var checkAge = false
for (var i = 1; i <= 4; i++) {
if (document.getElementById('age' + i).checked) {
checkAge = true
}
}
console.log(checkAge)
return checkAge
}
JSFiddle Demo: https://jsfiddle.net/a3fzd2kv/2/
You don't need to check the checked value of each of the radio buttons.
Here is a simpler solution:
var form = document.getElementById('form');
var ageRange = form.ageRange.value;
The value will equal to an empty string ('') when nothing is checked. Therefore, the logic for checkAge could be simplified to:
var checkAge = ageRange !== '';
your for loop is looping through i from 0 - 3, so your document.getElementById("age"+i) will look for id="age0", "age1", "age2, "age3".
Change your 'for' loop to for(var i=1; i<5; i++)

I have two radio button but the the form only can get one radio value even we choose different radio

I want to get the value from radio button that we have choose then multiple with the number in grossSalary. The result will be display on a textbox called epf. There are an error happening, the form only get 0.09 value even we choose 11% radio button.
Here is my javascript
<script>
function get(percent)
{
var percent = document.getElementById('percent').value;
var grossSalary= document.getElementById('grossSalary').value;
var epf = parseFloat(percent)*parseFloat(grossSalary);
epf = epf.toFixed(2);
document.getElementById('epf').value = epf;
}
</script>
Here is my form coding:
<div class="form-group">
<label>Gross Salary</label>
<input type="text" class="form-control" id="grossSalary" name="gross_salary">
</div>
<div class="form-group">
<label>EPF</label>
<input type="radio" id="percent" name="percent" value="0.09" onclick="get(this.value)">9%
<input type="radio" id="percent" name="percent" value="0.11" onclick="get(this.value)">11%
<input type="text" id ="epf" class="form-control" name="epf" >
</div>
</form>
You could use the name instead of the id (because id has to be unique). Also, with jQuery, you could use the change event.
i.e. :
HTML :
<div class="form-group">
<label>Gross Salary</label>
<input type="text" class="form-control" id="grossSalary" name="gross_salary">
</div>
<div class="form-group">
<label>EPF</label>
<input type="radio" name="percent" value="0.09">9%
<input type="radio" name="percent" value="0.11">11%
<input type="text" id ="epf" class="form-control" name="epf" >
</div>
JS :
$("input[name=percent]").change(function() {
var percent = $(this).val();
var grossSalary= $("#grossSalary").val();
var epf = parseFloat(percent)*parseFloat(grossSalary);
$("#epf").val(epf.toFixed(2));
});
Here is the working example on JSFiddle.
Hope it helps.
EDIT Don't forget to include jQuery source in your html file :
One file template :
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div class="form-group">
<label>Gross Salary</label>
<input type="text" class="form-control" id="grossSalary" name="gross_salary">
</div>
<div class="form-group">
<label>EPF</label>
<input type="radio" name="percent" value="0.09">9%
<input type="radio" name="percent" value="0.11">11%
<input type="text" id ="epf" class="form-control" name="epf" >
</div>
<script>
$("input[name=percent]").change(function() {
var percent = $(this).val();
var grossSalary= $("#grossSalary").val();
var epf = parseFloat(percent)*parseFloat(grossSalary);
$("#epf").val(epf.toFixed(2));
});
</script>
When you are using JS or Jquery than always remember one key point that:
id: used for single selection
class: used for multiple selection
In your case you are using same id for different tags, in that case it returns the first matching html value.
So to get rid of this, you have to use class and iterate over them and get the values.

Validating Checkboxes in javascript

Hi am new to Javascript and don't know how to validate my check-boxes I have looked up many examples but still don't understand it can someone please tell me how to validate it and also my drop down menu inst validating at all any help in advance will be appreciated.
My Java Script and HTML
function validateForm(){
var fname, lname, sex, address, email, length, songs, a, i, check, error;
a=0;
check=false;
error=false;
fname=document.getElementById("firstname").value;
lname=document.getElementById("lastname").value;
sex=document.getElementsByName("sex");
address=document.getElementById("address").value;
email=document.getElementById("email").value;
length=document.getElementById("len").value;
// songs=document.getElementByName("f_song");
if(fname=="" || fname==null){
alert("please input a first name");
error=true;
return false;
}
if(lname=="" || lname==null){
alert("please input your last name");
error=true;
return false;
}
for(i=0; i<sex.length; i++){
if(sex.item(i).checked==false){
a++;
}
}
if(a==sex.length){
alert("Please select Male or Female");
error=true;
return false;
}
if(address=="" || address==null){
alert("Please input your address thanks");
error=true;
return false;
}
if(email=="" || email==null){
alert("Please enter a email address");
error=true;
return false;
}
if(length=="" || length==null){
alert("Be select how long have you been a fan");
error=true;
return false;
}
alert("Am working ");
}
MY HTML
<head>
<title>] </title>
<link rel="stylesheet" type="Text/css" href="wit_frm.css"/>
<script type="text/javascript" src="java.js">
</script>
</head>
<body>
<div id="container">
<div id="header">
</div>
<div id="topnav">
<div id="link">
Home
Fan Site
Register
</div>
</div>
<div id="contentarea">
<form method="post" action="" onsubmit= "return validateForm();">
<fieldset>
<legend>Personal Information</legend>
First Name:<input type="text" name="fname" id="firstname"/>
<br/>
<br/> Last Name:<input type="text" name="lname" id="lastname"/>
<br/>
<br/> Sex: <input type="radio" name="sex" id="m"/>Male <input type="radio" name="sex" id="f"/>Female
<br/>
<br/>Address: <textarea id="address" name="add" rows="4" cols="30"></textarea>
</fieldset>
<fieldset>
<legend> User Information</legend>
<br/>Email: <input type="text" name="e_address" id="email"/>
<br/>
<br/>No of years listening to her music: <select name="n_years" id="len">
<option value="less than a yr"> less than 1yr</option>
<option value="2-5 years">2-5 years</option>
<option value="5+ years">5+ years</option>
</select>
<br/>
<br/>Favorite Songs:I will always love you<input type="checkbox" name="f_song" value="I will always love you"/> I look to you<input type="checkbox" name="f_song" value="I look to you"/></p>
<br/> I have nothing<input type="checkbox" name="f_song" value="I have nothing"/> One moment in time<input type="checkbox" name="f_song" value="one moment in time"/></p>
<br/> I wanna dance with somebody<input type="checkbox" name="f_song" value="I wanna dance with somebody"/> Greatest Love of All<input type="checkbox" name="f_song" value="Greatest love of all"/></p>
</fieldset>
<br/><input type="submit" name="sub_button" value="SUBMIT"/> <input type="reset" name="res_button" value="CLEAR"/>
</form>
</div>
<div id="footerfix">
</div>
<div id="footer">
<div id="link_1">
Home
Fan Site
About Her
</div>
</div>
</div>
</body>
</html>
I would do it like this:
Bin example
var f_song = document.getElementsByName("f_song");
var oneSongSelected = 0;
//Loop through the checkbox elements, and tally the selected
for(var ss = 0; ss < f_song.length; ss++){
if(f_song[ss].checked){
oneSongSelected++;
}
}
//If none are selected, then alert your error, and return false
if(oneSongSelected === 0){
alert("Please select at least one song");
return false;
}
You could use jquery, but you can do something like this:
In your html code, you can use the first dropdown option "Select" and value "-1":
<select id="dropDown">
<option value="-1">Select</option>
</select>
CheckBox:
<input type="checkbox" name="checkbox" id="checkbox" />
DropDown JavaScript:
var aValue;
aValue = document.getElementById("dropDown").value;
if(aValue == "-1"){
return false;
}
CheckBox JavaScript:
var checkbox = document.getElementById('checkbox');
if(!checkbox.checked){
return false;
}
as you are new in JavaScript, I recommend that you to learn jQuery, it's easier and simpler than JavaScript. If you have checkboxes and you want to validate them, you can try this:
$('#checkbox').click(function(){
if (this.checked) {
}
});
Explanation of Code
$('#checkbox').click(function() => this line says "when the element with id of #checkbox is clicked, do the stuff inside this function." You will need to replace #checkbox with the id of your checkbox (example: #yourCheck) or its class (example: .yourClass).
if (this.checked) => this if statement checks to see if the element is checked or not. You should include your code for when the checkbox is checked inside of the brackets.
EDIT: Here is a JSFiddle example that I made.

Radio buttons selected go to URL

I am trying to use the value of the selected radio button to go to a specific URL. Currently the Javascript I am using to do so is choosing the first "id" of the inputs and not using the value of what is actually selected.
HTML
<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
<input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
<input type="submit" />
</form>
Javascript
<script type="text/javascript">
function changeActionURL() {
var forma = document.getElementById('myForm');
forma.action += "?action=add&actiondata0=" + document.getElementById('ns_license').value;
}
</script>
You have multiple ID's that are the same, which is bad! getElementById expects one result, and it gets one by taking the first element which has that ID (ignoring your other 2, as it should). Use the class attribute on similar elements.
<input type="radio" name="ns_license" class="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" class="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" class="ns_license" value="1026" />NeuroSolutions Student
And to get the checked element
var checkedElem = document.querySelector(".ns_license:checked");
And if querySelector is out of the question:
var elems = document.getElementsByClassName("ns_license"),
checkedIndex = 0;
for (var i = 0; i < elems.length; i++) {
if (elems[i].checked)
checkedIndex = i;
}
Your current checked element would be at elems[checkedIndex]
to change a a specific attribute of an element, you can use the
setAttribute()
function of javascript. that should make it work.
While querySelector will work for modern browsers it does not work for IE <=7
If you want you can traverse through the radios by name, then check if the value is checked. If it is then return that value. That is the use of the getRadioValue() function:
<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
<input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
<input type="submit" />
</form>
<script type="text/javascript">
function changeActionURL() {
var forma = document.getElementById('myForm');
forma.action += "?action=add&actiondata0=" + getRadioValue('ns_license');
}
function getRadioValue(name){
var rads = document.getElementsByName('ns_license');
for(var x=0; x<rads.length;x++){
if(rads[x].checked){
return rads[x].value;
}
}
}
</script>

Categories