how to check radio buttons with javascript - javascript

this is my code in html:
<input type="radio" name="sex" id="boy" value="male" /> Boy<p></p><br>
<input type="radio" name="sex" id="girl" value="female" />Girl
<button id="fine" type="button">Submit</button>
and this is in my javascript file:
var maskio = document.getElementById('boy');
var femmna = document.getElementById('girl');
function prima(){
var fine = document.getElementById('fine');
fine.onclick=chek;
}
function chek(){
if((maskio.checked == false) && (femmna.checked == false)) {
alert('lol');
return false;
}
}
window.onload=prima;
Where is the problem? When i run it and click Submit nothing happens. Why?

Change your JS as follows. The elements were not created by the time you were getting them.
function prima() {
var fine = document.getElementById('fine');
fine.onclick = chek;
}
function chek() {
var maskio = document.getElementById('boy');
var femmna = document.getElementById('girl');
if ((maskio.checked == false) && (femmna.checked == false)) {
alert('lol');
return false;
}
}
window.onload=prima;
Check here: jsFiddle

The issue is your html tags, there is a space "< " remove the space and it will work fine...
<input type="radio" name="sex" id="boy" value="male" /> Boy
<p></p><br>
<input type="radio" name="sex" id="girl" value="female" /> Girl
<button id="fine" type="button">Submit</button>
<script>
var maskio = document.getElementById('boy');
var femmna = document.getElementById('girl');
function prima()
{
var fine = document.getElementById('fine');
fine.onclick=chek;
}
function chek()
{
if(maskio.checked)
{
alert("You are male Eh?");
}
else if(femmna.checked)
{
alert("Femal ;)");
}
else if(!maskio.checked && !femmna.checked)
{
alert("Come on Please check something!");
}
}
window.onload=prima;
</script>

when radio-buttons have the same name, they belong to the group of the name. That means, only one radio-button in a group can be selected. If you check both, there won't be a result, anyway !

Related

Javascript background changer no working

I want to implement a background image changer in my code, but it doesn't seem to work.
Here is my JS:
function XAX() {
var P = document.getElementById("background1");
var O = document.getElementById("background2");
var I = document.getElementById("background3");
if {P.checked === true} {
document.body.style.backgroundImage = "url(Gates.jpg)";
}
else if {O.checked === true} {
document.body.style.backgroundImage = "url(City.jpg)";
}
else if {I.checked === true} {
document.body.style.backgroundImage = "url(forest.jpg)";
}
}
Here is the HTML:
<input type="radio" id="background1" name="background" >Gates of Argonath</input><br>
<input type="radio" id="background2" name="background" >Minas Tirith</input><br>
<input type="radio" id="background3" name="background" >Rivendell</input><br>
<input type="button" value="Submit" onclick="XAX()">
if {P.checked === true} {
//TODO
}
You should use this directly on if block because element.checked return the Boolean result and you should handle this directly on if block their is no need to check either element.checked=== true || element.checked === 1.
Here is my fiddle check this
https://jsfiddle.net/DeMaiz/tn6thygq/
Please find correct code below
<html>
<body>
<input type="radio" id="background1" name="background" >Gates of Argonath</input><br>
<input type="radio" id="background2" name="background" >Minas Tirith</input><br>
<input type="radio" id="background3" name="background" >Rivendell</input><br>
<input type="button" value="Submit" onclick="XAX()">
<body>
<script>
function XAX() {
var P = document.getElementById("background1");
var O = document.getElementById("background2");
var I = document.getElementById("background3");
if (P.checked == true) {
document.body.style.backgroundImage = "url(Gates.jpg)";
}
else if (O.checked == true) {
document.body.style.backgroundImage = "url(City.jpg)";
}
else if (I.checked == true) {
document.body.style.backgroundImage = "url(forest.jpg)";
}
}
</script>
</html>
you are using { after if and else if statement, you should use (

Enable/disable button based on accepting the 2 checkbox conditions

I have gone through the stackoverflow regarding enable/disable button conditionally and was able to find some help but NOT EXACT what I was looking for.
Instead of 1 checkbox condition, I have 2 checkbox conditions. So unless if the two checkboxes have been accepted, the button should not be enabled.
Following is my html:
<input type="checkbox" id="f_agree" value="1" onchange="checked(this, 'f_agree2')"/>
<input type="checkbox" id="f_agree2" value="1" onchange="checked('f_agree', this)"/>
<button type="submit" disabled="disabled" id="acceptbtn">Continue</button>
Following is javascript:
function checked(element1, element2) {
var myLayer = document.getElementById('acceptbtn');
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.disabled = "";
} else {
myLayer.class = "button:disabled";
myLayer.disabled = "disabled";
};
}
I have tried like above, but it is not working. I don't know where I am going wrong.
it won't work because you are not removing that attribute disabled.
function checked(element1, element2) {
var myLayer = document.getElementById('acceptbtn');
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled","disabled");
};
}
Update
use any other name then checked as it seems to be reserved and not working.
you also need to do getElementById for element1 and element2.
function checkedFunc(element1Id, element2Id) {
var myLayer = document.getElementById('acceptbtn');
var element1 = document.getElementById(element1Id);
var element2 = document.getElementById(element2Id);
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled","disabled");
};
}
<input type="checkbox" id="f_agree" value="1" onchange="checkedFunc('f_agree', 'f_agree2')"/>
<input type="checkbox" id="f_agree2" value="1" onchange="checkedFunc('f_agree','f_agree2')"/>
<input type="button" value="check" id="acceptbtn" />
You can try the following code
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled", "disabled");
};
With jQuery:
var btn;
var changed = function() {
//get the length of non checked boxes
var disbl = $('input[id^=f_agree]:not(:checked)').length;
btn.prop('disabled', disbl);//disable if true, else enable
};
$(function() {
btn = $('#acceptbtn');
$('input[id^=f_agree]').on('change', changed).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" id="f_agree" value="1" />1
<input type="checkbox" id="f_agree2" value="1" />2
<input type="button" id="acceptbtn" value="Submit" />
The problem is that there is a difference between the string "f_agree" and the node with id="f_agree".
Your code should work as expected with
checked(this, document.getObjectById('f_agree2'))
Much better would be however to avoid having a widget knowing about the other... I'd implement instead by adding a list of external rules that check all widgets:
function okSubmit() {
return (document.getElementById("f_agree").checked &&
document.getElementById("f_agree2").checked);
}
This is much easier to read/maintain and also scales better in case you need to add more conditions later. In the onchange of all the widgets just call a function that will enable/disable the submit button depending on the conditions.
Try this
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled", "disabled");
};
Try the below code -
var chk1 = document.getElementById('chk1');
chk1.addEventListener('click', checked, false);
var chk2 = document.getElementById('chk2');
chk2.addEventListener('click', checked, false);
function checked(){
if(chk1.checked && chk2.checked) {
document.getElementById('btn').removeAttribute('disabled');
} else {
document.getElementById('btn').setAttribute('disabled','disabled');
}
}
<input type="checkbox" id="chk1" />
<input type="checkbox" id="chk2" />
<button id="btn" disabled >Button<button>
I tested it and it's working! Hope it helps u...

Jquery radio:checked is not working as expected

I am learning jquery. I have made a simple html file with minor validations in jquery , but they are not behaving properly. The issue is:
If Enter name first and then select the checkbox, everything seems to be working fine .
But if I select gender first and then enter name , it keeps alerting me to select gender.
Is there an issue with the way which the code has been implemented?
<script src="jquery.js"></script>
<script>
$(document).ready(function () {
$("#Name").focus();
$("#target").submit(function () {
var fn = $("#Name").val();
if (fn == "" && fn.length == 0) {
alert('Name is mandatory');
$("#Name").focus();
return false;
}
var status = false;
$("#gender").each(function () {
if ($(this).is(":radio:checked")) {
status = true;
}
});
if (!status) {
alert("Select Gender");
$("#gender").focus();
return false;
}
return true;
});
});
</script>
<form id='target' action='MyResult.html'>
First Name:
<input type='text' name='Name' id='Name' />
<br/>Gender:
<input type='radio' name='gender' id='gender' value='male' />Male
<input type='radio' name='gender' id='gender' value='female' />Female
<br/>
<input type='submit' value='Registration' />
</form>
IDs must be unique. You can use Attribute value selector in combination with :checked to filter out whether radio button is checked or not.
var status = $(":radio[name=gender]:checked").length > 0;
instead
var status = false;
$("#gender").each(function () {
if ($(this).is(":radio:checked")) {
status = true;
}
});
DEMO

validatin script for radio button not Working

I am getting errors. The script is not working. Help
thanks in advance.
I want to check if all my set of radio buttons are checked when button next is click.
other ways of doing this also are welcome
<div class="qheader">
9) What's the world's most widely spoken language?</div>
<div class="qselections">
<input type="radio" value="a" name="question9">a) English<br>
<input type="radio" value="b" name="question9">b) Spanish<br>
<input type="radio" value="c" name="question9">c) Mandarin<br>
<input type="radio" value="d" name="question9">d) French<br>
</div><br>
<div class="qheader">
10) Which continent is host to the most countries in the world?</div>
<div class="qselections">
<input type="radio" value="a" name="question10">a) Asia<br>
<input type="radio" value="b" name="question10">b) Africa<br>
<input type="radio" value="c" name="question10">c) Europe<br>
</div>
</div>
<input type="button" value="Next" name="B3" onclick="showdesc()">
<script>
$(function() {
$(document).on('click', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
});
</script>
function clicked() {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
}
JSFiddle
I reproduced your problem with slight modifications, works well for me. I guess it's just a syntax error in the portion of your code, not present in the fiddle. Cross check and let me know.
Try and modify your click call, make it direct like in the fiddle.
//try this script
if(!$(this).find("input[name=radio]").is(':checked')){
alert("hi");
}

Validating group of radio buttons

function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if(a.value.length<=0 || b.value.length<=0 || a.value.trim()=="" || b.value.trim()=="")
{
alert("Don't leave the field empty!");
valid = false;
}
if(isNaN(a.value) || isNaN(b.value))
{
alert("Enter a proper number!");
valid = false;
}
for(var i=0; i<form.elements.length; i++)
{
if(form.elements[i].checked)
{
valid = true;
}
else
{
alert("No option selected!");
valid = false;
}
}
return valid;
};
This is my JavaScript function to validate group of radio buttons to check if atleast one of them is selected. And, the one below is my form.
<form name="myForm" font-size="75px;" action ="serv" method="get" onsubmit="return validate();" >
<hr/>
Enter the 1st number: <input type="text" name="a" id="a" /><br/>
Enter the 2st number: <input type="text" name="b" id="b"/><br/><br/>
<label>Add</label><input type="radio" name="option" value="Add" id="r1" /><br/>
<label>Subtract</label><input type="radio" name="option" value="Subtract" id="r2" /><br/>
<label>Multiply</label><input type="radio" name="option" value="Multiply" id="r3" /><br/>
<label>Divide</label><input type="radio" name="option" value="Divide" id="r4" /><br/>
<input type="submit" value="Submit" />
</form>
When i give input and no radio button is selected it should alert the user, but its not happening. Can someone guide where I've gone wrong? And help me out with this? I know there might be lot of duplicates, but I've tried them all to no avail. When i click submit without selecting the radio button it gives me a blank page. Any help is appreciated. Thanks.
Try this, Check the demo here Fiddle
function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if(a.value.length<=0 || b.value.length<=0 || a.value.trim()=="" || b.value.trim()=="")
{
alert("Don't leave the field empty!");
valid = false;
}
if(isNaN(a.value) || isNaN(b.value))
{
alert("Enter a proper number!");
valid = false;
}
var ele = document.getElementsByName("option");
var flag=0;
for(var i=0; i<ele.length; i++)
{
if(ele[i].checked)
{
flag=1;
break;
}
}
if(flag == 0)
{
alert("No option selected!");
valid = false;
}
return valid;
};

Categories

Resources