Pulling radio button values with Javascript - javascript

I have a form on my webpage that looks like this:
<form id="numberForm">
<input type="radio" name="number" value="singular"> singular <br>
<input type="radio" name="number" value="plural"> plural <br>
</form>
How do I pull the value of the currently selected radio button (without a submit action) in Javascript?
What I'd like is something along the lines of the following:
var formInput = document.getElementById("numberForm");
var numberInputValue = formInput.SELECTEDBUTTON.value;

Try this (using querySelector in JS) :
function getSel() {
var formInput = document.getElementById("numberForm");
var rb=formInput.querySelector('[type="radio"]:checked'); //get selected radio button
document.getElementById('spVl').innerHTML = 'Selected value = '+rb.value;
}
<form id="numberForm">
<input type="radio" name="number" value="singular"> singular <br>
<input type="radio" name="number" value="plural"> plural <br>
<input type="button" value="Get selected radio button value" onclick="getSel();" /><br>
<span id="spVl"></span>
</form>

var form = document.getElementById('numberForm');
var radios = form.getElementsByTagName('input');
for(var i = 0; i < radios.length; ++i) {
if(radios[i].checked) {
console.log("Radio button '" + radios[i].value + "' is checked");
}
}

Related

Radio button selection when building HTML form

I have a simple HTML form that is used for bookings. Once completed it submits the fields via e-mail which can then be automatically uploaded into my Access database with VBA.
The process works fine if there is just text in the form but I want to include radio button choices as well. The problem is that it doesn't include an indication as to which button has been chosen.
The body of the e-mail, if "text" was entered into the text box and choice2 was selected would be:
text
Choice1
Choice2
Choice3
What I would like it to be is:
text
Choice2.
Can this be done?
A simplified version of my code so far is:
function displayRadioValue() {
var ele = document.getElementsByName('Choice');
for (j = 0; j < ele.length; j++) {
if (ele[j].checked)
document.getElementById("result").innerHTML = ele[j].value;
}
}
function btnClick() {
var link = "mailto:username#domain.com" +
"&subject=" + escape("Radio button trial") +
"&body=" + escape(buildForm());
window.location.href = link;
}
function buildForm() {
var str = "";
var elem = document.getElementById('RBT').elements;
for (var i = 1; i < elem.length; i++) {
if (elem[i].type != "button") {
str += elem[i].value + "\r\n";
}
}
return str;
}
<body>
<form id="RBT" name="RBT">
<fieldset>
<p></p>
<legend>Complete the form and\or choose an option</legend><br>
<div>
<label for "text1">Text1</label><br>
<input id="text1" name="text1"><br>
<input type="radio" id="radio1" name="Choice" value="Choice1" checked onclick="displayRadioValue()">
<label for="radio1">Choice1</label><br>
<input type="radio" id="radio2" name="Choice" value="Choice2" onclick="displayRadioValue()">
<label for="radio2">Choice2</label><br>
<input type="radio" id="radio3" name="Choice" value="Choice3" onclick="displayRadioValue()">
<label for="radio3">Choice3</label><br>
<br></div>
<div id="result" name="result" value="result"></div>
</fieldset>
</form>
<BUTTON type=submit onclick="btnClick()" />
<FONT size=5 bold>Submit choice</FONT>
</BUTTON>
You need to check if the element is checked.
And since you're adding it in the same loop as the text field you also need to make sure the element that has to be checked is actually a radio button:
if(elem[i].type != "radio" || elem[i].checked) {
str += elem[i].value + "\r\n";
}
But: In your snippet everything is added to the TO field of the mail, is that intended?
function displayRadioValue() {
var ele = document.getElementsByName('Choice');
for (j = 0; j < ele.length; j++) {
if (ele[j].checked)
document.getElementById("result").innerHTML = ele[j].value;
}
}
function btnClick() {
var link = "mailto:username#domain.com" +
"&subject=" + escape("Radio button trial") +
"&body=" + escape(buildForm());
window.location.href = link;
}
function buildForm() {
var str = "";
var elem = document.getElementById('RBT').elements;
for (var i = 1; i < elem.length; i++) {
if (elem[i].type != "button") {
if(elem[i].type != "radio" || elem[i].checked) {
str += elem[i].value + "\r\n";
}
}
}
return str;
}
<html>
<head>
<title>Radio button trial</title>
</head>
<body>
<form id="RBT" name="RBT">
<fieldset>
<p></p>
<legend>Complete the form and\or choose an option</legend><br>
<div>
<label for "text1">Text1</label><br>
<input id="text1" name="text1"><br>
<input type="radio" id="radio1" name="Choice" value="Choice1" checked onclick="displayRadioValue()">
<label for="radio1">Choice1</label><br>
<input type="radio" id="radio2" name="Choice" value="Choice2" onclick="displayRadioValue()">
<label for="radio2">Choice2</label><br>
<input type="radio" id="radio3" name="Choice" value="Choice3" onclick="displayRadioValue()">
<label for="radio3">Choice3</label><br>
<br></div>
<div id="result" name="result" value="result"></div>
</fieldset>
</form>
<BUTTON type=submit onclick="btnClick()" />
<FONT size=5 bold>Submit choice</FONT>
</BUTTON>
</body>
</html>

Reading in radio button selections in JS

I am trying to get a popup window to display whatever was entered into the form. I have managed to get it display the Name that was entered into the form, but would also like it to display the rating given in the website (radio buttons) using only JavaScript and HTML.
<form>
<fieldset>
<legend><b>Details</b></legend>
<label>First Name </label><input id = "fname" type="text" autofocus="" placeholder="Enter first name" name = "fname"><br><br>
<label>Last Name </label><input type="text" placeholder="Enter last name"><br><br>
<label>Email </label><input type="email" placeholder="Enter valid email"> <button onclick="myFunction()">Help</button><br><br>
</fieldset>
<fieldset>
<legend><b>Rating</b></legend>
<label>Website Rating:</label>
<input type="radio" name="Rating" value="1">* (1 Star)
<input type="radio" name="Rating" value="2">* * (2 Star)
<input type="radio" name="Rating" value="3">* * * (3 Star)
<input type="radio" name="Rating" value="4">* * * * (4 Star)
<input type="radio" name="Rating" value="5">* * * * * (5 Star)<br>
</fieldset>
<fieldset>
<legend><b>Comments</b></legend>
<label>Comments on the website:</label>
<textarea name="feedback1" rows="8" cols="70"></textarea><br>
</fieldset>
<fieldset>
<legend><b>Updates</b></legend>
Do you want to receive updates via Email?<br>
<input type="checkbox" name="updateYes" value="Yes">Yes
<input type="checkbox" name="update" value="No" checked>No<br>
</fieldset>
<input type="reset" value="Reset">
<button onclick="myFunction2()" type = "submit">Submit</button>
</form>
<script>
function myFunction() {
alert("Please enter a valid Email adress into the 'Email' field");
}
function myFunction2() {
alert("Thank you for your feedback " + document.getElementById('fname').value + ", You have rated the website ");
}
</script>
</body>
</html>
You could use querySelector for this:
var value = document.querySelector('input[name=Rating]:checked').value;
alert("Thank you for your feedback " + value + ", You have rated the website ");
Example: http://jsfiddle.net/bvaughn/kaqqsrc1/
You could also use getElementsByName:
var value;
var radios = document.getElementsByName("Rating");
for(var i = 0; i < radios.length; i++) {
if(radios[i].checked) value = radios[i].value;
}
Example: http://jsfiddle.net/bvaughn/1qqqtafu/
Get the selected radiobutton by looping over them:
function myFunction2() {
var checkedRadioButton, inputs, rating;
inputs = document.getElementsByName("Rating");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checkedRadioButton = inputs[i];
break;
}
}
if (checkedRadioButton) {
rating = checkedRadioButton.value;
}
alert("Thank you for your feedback " + document.getElementById('fname').value + ", You have rated the website " + rating);
}
https://jsfiddle.net/d5jo235p/

How to Disable whole Div Contents without using JQuery

As I have Basic knowledge of JavaScript I want to do operation like following :
By using Two radio button giving two option for Payment :
By Cash
By Check
If user select the radio button of Cash the Cheque Button should also disable and the Div of Cheque in which the details like cheque no and bank name is should also disable.
And visa Versa
Is there a way to do that without using JQuery? (disable a div and get all content disabled also)
Thanks in Advance For Help.
Try this:
document.getElementById("myDivId").disabled = true;
To disable all elements inside the div, try this:
var allChildNodes = document.getElementById("myDivId").getElementsByTagName('*');
for(var i = 0; i < allChildNodes.length; i++)
{
allChildNodes[i].disabled = true;
}
This code will disable all elements within the given container.
var container = document.getElementById("cashContainer");
var inputs = document.getElementsByTagName("input").concat(document.getElementsByTagName("select"));
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
Applying the same code you can re-enable the other container.
You may try this
HTML
<input type="radio" name="cashcheck" value="cash" checked />Cash<br />
<div id="cash">
<form method="post">
<input type="text" name="cashTxt1" />
<input type="text" name="cashTxt2" />
</form>
</div>
<input type="radio" name="cashcheck" value="check" />Check<br />
<div id="check">
<form method="post">
<input type="text" name="checkTxt1" disabled />
<input type="text" name="checkTxt2" disabled />
</form>
</div>
JS
window.onload=function(){
var radios = document.getElementsByName('cashcheck');
radios[0].onchange=toggle;
radios[1].onchange=toggle;
};
function toggle()
{
if(this.checked)
{
var div = document.getElementById(this.value),
inputs = div.getElementsByTagName('form')[0].getElementsByTagName('*');
for( var i=0; i<inputs.length; i++)
{
inputs[i].removeAttribute('disabled');
}
var op = this.value == 'cash' ? 'check' : 'cash',
divOp = document.getElementById(op),
divOpInputs = divOp.getElementsByTagName('form')[0].getElementsByTagName('*');
for( var i=0; i<divOpInputs.length; i++)
{
divOpInputs[i].setAttribute('disabled');
}
}
}
DEMO.
<fieldset disabled="true">
<div>
<input type="text" />
</div>
<br>
<div>
<input type="text" />
</div>
<br>
<div>
<input type="text" />
</div>
<br>
</fieldset>

How to confirm a radio button selection with an alert box

So i have this code:
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n');
}
function formfocus() {
document.getElementById('textbox').focus();
}
window.onload = formfocus;
var option;
</script>
</head>
<body>
Your name:
<input type="text" name="FirstName" id="textbox" <br><br/>
Your Address:
<input type="text" name="address" id="location" <br></br><br></br>
Choose your location:
<form name="Radio" id="destination" action="">
Bristol:
<input type="radio" name="selection" value="bristol" onClick="option=0">
London:
<input type="radio" name="selection" value="london" onClick="option=1">
Birmingham:
<input type="radio" name="selection" value="birmingham" onClick="option=2" />
</form>
<br></br> Click:
<input type="button" value="Submit" onclick="showConfirmationDialog();" /><br></br>
</body>
</html>
... This code basically represents a form for a user to fill in and at the end select one of three option provided via the radio buttons. What I wanted to find out was that how do I get the selection from one radio button which the user will need to select, displayed within the alert box after they press submit.
Something like this...
function getSelRadioValue()
for(i = 0; i< document.forms['Radio'].elements['selection'].length ; i++){
if(document.forms['Radio'].elements['selection'][i].checked == true)
return document.forms['Radio'].elements['selection'][i].value;
}
return null;
}
var selectedRadioValue = getSelRadioValue(); //use this variable in your alert.
if(selectedRadioValue == null)
alert("please select a destination");
else if(confirm("You have selected " + selectedRadioValue))
//deal with success
You need to loop through the selection radios to get the checked value:
var selection = document.Radio.selection;
var selectionResult = "";
for(var i = 0; i < selection.length; i++) {
if(selection[i].checked) {
selectionResult = selection[i].value;
}
}
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n' + 'Location: '+selectionResult);

javascript ID selector

I have 2 forms
<form name= "form1" action="">
<input type="hidden" name="max" id= "max1" value="100"/>
<input type="submit" class="submit" value="part 1" />
</form>
<form name= "form2" action="">
<input type="hidden" name="max2" id= "max2" value="200"/>
<input type="submit" class="submit" value="part 2" />
</form>
I get the values from this form here
$(".submit").click(function () {
here --> var max_res = $("input#max1").val();
var Results = "Max Result " + max_res;
});
My question is how can i dynamically change the id from max1 to max2 so I can store max2's value in max-res when a click is made in form2
var max_res = $('input[id^="max"]', $(this).parent()).val();
//selects the id starting with max in this form
var Results = "Max Result " + max_res;
var i = 1;
var max_res = $("input#max"+i).val();
/edit: I would add common class to all inputs like class="max" and then:
var max_res = $(this).parent().find("input.max").val();
var max_res = $(this).closest("form").find("input:hidden").val()

Categories