Radio button selection when building HTML form - javascript

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>

Related

Output form within html page

I want to print the submitted input elements within the same page below the html form. The checked checkbox elements should all be printed. The image element can be avoided.
The function does not seem to be working.
function validateForm(myForm) {
var a = document.getElementById("fname").value;
document.getElementById("display").innerHTML = y;
var b = document.getElementByName("passwords").value;
document.getElementById("display1").innerHTML = y;
var c = document.getElementByName("gender");
var i;
for (i = 0; i < c.length; ++i) {
if (c[i].checked)
document.getElementById("display1").innerHTML = c[i].value; //looping through radio buttons
}
var d = document.getElementByName("hobbies");
for (i = 0; i < d.length; ++i) {
if (d[i] checked)
ans = ans + d[i].value; //looping through checkboxes and adding to display in display 2 id.
}
document.getElementById("display2").innerHTML = ans;
var e = document.getElementByName("cities").value;
document.getElementById("display3").innerHTML = e;
}
<form name="myForm">
<fieldset>
<legend>Personal Details</legend>
Name:
<input type="text" id="fname" <br>Password:
<input type="password" name="password" id="passwords" />
<br>Gender:
<input type="radio" name="gender" />Male
<input type="radio" name="gender" />Female</input>
<br>Hobbies:
<input type="radio" name="hobbies" value="Reading" />Reading
<input type="radio" name="hobbies" value="Writing" />Writing</input>
<br>City:
<select name="cities" />
<option>Surat</option>
<option>Ahmedabad</option>
<option>Rajkot</option>
<option>Vadodra</option>
</select>
<br>Image:
<input type="file" accept="image/*" value="image" style="margin:0px 10px 10px 100px; margin:absolute;" />
</form>
<br>
<input type="Submit" value="Submit" onSubmit="validateform(myForm);">
</fieldset>
<p id="display"></p>//display the values submitted within the html page
<p id="display1"></p>
<p id="display2"></p>
<p id="display3"></p>
getElementsByName - plural and when accessing the first, use [0] like
document.getElementsByName("cities")[0].value
missing a dot in d[i].checked
move the onSubmit="validateform(myForm);" to the form tag and do onSubmit="return validateForm(this);" and add return false;
validateForm misspelled in event handler (lower case f)
y missing
ans not defined
function validateForm(myForm) {
var a = document.getElementById("fname").value;
document.getElementById("display").innerHTML = a;
var b = document.getElementsByName("passwords").value;
document.getElementById("display1").innerHTML = a;
var c = document.getElementsByName("gender");
var i, ans;
for (i = 0; i < c.length; ++i) {
if (c[i].checked)
document.getElementById("display1").innerHTML = c[i].value; //looping through radio buttons
}
var d = document.getElementsByName("hobbies");
for (i = 0; i < d.length; ++i) {
if (d[i].checked)
ans = ans + d[i].value; //looping through checkboxes and adding to display in display 2 id.
}
document.getElementById("display2").innerHTML = ans;
var e = document.getElementsByName("cities")[0].value;
document.getElementById("display3").innerHTML = e;
return false; // normally when error but here to stay on page
}
<form name="myForm" onSubmit="return validateForm(this);">
<fieldset>
<legend>Personal Details</legend>
Name:
<input type="text" id="fname" <br>Password:
<input type="password" name="password" id="passwords" />
<br>Gender:
<input type="radio" name="gender" />Male
<input type="radio" name="gender" />Female</input>
<br>Hobbies:
<input type="radio" name="hobbies" value="Reading" />Reading
<input type="radio" name="hobbies" value="Writing" />Writing</input>
<br>City:
<select name="cities" />
<option>Surat</option>
<option>Ahmedabad</option>
<option>Rajkot</option>
<option>Vadodra</option>
</select>
<br>Image:
<input type="file" accept="image/*" value="image" style="margin:0px 10px 10px 100px; margin:absolute;" />
</form>
<br>
<input type="Submit" value="Submit">
</fieldset>
<p id="display"></p><!-- display the values submitted within the html page -->
<p id="display1"></p>
<p id="display2"></p>
<p id="display3"></p>

Pulling radio button values with 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");
}
}

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/

Sum dynamic values from input text and radio

I'm trying to sum the value of an input text changing dynamically with a radio that also changes dynamically. I'm doing something right but also something wrong because it doesn't sum when I want. The sum should show everytime the input text changes and not randomly disappear then you click a radio, just sum them.
the fiddle http://jsfiddle.net/7tFhx/
and the code
<form id="myForm" accept-charset="UTF-8">
<button type="button" class="btn-tt btn-primary btn-lg" disabled>1. Elige el color</button></br>
<label>
<input class="calc" id="fb1" type="radio" name="fb" value="10">
<img src="img/01.jpg"/>
</label>
<label>
<input class="calc" id="fb2" type="radio" name="fb" value="15">
<img src="img/02.jpg"/>
</label>
</br>
</br>
<button type="button" class="btn-tt btn-primary btn-lg" disabled>2. Elige las medidas</button></br>
<div class="row">
<div class="col-xs-2">
ancho (cm.)
<input id="ancho" type="text" class="form-control" placeholder="100">
</div>
<div class="col-xs-2">
alto (cm.)
<input id="alto" type="text" class="form-control" placeholder="100">
</div>
<div class="col-xs-2">
cantidad
<input id="cantidad" type="text" class="form-control" placeholder="1">
</div>
</div>
</br>
<button type="button" class="btn-tt btn-primary btn-lg" disabled>3. Posición mecanismo</button></br>
<label>
<input class="calc" id="fb3" type="radio" name="fb1" value="20">
<img src="img/01.jpg"/>
</label>
<label>
<input class="calc" id="fb4" type="radio" name="fb1" value="35">
<img src="img/02.jpg"/>
</label>
<div>
Total: <span id="price">0</span>€
</div>
</form>
js:
$(function(){
var mecanismoMedida = ['100','200'];
var mecanismoPrecio = ['50','80'];
$('#ancho').on('input',function(){
var j = 1, i = 0;
value = parseInt(($("#ancho").val() / 8) + 1);
for(i = 0; i < mecanismoMedida.length; i++){
if($("#ancho").val() >= mecanismoMedida[i] && $("#ancho").val() <
mecanismoMedida[j]){
value += mecanismoPrecio[i];
break;
} else {
j++;
}
}
$("#price").text(this.value + value);
});
$('#myForm input[type="radio"]').on('change', function () {
var sum = 0;
$("#myForm").find("input[type='radio']:checked").each(function () {
sum += parseInt(this.value);
});
$("#price").text(sum);
});
});
If it's a simple sum you're after, you can simply run an update code on the keyup and change events of all input elements:
$("input").change(function(){update();}).keyup(function(){update();});
To update them, first you need to check and see which one of the two radio buttons are checked and get its value:
function update(){
var p = 0;
for(var i = 0; i < $(".calc").val(); i++)
{
if($($(".calc")[i]).prop("checked") == true)
{
p += parseInt($($(".calc")[i]).val());
}
}
After that, simply parse the values of the textboxes to integers and add them to the value of the radio button. I created a custom function to do this, because if the boxes are empty, parsing them returns NaN:
p = parseInt(p);
p += parseInt(val2($("#ancho")));
p += parseInt(val2($("#alto")));
p += parseInt(val2($("#cantidad")));
p = parseInt(p);
$("#price").html(p);
}
function val2(elm){
if(isNaN(parseInt($(elm).val())))
return 0;
else
return parseInt($(elm).val());
}
JSFiddle

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);

Categories