enabling a checkbox when another checkbox is checked using javascript - javascript

I am trying to enable a disabled checkbox when another checkbox is checked by using javascript. I believe my problem is when I am trying to pass the form information into the javascript.
Here is my HTML:
<form id="checkboxes">
<input type="checkbox" name="checkboxa" onclick="javascript:ToggleSwitch(form)" />1
<input type="checkbox" name="checkboxb" disabled="true" />2
</form>
Here is my Javascript:
<script type="text/javascript">
var form= document.getElementById("checkboxes")
function ToggleSwitch(form) {
if (form.elements["checkboxa"].checked)
form.elements["checkboxb"].disabled = false
} else {
form.elements["checkboxb"].disabled = true
}
</script>

You missed { and } in your javascript. Try this:
var form= document.getElementById("checkboxes")
function ToggleSwitch(form) {
if (form.elements["checkboxa"].checked) { // here
form.elements["checkboxb"].disabled = false
} else {
form.elements["checkboxb"].disabled = true
}
} // and here

Change you onclick event like this
onclick="javascript:ToggleSwitch(this.form)"
and also you don't need to var form= document.getElementById("checkboxes") since you are already passing it as a parameter from onclick event.
And you are also missing a parenthesis
Here is the js
<script>
function ToggleSwitch(form) {
if (form.elements["checkboxa"].checked) {
form.elements["checkboxb"].disabled = false
} else {
form.elements["checkboxb"].disabled = true
}
}
</script>
And here is the html
<form id="checkboxes">
<input type="checkbox" name="checkboxa" onclick="javascript:ToggleSwitch(this.form)" />1
<input type="checkbox" name="checkboxb" disabled="disabled" />2
</form>
And here is a demo

Firstly, you've got syntax errors in your javascript (missing { in the if statement).
You also have some redundancy in your function. It is essentially this pattern:
if (x) { return true; } else { return false; };
which can be simplified to
return x;
Here is a slightly different method, taking these points into account, and also removing the need to search the whole document for ids (which usually makes things more portable/reusable).
<html>
<head>
<script type="text/javascript">
function ToggleSwitch(el, other) {
el.form.elements[other].disabled = !el.checked;
}
</script>
</head>
<body>
<form id="checkboxes">
<input type="checkbox" name="checkboxa" onclick="ToggleSwitch(this, 'checkboxb')" />1
<input type="checkbox" name="checkboxb" disabled="true" />2
</form>
</body>
<html>

Related

jQuery.validator.addMethod is not being executed

This is a simplified version of a page I've been working on; I got some basic validation working here but I want to integrate with the jQuery validator to get inline error messages instead of just alert boxes.
<html>
<head>
<title>pick a box, its contents will help you on your way!</title>
<script src="jQuery-1.4.4-min.js"></script>
<script src="jQuery-validate.js"></script>
</head>
<body>
<form id="fred">
<input class="Notes8" name="Notes8~1" id="Notes8~1" type="checkbox" value="Yes"> Option 1<br>
<input class="Notes8" name="Notes8~2" id="Notes8~2" type="checkbox" value="Yes"> Option 2<br>
<input class="Notes8" name="Notes8~3" id="Notes8~3" type="checkbox" value="Yes"> Option 3<br>
<script type='text/javascript'>
jQuery(function($) {
function validateMultiple (selector, n, isExactlyN) {
const totChecked = $(selector).filter(':checked').length;
return !(isExactlyN ? totChecked == n : totChecked >= n);
}
jQuery.validator.addMethod('.Notes8',
function(value, element) {
return validateMultiple('.Notes8', 1);
},
'Please check at least one check box.');
});
</script>
<button type="submit">SUBMIT!</button>
</form>
</body>
</html>
Problem is, the jQuery.validator.addMethod call doesn't seem to be working; no validation takes place and if I put alert("FRED"); inside the function(value, element) then nothing is displayed, indicating that the validator method never got wired up properly. Why is this? How can I get the validation function to execute when I submit the form? I see no JavaScript errors in the browser console.
You forgot to call validate method: $("#fred").validate();. There was also issue with your validation code - I removed unecessary negation. Also you don't need dot in name paramater in addMethod.
<html>
<head>
<title>pick a box, its contents will help you on your way!</title>
<script src="jQuery-1.4.4-min.js"></script>
<script src="jQuery-validate.js"></script>
</head>
<body>
<form id="fred">
<input class="Notes8" name="Notes8~1" id="Notes8~1" type="checkbox" value="Yes"> Option 1<br>
<input class="Notes8" name="Notes8~2" id="Notes8~2" type="checkbox" value="Yes"> Option 2<br>
<input class="Notes8" name="Notes8~3" id="Notes8~3" type="checkbox" value="Yes"> Option 3<br>
<script type='text/javascript'>
jQuery(function ($) {
function validateMultiple(selector, n, isExactlyN) {
var totChecked = $(selector).filter(':checked').length;
return (isExactlyN ? totChecked == n : totChecked >= n);
}
jQuery.validator.addMethod('Notes8',
function (value, element) {
return validateMultiple('.Notes8', 1);
},
'Please check at least one check box.');
});
$("#fred").validate();
</script>
<button type="submit">SUBMIT!</button>
</form>
</body>
</html>

Onclick event not working with radio button

I am new to html
I am trying to add a onclick event with radio button but it is not working. I am unable to figure out the reason. Please help.
Example code
<script>
function select(btn)
{
var1=document.getElementById("radio1");
var2=document.getElementById("radio2");
var3=document.getElementById("radio3");
if(var1.checked==true)
{
document.myform.action="A.html";
}
elseif(var2.checked==true)
{
document.myform.action="B.html";
}
else
{
document.myform.action="C.html";
}
}
</script>
function test()
{
alert('Testing')
}
{% block radio_buttons %}
<br><br><br>
<!-- <input type="radio" id="radio1" name="project_type" value=0 checked onclick="alert('yes')"><label>Projects I own</label> -->
<input type="radio" id="radio1" name="project_type" value=0 checked onclick="select('this')"><label>Projects I own</label>
<br>
<input type="radio" id="radio2" name="project_type" value=1 onclick="test()"><label>Projects I manage</label>
<br>
<input type="radio" id="radio3" name="project_type" value=1 onclick="select()"><label>Projects I can edit</label>
<br>
{% endblock %}
This code I have added in templates. I tried adding alerts. Alert get exceuted but not onclick event
The select function contains a syntax error and is therefore never executed.
Write:
else if (var2.checked==true)
instead of
elseif (var2.checked==true)
To avoid these kind of errors open the developer console of your browser and check if syntax errors are shown.
Second the choice of select for the function name is unfortunate, since input elements have a select function which is called instead of your function.
To avoid this rename your function (e.g. radioSelect) and call it accordingly (onclick="radioSelect(this);").
Also your test function is placed outside of a script element which is not a good idea.
You have quite a few syntax errors in your code. And you don't need the (btn) after your select in your function. You have omitted a few semi-colons, not least the one after the testing alert.
This code works
<head>
<script>
function select() {
var1 = document.getElementById("radio1");
var2 = document.getElementById("radio2");
var3 = document.getElementById("radio3");
if (var1.selected === true) {
document.myform.action = "A.html";
}
else if(var2.selected === true) {
document.myform.action = "B.html";
} else {
document.myform.action = "C.html";
}
}
function test() {
alert('Testing');
}
</script>
</head>
<body>
<br>
<br>
<br>
<!-- <input type="radio" id="radio1" name="project_type" value=0 checked onclick="alert('yes')"><label>Projects I own</label> -->
<input type="radio" id="radio1" name="project_type" value=0 checked onclick="select();">
<label>Projects I own</label>
<br>
<input type="radio" id="radio2" name="project_type" value=1 onclick="test();">
<label>Projects I manage</label>
<br>
<input type="radio" id="radio3" name="project_type" value=1 onclick="select();">
<label>Projects I can edit</label>
</body>
Here is a fiddle

Javascript and HTML fill variable

so I'm trying to get a html radio button when pressed to send a value to the variable (UserInput) in the JavaScript code.
//HTML CODE//
</HEAD>
<script type="text/javascript" src="javascripts/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="javascripts/question.js"></script>
<BODY>
<form>
<INPUT TYPE="radio" NAME="Home" VALUE="1" >Home
<INPUT TYPE="radio" NAME="School" VALUE="2" >School
<INPUT TYPE="radio" NAME="Work" VALUE="3" >Work
<center><input type="button" name="send" value="Submit" onclick="var UserInput=getValue();"></center>
</form>
</BODY>
</HTML>
I would like to get the value from the radio buttons and store them in the variable UserInput,however it does not seem to be working.
// Javascript code (qustion.js) //
var UserInput = '';
if (UserInput=== '3')
{
confirm("You have selected WORK");
console.log("WORK");
}
else if (UserInput==='2')
{
confirm("You have selected SCHOOL");
console.log("SCHOOL");
}
else if (UserInput==='1')
{
confirm("You have selected HOME");
console.log("HOME");
}
else if (UserInput==='')
{
confirm("You have selected NOTHING");
console.log("NONE");
}
Thanks,also I'm sort of a beginner so a in-depth explanation would be great too.
first you have to use a single name for all, to make them a group (let's say here the group name is myradiogroup), you can define different ids, then do this:
document.querySelector('input[name=myradiogroup]:checked').value
you can also do this in your onclick event:
<input type="button" name="send" value="Submit"
onclick="var UserInput=document.querySelector('input[name=myradiogroup]:checked').value;">
Do something like this in the Html side:
</HEAD>
<script type="text/javascript" src="javascripts/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="javascripts/question.js"></script>
<BODY>
<form>
<INPUT TYPE="radio" id="Home" VALUE="1" >Home
<center><input type="button" name="send" value="Submit" onclick="var UserInput=getValue();"></center>
</form>
and the js side like this:
var UserChoice;
function getValue(){
if ($('input[id = Home]:checked').size() > 0) {
UserChoice = "Home";
}
}
Same is applicable to school and work
first set the same name property to your radios for create a group
<INPUT TYPE="radio" name="optionsRadios" id="Home" VALUE="1" >Home
<INPUT TYPE="radio" name="optionsRadios" id="School" VALUE="2" >School
<INPUT TYPE="radio" name="optionsRadios" id="Work" VALUE="3" >Work
after call the function on your button
<input type="button" name="send" value="Submit" onclick="getValue();">
and last create the function getValue and use :
document.querySelector("input[name=optionsRadios]:checked").value;
the querySelector return all the objects with the name "optionRadios" and checked , in this case just one
function getValue(){
var UserInput = '';
UserInput= document.querySelector("input[name=optionsRadios]:checked").value;
if (UserInput=== '3')
{
confirm("You have selected WORK");
console.log("WORK");
}
else if (UserInput==='2')
{
confirm("You have selected SCHOOL");
console.log("SCHOOL");
}
else if (UserInput==='1')
{
confirm("You have selected HOME");
console.log("HOME");
}
else if (UserInput==='')
{
confirm("You have selected NOTHING");
console.log("NONE");
}
}
Example:
http://jsfiddle.net/RrYJu/1/
Try This Code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(function(){
$(document).ready(function(){
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
alert($(this).val());
}
});
});
});
var UserInput = '';
$(document).ready(function() {
$('input:radio').click(function() {
if ($(this).is(':checked'))
{UserInput =$(this).val();}
});
}
You can easily accomplish this by using jquery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(function(){
$(".button_classname_here").click(function(){
alert($('input[type=radio]:checked').val());
});
});
</script>

put html checkbox value into text field

I have a checkbox with a value of U
i want to put this value into a text input when the checkbox is checked.
how can i do this using javascript or jquery? I need to be able to do it on multiple checkboxes and input text fields too
HTML
<input type="checkbox" value="U" id="checkBox"/>
<input type="text" value="" id="textInput" />
JQUERY
$("#checkBox").change(function(){
$("#textInput").val($(this).val());
});
DEMO
Try this,
HTML
<label><input type="checkbox" value="U" />Check</label>
<input type="text" />
SCRIPT
$('input[type="checkbox"]').on('click',function(){
var is_checked=$(this).prop('checked');
var val='';
if(is_checked)
val=this.value;
$('input[type="text"]').val(val);
});
Working Demo
the simpliest way to do this :o)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var checkboxInput = document.getElementById('checkboxInput'),
textInput = document.getElementById('textInput');
checkboxInput.addEventListener('click', UpdateTextInput, false);
};
function UpdateTextInput () {
if(checkboxInput.checked) {
textInput.value = checkboxInput.value;
}
else {
textInput.value = '';
}
}
</script>
</head>
<body>
<input type="checkbox" id="checkboxInput" value="U"/>
<input type="text" id="textInput" />
</body>
</html>
Assuming one textbox is associated with every checkbox like below.
HTML Pattern :
<input type="checkbox" value="test1" id="test1" checked><label>Test</label>
<input type="text" class="text1"id="textbox1" name="textbox1" value="">
jQuery:
$('input[type="checkbox"]').change(function() {
var vals = $(this).val();
if($(this).is(':checked')){
$(this).next().next("input[type='text']").val(vals);
}else{
$(this).next().next("input[type='text']").val("");
}
});
Here is the working demo : http://jsfiddle.net/uH4us/

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