Reading in radio button selections in JS - javascript

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/

Related

enabling submit btn after filling form (all inputs) with javascript no jquery

I am trying to create a form that the submit btn is disabled untill all (except for one) of the fields are filled.
this is the html:
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>
this is the js:
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var filled = true;
for(var i = 0; i < txs.length; i++){
if(txs[i].value === "")
filled = false;
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value === "")
filled = false;
}
submitform.disabled = filled;
});
first, it takes a few seconds until the btn becomes disabled. secondly, after I fill any field the btn becomes enabled.
thank you!
Disregarding the comments and the radio buttons and focusing on the main issue, try changing the second half of the code to:
submitform.disabled = true;
contactForm.addEventListener('keyup', function() {
var ins = document.getElementsByTagName("INPUT");
filled = []
for (var j = 0; j < ins.length; j++) {
if (ins[j].value === "")
filled.push(false);
else {
filled.push(true)
}
}
if (filled.includes(false) === false) {
submitform.disabled = false
};
});
and see if it works.
The reason it becomes enabled when you input something is because you are setting
submitform.disabled = filled
At the start, filled is set to true which is why the button is disabled. However, once you type something in any input, you set filled to false which enables the button (submitform.disabled = false).
There's a lot of ways to go about this but here's one. It increments a counter when ever something is filled in. Then you check if that counter is the same as the amount of inputs and textareas.
Secondly, we set the button to be disabled at the very start so even if you remove text from an input, the button will be disabled again if it wasn't
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var amountFilled = 0
submitform.disabled = true
for(var i = 0; i < txs.length; i++){
if(txs[i].value !== "") {
amountFilled += 1
}
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value !== "") {
amountFilled += 1
}
}
if (amountFilled === ins.length + txs.length) {
submitform.disabled = false
}
});
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>

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>

Output from the radio button into JavaScript doesn't work

I am doing a simple online form to calculate BMR using Harris–Benedict equation with the imperial measurements. I don't know where the error is inside my code but right now only the Clear the form button works. I didn't post the entire HTML code for the webpage because it looks just like I want it and it's only the calculation that I am having the problem with.
<form>
<fieldset id="ImpCalcInfo">
<label for="ageinput">
Age
<input tabindex="1" type="text" id="ageinput" name="age" />
</label>
<label for="heightinput">
Height
<input tabindex="3" type="text" id="heightinput" name="heigh" />
</label>
<label for="weightinput">
Weight
<input tabindex="5" type="text" id="weightinput" name="weight" />
</label>
<label for="genderinput">
<input name="gender" tabindex="7" type="radio" id="maleinput" value="1" checked>Male
<input name="gender" tabindex="9" type="radio" id="femaleinput" value="0">Female
</label>
</fieldset>
<input tabindex="11" type="button" id="submit" value="Submit" />
<input tabindex="13" type="reset" value="Clear fields" />
</form>
function impCalc() {
var bmrIm = 0;
var ageIm = document.getElementById("ageinput").value;
var heightIm = document.getElementById("heightinput").value;
var weightIm = document.getElementById("weightinput").value;
var genderIm = document.getElementById("gender").value;
if (genderIm.value = "1") {
bmrIm = 66 + (6.2 * weightIm) + (12.7 * heightIm) - (6.76 * ageIm);
}
else {
bmrIm = 655 + (4.35 * weightIm) + (4.7 * heightIm) - (4.7 * ageIm);
}
(ageIm && heightIm && weightIm) ? alert("Your BMR is: " + bmrIm) : alert("Please fill in all fields");
}
document.getElementById("button").addEventListener("submit", impCalc, false);
The radio button were not working because you were taking them as an ID but the id does not exist in the input. You have get them via getElementsByName()[0]
Also you event listener did not know where button is clicked so the button id is is unique and it will listen to that click only when you click submit.
Here is working demo: https://jsfiddle.net/usmanmunir/tjsnaz4w/10/
function impCalc() {
var bmrIm = 0;
var ageIm = document.getElementById("ageinput").value;
var heightIm = document.getElementById("heightinput").value;
var weightIm = document.getElementById("weightinput").value;
var genderIm = document.getElementsByName("gender")[0].value
if (genderIm.value == "1") {
bmrIm = 66 + (6.2 * weightIm) + (12.7 * heightIm) - (6.76 * ageIm);
}
else {
bmrIm = 655 + (4.35 * weightIm) + (4.7 * heightIm) - (4.7 * ageIm);
}
(ageIm && heightIm && weightIm) ? alert("Your BMR is: " + bmrIm) : alert("Please fill in all fields");
}
var el = document.getElementById('submit');
el.addEventListener("click", impCalc, false);
HTML
<form>
<fieldset id="ImpCalcInfo">
<label for="ageinput">
Age
<input tabindex="1" type="text" id="ageinput" name="age" />
</label>
<label for="heightinput">
Height
<input tabindex="3" type="text" id="heightinput" name="heigh" />
</label>
<label for="weightinput">
Weight
<input tabindex="5" type="text" id="weightinput" name="weight" />
</label>
<label for="genderinput">
<input name="gender" tabindex="7" type="radio" id="gender" value="1" checked>Male
<input name="gender" tabindex="9" type="radio" id="gender" value="0">Female
</label>
</fieldset>
<input tabindex="11" type="button" id="submit" value="Submit" />
<input tabindex="13" type="reset" value="Clear fields" />
</form>
Hope this helps.

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

Categories