JavaScript checking radio buttons - javascript

Ok, this is really a simple question but I am really incompetent at JavaScript.
Basically all I have a form with 2 radio buttons on them.
I need a JavaScript statement which basically says
If radiobutton1 is selected then
document.write ("radiobutton1selected")
else if radiobutton2 is selected then
document.write ("radiobutton2selected")
There are similar questions on here i accept but they are all alot more advanced than what i need.

Radio button html:
<input type="radio" name="radionbutton" value="1" id="button1"/>
<input type="radio" name="radionbutton" value="2" id="button"/>
Javascript:
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
if (button1.checked){
alert("radio1 selected");
}else if (button2.checked) {
alert("radio2 selected");
}

http://jsfiddle.net/Squeegy/KCT8h/
html
<input type="radio" name="zing" id="foo" checked/>
<input type="radio" name="zing" id="bar"/>​
js
if (document.getElementById('foo').checked) {
alert('foo');
} else {
alert('bar');
}​

This is simple:
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
alert(button1.checked?"Button1 is checked":"Button2 is checked");

Related

addEventListener: click just one element of a bunch of elements

I'm beginner and have trouble with something in JS that might be simple to solve.
I made a quiz based on a NetNinja Udemy course, and I want the submit button to be enabled just when the user clicks on any answer option, and not before, so that he/she can't send a totally empty quiz.
The quiz has 4 questions with 2 options each, and I found this way...
const input_a = document.getElementById("q1a");
const input_b = document.getElementById("q1b");
button.disabled = true;
input_a.addEventListener('click', () => {
button.disabled = false;
});
input_b.addEventListener('click', () => {
button.disabled = false;
});
...to enable the button when the user clicks on any of the two options of the first question (ids: q1a & q1b) Following this logic, there'd also be q2a, q2b, q3a, q3b, q4a & q4b..
As there is a way to include all the answers in one JS element, what should I do in the event function to say "when you click any of this 8 options, enable the button"? Because everything I tried only makes the function work if I click all the buttons, which is obviously impossible in a Quiz .
Thank you! :)
In the solution below, when any of the radio buttons is clicked, the submit button is activated.
let result = [false, false, false, false];
let submitButton = document.getElementById('submitButton');
/* Returns true if all tests have been completed. */
function isValid(){
for(let i = 0 ; i < result.length ; ++i)
if(result[i] != true)
return false;
return true;
}
/* If all tests are completed, the submit button is activated. */
function send(){
result[this.value] = true;
if(isValid()){
submitButton.disabled = false;
console.log("The form can be submitted!");
}
}
/* The send() method is called when the change event of <input> elements whose type is "radio" is fired. */
document.querySelectorAll('input[type="radio"]').forEach((element) => {
element.addEventListener("change", send);
});
<form action="#">
<input type="radio" id="html" name="test1" value="0">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="test1" value="0">
<label for="css">CSS</label><br><br>
<input type="radio" id="js" name="test2" value="1">
<label for="html">JavaScript</label><br>
<input type="radio" id="c#" name="test2" value="1">
<label for="css">C#</label><br><br>
<input type="radio" id="c" name="test3" value="2">
<label for="html">C</label><br>
<input type="radio" id="c++" name="test3" value="2">
<label for="css">C++</label><br><br>
<input type="radio" id="python" name="test4" value="3">
<label for="html">Python</label><br>
<input type="radio" id="ruby" name="test4" value="3">
<label for="css">Ruby</label><br><br>
<button id="submitButton" type="submit" disabled>Submit</button>
</form>

working with radio buttons passing the status along with value?

I am writing code for radio buttons where there are 3 radio buttons like YES, NO and ALL. I am using same class name for all the 3 and also binding a value for them. If user clicks on one of the three Am able to pass the corresponding value on onclick event but my problem is how to know whether user clicks on which radion button among the three buttons like if user clicks on 'All' radio button I want to perform some type of action else if user clicks on 'Yes' option then some different action, etc. how to know user clicks on which radio button? mycode is below:
<input type="radio" name="select_option" class="select_option" value="<?=$row_id;?>">All
<input type="radio" name="select_option" class="select_option" value="<?=$row_id;?>">Yes
<input type="radio" name="select_option" class="select_option" value="<?=$row_id;?>">No
I need radio button value along with user clicked on which radio button. how to achieve this? Can anyone please guide me.
I have added my class names(all, yes, no) in those html elements
<input type="radio" name="select_option" class="select_option all" value="<?=$row_id;?>">All
<input type="radio" name="select_option" class="select_option yes" value="<?=$row_id;?>">Yes
<input type="radio" name="select_option" class="select_option no" value="<?=$row_id;?>">No
Using jQuery
$(document).ready(function(){
$("input:radio").click(function(e){
if($(this).hasClass("all"))
{
console.log("which button -> all");
console.log("value="+$(this).val());
}
else if($(this).hasClass("yes"))
{
console.log("which button -> yes");
console.log("value="+$(this).val());
}
else if($(this).hasClass("no"))
{
console.log("which button -> no");
console.log("value="+$(this).val());
}
});
});
FIDDLE
Please add an extra parameter for storing the 'id' inside the input box, just like this:
<input type="radio" name="select_option" class="select_option" value="all" data-id="<?=$row_id;?>">All
<input type="radio" name="select_option" class="select_option" value="yes" data-id="<?=$row_id;?>">Yes
<input type="radio" name="select_option" class="select_option" value="no" data-id="<?=$row_id;?>">No
Now, here is the script which will run after checking the radio button:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.select_option').click(function() {
if ($(this).prop('checked')) {
var id = $(this).data('id');
var value = $(this).val();
}
alert(value);
});
});
</script>
I hope, this may be useful to you.
try this
$(".select_option").change(function(){
var radioValue = $("input[name='select_option']:checked").val();
if(radioValue){
alert("Your are clicked - " + radioValue);
}
});
$(".select_option").change(function () {
if ($(this).is(":checked")) {
var value = $(this).val();
console.log(value);
}
});
fiddle

Cannot get the checked radio correctly in click event

Page code as below:
<input type="radio" class="direct" name="r1" value="first" />
<span class="proxy">radio1</span>
<input type="radio" class="direct" name="r1" value="second" />
<span class="proxy">radio2</span>
js code as below:
$('.direct').click(function(e) {
var obj = $(this).parent(),
value = obj.find('input:checked').val();
if(value){
alert('you click ' + value + ' button');
}else{
alert('you did not click a button');
}
});
$('.proxy').click(function(e) {
$(this).prev().click();
});​
Here is the example on JSFiddle
My question is:
why clicking on span text does not work like clicking directly on radio button?
As i said earlier, question was not clear, at least for me. however, if you want to get the radio checked when clicked on next span, you can do this way:
$('.proxy').click(function(e) {
$(this).prev().attr('checked', true)
});​
If you use a label with for attribute set to the correct input, you could avoid all this problem.
<input type="radio" class="direct" name="r1" id="r11" value="first"/>
<label class="proxy" for="r11">radio1</label>
<input type="radio" class="direct" name="r1" id="r12" value="second"/>
<label class="proxy" for="r12">radio1</label>​​​​​​​​​
DEMO

Check if a radio button is on

I am trying to check whether a radio button has been clicked on my page but for some strange reason it not acting the way I expect it to.
In my .js I have:
function radio_is_on() {
var elementId = document.getElementById('delete');
if (elementId.checked == "on" ){
alert('I am here');
}
}
In my html I have:
<input type="radio" id="some" name="radio1" value="someVal" >
<input type="radio" id="delete" name="radio2" value="delete" >
<input class=b1 type="submit" name="ok" value="Go" onclick="radio_is_on();">
Try this:
function radio_is_on() {
var elementId = document.getElementById('delete');
if (elementId.checked){
alert('I am here');
}
}
BTW: If you are not using the same name at least twice, you might want to use checkboxes.

make checkbox behave like radio buttons with javascript

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
$(".chb").not(this).prop('checked', false);
});
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){
e = e || event;
var cb = e.srcElement || e.target;
if (cb.type !== 'checkbox') {return true;}
var cbxs = document.getElementById('radiocb')
.getElementsByTagName('input'),
i = cbxs.length;
while(i--) {
if (cbxs[i].type
&& cbxs[i].type == 'checkbox'
&& cbxs[i].id !== cb.id) {
cbxs[i].checked = false;
}
}
}
Here's a working example.
This is a better option as it allows unchecking also:
$(".cb").change(function () {
$(".cb").not(this).prop('checked', false);
});
I kept it simple...
<html>
<body>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('id1').checked = false;
document.getElementById('id2').checked = false;
document.getElementById('id3').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
<form action="your action" method="post">
<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
#DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:
$(".chb").change(function(e) {
//Getting status before unchecking all
var status = $(this).prop("checked");
$(".chb").prop('checked', false);
$(this).prop('checked', true);
//false means checkbox was checked and became unchecked on change event, so let it stay unchecked
if (status === false) {
$(this).prop('checked', false);
}
});
https://jsfiddle.net/mapetek/nLtb0q1e/4/
Just in case it helps someone else
I was having the same situation where my client needed to have a checkbox behaving like a radio button. But to me it was meaningless to use a checkbox and make it act like radio button and it was very complex for me as I was using so many checkboxes in a GridView Control.
My Solution: So, I styled a radio button look like a checkbox and took the help of grouping of radio buttons.
You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:
function clickReset ()
{
var isChecked = false,
clicked = $(this),
set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
if (isChecked = clicked.attr ('checked'))
{
set.attr ('checked', false);
}
return true;
}
$(function ()
{
$('.test').click (clickReset);
});
Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.
I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.
EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.
http://jsfiddle.net/j53gd/1/
<html>
<body>
<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Ultimately you can use brackets with the name attribute to create an array of radio input like so:
<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4
What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.
In Simple JS.
Enjoy !
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onChoiceChange(obj) {
// Get Objects
var that=obj,
triggerChoice = document.getElementById(that.id),
domChoice1 = document.getElementById("Choice1"),
domChoice2 = document.getElementById("Choice2");
// Apply
if (triggerChoice.checked && triggerChoice.id === "Choice1")
domChoice2.checked=false;
if (triggerChoice.checked && triggerChoice.id === "Choice2")
domChoice1.checked=false;
// Logout
var log = document.getElementById("message");
log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
// Return !
return that.checked;
}
</script>
</head>
<body>
<h1 id="title">Title</h1>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
<hr>
<div id="message"></div>
</body>
</html>
try this
<form id="form" action="#">
<input name="checkbox1" type="checkbox" />
<input name="checkbox2" type="checkbox" />
<input name="checkbox3" type="checkbox" />
<input name="checkbox4" type="checkbox" />
<input name="checkbox5" type="checkbox" />
<input name="checkbox6" type="checkbox" />
<input name="checkbox7" type="checkbox" />
<input name="checkbox8" type="checkbox" />
<input name="checkbox9" type="checkbox" />
<input name="checkbox10" type="checkbox" />
<input type="submit" name="submit" value="submit"/>
</form>
and this is the javascript
(function () {
function checkLikeRadio(tag) {
var form = document.getElementById(tag);//selecting the form ID
var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false.
if (checkboxList[i].type == "checkbox") {
checkboxList[i].checked = false;
}
checkboxList[i].onclick = function () {
checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
checkBoxName(this);// passing the location of selected checkbox to another function.
};
}
}
function checkBoxName(id) {
return id.checked = true;// selecting the selected checkbox and maiking its value true;
}
window.onload = function () {
checkLikeRadio("form");
};
})();
I like D.A.V.O.O.D's Answer to this question, but it relies on classes on the checkbox, which should not be needed.
As checkboxes tend to be related in that they will have the same (field) name, or a name which make them part of an array, then using that to decide which other checkboxes to untick would be a better solution.
$(document)
.on('change','input[type="checkbox"]',function(e){
var $t = $(this);
var $form = $t.closest('form');
var name = $t.attr('name');
var selector = 'input[type="checkbox"]';
var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
if( m ){
selector += '[name^="'+m[1]+'["][name$="]"]';
}else{
selector += '[name="'+name+'"]';
}
$(selector, $form).not($t).prop('checked',false);
});
This code on jsFiddle

Categories

Resources