Radio Button failed sometimes to get value - javascript

$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="frm">
<label>True</label>
<input type="radio" id="rbOwner" value="1" name="IsOccupant" required="" />
<label>False</label>
<input type="radio" id="rbOccupant" value="2" name="IsOccupant" required="" />
</form>
<button id="btn">Click Me</button>
I am wondering why sometime my code upon publish failed to determine the checkbox value(Checked checkbox). But when I manually debug it it returns the correct value. Does anyone knows the reason for this?.

Wrap your code inside
$(document).ready(function(){
// Your code goes here
$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
})
This will ensure your JavaScript executes only when the document is fully loaded.

To take the values from an input tag kind is necessary to use the .value function instead of .val
Is something similar to this:
<!DOCTYPE html>
<html>
<head>
<title>
Get value of selected
radio button
</title>
</head>
<body>
<p>
Select a radio button and click on Submit.
</p>
Gender:
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>
<script>
function displayRadioValue() {
var ele = document.getElementsByName('gender');
for(i = 0; i < ele.length; i++) {
if(ele[i].checked)
document.getElementById("result").innerHTML
= "Gender: "+ele[i].value;
}
}
</script>
</body>
</html>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>

Related

I am unable to disable a input field

I am trying to disable a input field of return date when the travel type is one way. when I checked the radio button for one way the return date is still enabled. Please help me what i am missing here.
Thanks in advance.
<label>
<input type="radio" name="travel_type"value=""class="with-gap"
id="one_way">
<span style="color:white;">One Way</span>
</label>
<label>
<input type="radio"name="travel_type"value=""class="with-gap"id="round_trip">
<span style="color: white;">Round Trip</span>
</label>
var button = document.getElementById('one_way');
if (document.getElementById('one_way').checked) {
document.getElementById('datepicker1').disabled = true;
}
Try this. It should must work! Use jQuery click event instead of Javascript
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" class="form-control" id="datepicker1" />
<label>
<input type="radio" name="travel_type" value="1"class="with-gap travel_type"
id="one_way">
<span style="color:red;">One Way</span>
</label>
<label>
<input type="radio" name="travel_type" value="2"class="with-gap travel_type"id="round_trip">
<span style="color: red;">Round Trip</span>
</label>
</body>
</html>
<script>
$(".travel_type").click(function(){
if($(this).val() == 1)
{
$("#datepicker1").prop('disabled', true);
}else{
$("#datepicker1").prop('disabled', false);
}
});
</script>
If you will use jQuery , it will be easy. I created this example using Jquery. Hope this will help you.
$("input[name='travel_type']").click(function(){
if($(this).is(':checked') && $(this).val()=='1'){
$('#datepicker1').attr('disabled','disabled');
}else{
$('#datepicker1').removeAttr('disabled');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> One Way
<input type="radio" name="travel_type" value="1" class="with-gap" ></label>
<label>Round Trip
<input type="radio" name="travel_type" value="2" class="with-gap" ></label>
<p><label>Date Picker <input type="date" name="datepicker" id="datepicker1"></label></p>
You have to bind events to radio buttons, Here is your working code,
var button = document.getElementById('one_way');
var button2 = document.getElementById('round_trip');
button.addEventListener('change', function() {
if (document.getElementById('one_way').checked) {
document.getElementById('datepicker1').disabled = true;
}
})
button2.addEventListener('change', function() {
if (!document.getElementById('one_way').checked) {
document.getElementById('datepicker1').disabled = false;
}
})
You can also check it on JSFiddle Code
I think you forgot to call the "function" when radio button clicked.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<label>
<input type="radio" name="travel_type"value=""class="with-gap"
id="one_way" onclick="functionRadioChecked();">
<span style="color:red;">One Way</span>
</label>
<label>
<input type="radio"name="travel_type"value=""class="with-gap"id="round_trip">
<span style="color: red;">Round Trip</span>
</label>
<br><br><br>
<input type="date" id="datepicker1">
<script>
function functionRadioChecked() {
var button = document.getElementById('one_way');
if (document.getElementById('one_way').checked) {
document.getElementById('datepicker1').disabled = true;
}
}
</script>
</body>
</html>
Try out this code block where with self executing function on document load
<html>
<label>
<input type="radio" name="travel_type"value=""class="with-gap"
id="one_way">
<span style="color:black;">One Way</span>
</label>
<label>
<input type="radio"name="travel_type"value=""class="with-gap"id="round_trip">
<span style="color: black;">Round Trip</span>
</label>
<script>
(function() {
var button1 = document.getElementById('one_way');
button1.onclick = function()
{
document.getElementById('datepicker1').disabled = true;
}
var button2 = document.getElementById('round_trip');
button2.onclick = function()
{
document.getElementById('datepicker1').disabled = false;
}
})();
</script>
</html>
You could also assign a separate function to the radio button onclick
But depending your submitted code I would recommend the above code
Good Luck

How to access the value of a radio button

I am trying to access the value of a radio button using HTML and Javascript to make a simple quiz but it does not seem to be working. Here is my code:
function check() {
var a = document.getElementById("test").value
if (a === "one") {
alert("Correct!")
} else {
alert("Wrong!")
}
}
<h1><center>Simple Quiz</center></h1>
<br>
1) What is 1 + 1?
<br>
<form>
<input type="radio" name="one" id="test" value="one">1<br>
<input type="radio" name="one" id="test" value="two">2<br>
<input type="radio" name="one" id="test" value="three">3<br>
<button onclick="check()">Check</button>
</form>
It always says "Correct!" even when it is not. Does anyone know how to fix this?
Some points you are missing:
An id must be unique on the whole page
To check if a radio button is checked, use its checked attribute
function check() {
var two = document.getElementById("two");
if (two.checked) {
alert("Correct!")
} else {
alert("Wrong!")
}
}
<h1>
<center>Simple Quiz</center>
</h1>
<br> 1) What is 1 + 1?
<br>
<form>
<input type="radio" name="one" id="one" value="one">1<br>
<input type="radio" name="one" id="two" value="two">2<br>
<input type="radio" name="one" id="three" value="three">3<br>
<button onclick="check()">Check</button>
</form>
First, you cannot have the same id on multiple elements. Make to give your elements a unique id and if you need to give them all the same style you could use class instead.
Instead of checking the value of the radio button, you should check whether the radio button is checked.
Take a look at the example below.
function check() {
if (document.getElementById('test2').checked) {
alert('correct');
} else {
alert('wrong');
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
</head>
<body>
<h1><center>Simple Quiz</center></h1>
<br>
1) What is 1 + 1?
<br>
<form>
<input type="radio" name="one" id="test1" value="one">1<br>
<input type="radio" name="one" id="test2" value="two">2<br>
<input type="radio" name="one" id="test3" value="three">3<br>
<button onclick="check()">Check</button>
</form>
</body>
</html>
you should not define more than one element with the same id that's a bad practice, you could improve your code function check() {
for (elemnt of document.getElementByClassName('test') ) { if (element.checked ) alert('correct');
else alert ("incrrect");}}
Them in the html you can do this
<input type="radio" class="test" value="1">
<input type="radio" class="test" value="2">
<input type="radio" class="test" value="3">

How to display a div when 3 Radiobuttons from 3 questions checked?

I am trying to display 2 different div when the user answer 3 questions.
All questions have Yes and No answers which is shown by radio buttons.
I want to show div2 when 3 NO are given by the users. If ONLY ONE of the answers is Yes then the div1 must be shown.
this is the code:
<script type="text/javascript">
function display(e){
if(e.value == "yes"){
document.getElementById("hidediv1").style.display='block';
document.getElementById("hidediv2").style.display='none';
}
else if(e.value =="no"){
document.getElementById("hidediv2").style.display='block';
document.getElementById("hidediv1").style.display='none';
}
}
</script>
<form id="stu01" action="#" method="post">
<p>1. Q1?<br>
<input type="radio" name="sq01" value="yes" onclick="display(this)">Yes
<input type="radio" name="sq01" value="no" onclick="display(this)">No
</p>
<p>2. Q2?<br>
<input type="radio" name="sq02" value="yes" onclick="display(this)">Yes
<input type="radio" name="sq02" value="no" onclick="display(this)">No
</p>
<p>3. Q3?<br>
<input type="radio" name="sq03" value="yes" onclick="display(this)">Yes
<input type="radio" name="sq03" value="no" onclick="display(this)">No
</p>
<div id="hidediv1" style="display:none">
</div>
<div id="hidediv2" style="display:none">
</div>
</form>
I hope that i understand ur request right..
JSFIDDLE DEMO
$('input[type="radio"]').click(function () {
var checkedNo = $('input[type="radio"]').filter(function () {
return $(this).is(":checked") && $(this).val() === "no";
});
if (checkedNo.length === 3) {
$('#hidediv1').show();
$('#hidediv2').hide();
} else {
$('#hidediv2').show();
$('#hidediv1').hide();
}
});
Full version:
<!DOCTYPE html>
<html>
<head>
<title>Form Radio Button</title>
</head>
<body>
<form id="stu01" action="#" method="post">
<p>1. Q1?<br>
<input type="radio" name="sq01" value="yes">Yes
<input type="radio" name="sq01" value="no">No
</p>
<p>2. Q2?<br>
<input type="radio" name="sq02" value="yes">Yes
<input type="radio" name="sq02" value="no">No
</p>
<p>3. Q3?<br>
<input type="radio" name="sq03" value="yes">Yes
<input type="radio" name="sq03" value="no">No
</p>
<div id="hidediv1" style="display:none">
No!
</div>
<div id="hidediv2" style="display:none">
Yes!
</div>
</form>
<script src="http://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b‌​8=" crossorigin="anonymous"></script>
<script type="text/javascript">
$('input[type="radio"]').click(function () {
var checkedNo = $('input[type="radio"]').filter(function () {
return $(this).is(":checked") && $(this).val() === "no";
});
if (checkedNo.length === 3) {
$('#hidediv1').show();
$('#hidediv2').hide();
} else {
$('#hidediv2').show();
$('#hidediv1').hide();
}
});
</script>
</body>
</html>
Use onChange event listener, update a variable status, check when it is 3, append your div

Function that hides a label depending on radio button

I'm trying to get a function working that hides a label in the form depending on the radio button option selected. Here's my code so far.
HTML
<form action="">
<input type="radio" id="test" value="first"> first<br>
<input type="radio" id="test" value="second"> second<br>
<input type="radio" id="test" value="third"> third
</form>
<label class="hidden">Hide this</label>
Javascript
var rbtn = document.getElementById("test");
var x = document.getElementsByClassName("hidden");
function hidelabel() {
if (rbtn == 'third') {
x.style.display='none';
}
}
You must fire your hide function after radio button clicked like this:
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
if (radVal == 'third') {
document.getElementsByClassName("hidden")[0].style.display = 'none';
}
}
ps: document.getElementsByClassName returns an array. So you cannot use x.style.display='none';.
Working example: https://jsfiddle.net/5ts0dak4/
First name the radio button ID's with something decent:
<form action="">
<input type="radio" id="first" value="first"> first<br>
<input type="radio" id="second" value="second"> second<br>
<input type="radio" id="third" onclick="hide();" value="third"> third
</form>
<label class="hidden" id="hidden">Hide this</label>
Then try this:
function hide(){
var x = document.getElementById('hidden');
if(document.getElementById('third').checked) {
x.style.display='none';
}
}
You can test it here https://jsfiddle.net/o54mzrk5/
Try this one.
CSS:
<style type="text/css">
.hidden{ display:none; }
</style>
HTML:
<form action="">
<input type="radio" name="test" value="first" onclick="func(this, true);"> first<br>
<input type="radio" name="test" value="second" onclick="func(this, true);"> second<br>
<input type="radio" name="test" value="third" onclick="func(this, false);"> third
</form>
<label class="hidden">Hide this</label>
Script:
<script type="text/javascript">
func = function(ctrl, visible) {
if(visible)
document.getElementsByClassName("hidden")[0].style.display='block';
else
document.getElementsByClassName("hidden")[0].style.display='none';
};
</script>

How to compare user input with attribute values in JavaScript?

I have a code like this and I want to compare in a loop the attribute values of name with user entered input stored in variable "user". How can I do this?
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
See this answer for an example of how to loop through radio buttons in native javascript, quoted here for convenience:
<html>
<head>
<script>
var userChoice;
var setUserChoice = function(event) {
event.preventDefault();
var choices = event.target.userChoice;
for (var i =0; i < choices.length; i++) {
if (choices[i].checked) {
userChoice = choices[i].value;
}
}
event.target.choice.value = userChoice;
}
window.onload = function() {
var form = document.getElementById('userInput');
form.addEventListener('submit', setUserChoice, false);
};
</script>
</head>
<body>
<form id="userInput">
<input type="radio" name="userChoice" id="userChoice_rock" value="rock">Rock</input> </br>
<input type="radio" name="userChoice" id="userChoice_paper" value="paper">Paper</input> </br>
<input type="radio" name="userChoice" id="userChoice_scissors"value="scissors">Scissors</input> </br>
<input type="radio" name="userChoice" id="userChoice_lizard" value="lizard">Lizard</input> </br>
<input type="radio" name="userChoice" id="userChoice_spock" value="spock">Spock</input> </br>
<input type="submit" value="Enter" /></br>
<output name="choice"></output>
</form>
</body>
</html>
You can compare tha values like in this fiddle: http://jsfiddle.net/5wd8p/
HTML
<form action="demo.html" id="myForm">
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
<input type="submit" value="Submit">
</form>
JQuery
$(function () {
// Handler for .ready() called.
var user = "three"; //default value: depends on youur code..
//Loop through each radio element of the DOM
$("input[type=radio]").each(function(){
//Compare values of the "name" attribute and the user var
if (user == $(this).attr("name")){
alert("Same: " + $(this).attr("name"));
}else{
alert("Different: " + $(this).attr("name"));
}
});
});
try this:
document.getElementsByName(user)[0]

Categories

Resources