Check if a radio button is on - javascript

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.

Related

trigger event if checkbox is checked javascript

I have an HTML page with several checkboxes and one disabled button.
Now, as soon as one or more of the checkboxes are checked, the button must enable.
Also, when all the checkboxes are unchecked, the button must go to disabled-state again.
The test case seems to be:
If a checkbox is checked, then the button should enable (this I can get to work).
If another checkbox is checked, the button remains enabled (this also works).
If the first checkbox is unchecked, the button must also stay enabled, because the 2nd checkbox is still checked.
This last part is that I can't get to work.
The checkboxes are dynamical, so I can't define them beforehand. There might be two, or ten.
This is why I tried a for loop.
I can't get this to work, what I have so far:
var x = document.getElementsByName("cb");
for (var i = 0; i < x.length; i++) {
if(x[i].checked == true){
document.getElementById('Button1').disabled = false;
}
}
<div class="container">
<input type="button disabled" name="Button1" class="inputButton" id="Button1" value=" Send " disabled="disabled" />
</div>
<div>
<input type="checkbox" onchange="document.getElementById('Button1').disabled = !this.checked;" />
<input type="checkbox" onchange="document.getElementById('Button1').disabled = !this.checked;" />
</div>
Both with the HTML and onchange event and the Javascript I can't get it to work.
The two are not used at the same time.
EDIT: Got it to work: The answer by Takit Isy works fine!
I suggest you to do that kind of things:
(See comments in my code)
var cbs = document.querySelectorAll('input[type="checkbox"]');
var but = document.getElementById('Button1');
function update() {
but.disabled = true; // Disabled by default
cbs.forEach(function(entry) {
if (entry.checked) {
but.disabled = false; // Enable button
return false; // Exit the loop
}
});
}
cbs.forEach(function(entry) {
entry.onchange = update; // Bind update() function on change of each checkboxes
});
<div class="container">
<input type="submit" name="Button1" class="inputButton" id="Button1" value=" Send " disabled />
</div>
<div>
<input type="checkbox" />
<input type="checkbox" />
</div>
Hope it helps.
function onChange(e) {
var checkedInputs = document.querySelectorAll('input[type="checkbox"]:checked');
if (checkedInputs.length > 0) {
document.getElementById('Button1').disabled = false;
} else {
document.getElementById('Button1').disabled = true;
}
}
document.querySelectorAll('input[type="checkbox"]').forEach(function(val, key) {
val.addEventListener("change", onChange);
})
<div class="container">
<input type="button disabled" name="Button1" class="inputButton" id="Button1" value=" Send " disabled="disabled" />
</div>
<div>
<input type="checkbox" />
<input type="checkbox" />
</div>

Check/Uncheck using jQuery not working

I am trying to make the check boxes behave like radio buttons in my ASP .NET MVC Web Application. I have got about 20-30 check boxes grouped in two. For Example:
<input type="checkbox" id="#riggingType.RiggingTypeId 1" name="RiggingTypePlus"
value="#riggingType.RiggingTypeId"
checked="#riggingTypeIds.Contains(riggingType.RiggingTypeId)" />
<input type="checkbox" id="#riggingType.RiggingTypeId 2" name="RiggingTypeMinus"
value="#riggingType.RiggingTypeId"
checked="#riggingTypeIds.Contains(riggingType.RiggingTypeId)" />
Goal:
I want to make the check boxes to behave in such a way that if a Plus Check box is checked then the Minus is unchecked automatically and vice versa. I have written following code to try and achieve this functionality:
$(":checkbox").change(function () {
var inputs = $(this).parents("form").eq(0).find(":checkbox");
var idx = inputs.index(this);
if (this.name.substring(this.name.length - 4, this.name.length) === "Plus") {
// just trying to check if I am getting the right it
// and I am getting the right id
// alert(inputs[idx + 1].id);
// But this does not work
$("#" + inputs[idx + 1].id).prop('checked', false);
}
});
Am I doing something wrong here:
$("#" + inputs[idx + 1].id).prop('checked', false);
Any help will be appreciated.
I know that I can use the radio buttons and group them by same name but I am rendering the elements in a loop so they all have the same name but different values and I don't want to name them differently because I am using this data on the server side... Is there a better way to do this?
Answer:
Got this working using the following:
$(document).ready(function(){
$(":checkbox").on('click', function () {
var $this = $(this);
var inputs = $this.closest("form").find(":checkbox");
if ($this.attr('name').substring(this.name.length - 4, this.name.length) === "Plus" && $this.attr('checked')) {
$this.next().prop('checked', false);
}
else
{
$this.prev().prop('checked', false);
}
});
});
Fiddle Link
fiddle: https://jsfiddle.net/24gmnjwm/1/
$(document).ready(function(){
$(":checkbox").on('click', function () {
var $this = $(this);
var inputs = $this.closest("form").find(":checkbox");
if ($this.attr('name').substring(this.name.length - 4, this.name.length) === "Plus") {
$this.next().prop('checked', false);
}
});
});
If we can assume that the "plus" checkbox always appears immediately before its related "minus" checkbox then this will do the trick:
$(":checkbox").change(function () {
if ($(this).prop("name").match(/Plus$/)) {
$(this).next().prop("checked", !$(this).prop("checked"));
} else {
$(this).prev().prop("checked", !$(this).prop("checked"));
}
});
sample form:
<form>
<input type="checkbox" name="RiggingTypePlus" value="2" checked />
<input type="checkbox" name="RiggingTypeMinus" value="2" />
<input type="checkbox" name="RiggingTypePlus" value="3" />
<input type="checkbox" name="RiggingTypeMinus" value="3" />
<input type="checkbox" name="RiggingTypePlus" value="4" />
<input type="checkbox" name="RiggingTypeMinus" value="4" />
<input type="checkbox" name="RiggingTypePlus" value="5" />
<input type="checkbox" name="RiggingTypeMinus" value="5" />
</form>
fiddle

Enabling or Disabling Buttons Based on CheckBox

I had an I Agree Checkbox that when checked or unchecked it used JS to toggle the Disabled setting on a button with id="submit1". However, I added more buttons and now it needs to toggle all of these buttons rather than just the first, so the ID isn't working anymore.
Current Code for checkbox:
<input type="checkbox" checked id="agree" name="agree" value="ON" onclick="javascript: if(document.getElementById('agree').checked==true){document.getElementByID('submit1').disabled=false;}else{document.getElementByID('submit1').disabled=true;}">
And for button:
<button onclick="do_file_form_submit(7);" id="submit1" name="submit1" class="custombutton">Button Number 1</button>
So, I have added more buttons, so I need 2 things:
I need JS or jquery that will loop through and toggle EACH button when the box is checked rather that just the single button (first button with the ID).
On page load, I also need it to check and see if the box is checked and if not, loop through and disable all of those buttons.
Thanks so much for any help you can give!!
Craig
HTML:
<input type="checkbox" checked id="agree" name="agree" value="ON">
<button onclick="do_file_form_submit(7);" id="submit1" name="submit1" class="custombutton">Button Number 1</button>
<button onclick="do_file_form_submit(7);" id="submit2" name="submit2" class="custombutton">Button Number 2</button>
jQuery:
$('#agree').change(function () {
if ($(this).is(":checked")) {
$('button').attr("disabled", false);
} else {
$('button').attr("disabled", true);
}
});
Here is the fiddle: http://jsfiddle.net/shahe_masoyan/UpxzB/3/
Check this out Your working page
function checkStatus() {
if ($('#agree_again').is(":checked")) {
$(".custombutton").attr('disabled', false);
}
else {
$(".custombutton").attr('disabled', true);
}
}
$("#agree_again").change(function () {
checkStatus();
});
You can call this checkStatus function on body load to check whether its checked or not on page load .
asign same classname for all button.
then use the class name for selector.
document.getElementByClassName("custombutton").disabled=false
Try this code. Hope this resolve your problem
$(function(){
//$("#agree").is(":checked")
EnableDisableButton(!$("#agree").is(":checked"))
$("#agree").click(function(){
EnableDisableButton(!$("#agree").is(":checked"));
})
function EnableDisableButton(isEnable){
$(".custombutton").attr("disabled",isEnable);
}
});
very simple
<input type="checkbox" checked="checked" id="agree" name="agree" value="ON"
class="agree_chk" />
<input type="button" class="button" id="button1" value="button1"/>
<input type="button" class="button" id="button1" value="button2"/>
<input type="button" class="button" id="button1" value="button3"/>
<input type="button" class="button" id="button1" value="button4"/>
and the javascript is
$(document).on('click','#agree',function() {
$('.button').attr({disabled:!$(this).is(':checked')})
});
js fiddle http://jsfiddle.net/5V2Y4/
try this code
<input type="checkbox" checked id="agree" name="agree" value="ON" onclick="change()">
<input type="button" id="button1">
<input type="button" id="button2">
<input type="button" id="button3">
<script>
$(document).ready(function() {
change();
});
function change() {
var i = 1;
for (i = 1; i <= 3; i++) {
var btnid = "button" + i;
if (document.getElementById("agree").checked) {
document.getElementById(btnid).disabled = false;
} else {
document.getElementById(btnid).disabled = true;
}
}
}
</script>
you can change the limit as the number of buttons changes

JavaScript checking radio buttons

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

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