I have a form full of checkboxes and I would like to disable the form if a certain boxed is checked. I will have this appear multiple times on my site and I was wondering if there is a better way than what I'm currently trying (which isn't working). If I want to use this same disable function multiple times, should I create a class 'disable'? Thanks!
JS
$(document).ready(function()
{
$('#disabler_0').click(function()
{
$('[name*=form1]').attr('disabled', 'disabled')
});
});
html
<form id="form1" name="form1" method="post" action="">
<p>
<label>
<input type="checkbox" name="disabler" value="one" id="disabler_0" />
one</label>
<br />
<label>
<input type="checkbox" name="disabler" value="two" id="disabler_1" />
two</label>
<br />
<label>
<input type="checkbox" name="disabler" value="three" id="disabler_2" />
three</label>
<br />
<label>
<input type="checkbox" name="disabler" value="four" id="disabler_3" />
four</label>
<br />
<label>
<input type="checkbox" name="disabler" value="five" id="disabler_4" />
five</label>
<br />
</p>
</form>
I wasn't able to disable a whole form, but every inner element on it:
There's a dummy updated example here:
http://jsfiddle.net/marcosfromero/S2SxN/
Updated
The code should be adapted to your needs and turn it more usable because once you disabled the whole form, you can't enable it again:
$('#disabler_0').click(function() {
var elements = $(this).closest('form').find('input, select textarea').not('#disabler_0');
if(this.checked) {
elements.attr('disabled', 'disabled');
} else {
elements.removeAttr('disabled');
}
});
Okay then, based on your response:
$(document).ready(function()
{
$('#disabler_0').click(function()
{
$('#form1 input[type="checkbox"]').not("#disabler_0").attr('disabled', 'disabled')
});
});
This will disable all input elements of type checkbox that are children of the form.
You cannot actually disable a form, the disable attribute is only used for inputs. What you want to do is something like this:
$("#form1").live("submit", function() {
if ($("#disabler_0").is(":checked"))
return false;
return true;
});
This will not let the form submit when the check-box is checked.
Edit for the comment clarification, this will disable all the inputs and selects when the check-box is selected.
$('#disabler_0').live("click", function() {
var form = $(this).parents("form");
var inputs = $("input,select,textarea", form);
inputs.attr("disabled", "disabled");
});
this can be improvment:
$(function() {
$('.disabler').click(function() {
$(this).parent('form').attr('disabled', 'disabled');
});
});
by this code you dont need modify code for each form
You could put a class on all of the checkboxes that you want to disable the form and use this code:
$('input.disabler').click(function() {
var form = $(this).closest('form');
var isChecked = $(this).is(':checked');
form.toggleClass('disabled', isChecked);
if (isChecked)
form.find(':input').attr('disabled', 'disabled')
});
$('#form1').bind('submit', function() {
if ($(this).hasClass('disabled'))
return false;
});
Related
I'm trying to make a form that will hide and show some parts of the form. It working correctly in some tries. But when the user chooses and checks an option with class badCheckbox which is showing badField subsequently then user checks option without class badCheckbox which should showing 'goodField' than 'badField' is not hiding and still is shown.
And when a user tries to check options separately all work correctly only in upper mentioned case.
Is there any way to do it?
//Script to hide and show div
$('.badCheckbox').change(function() {
let checked = 0;
$('.badCheckbox').each(function() {
if (this.checked) {
checked += 1;
}
});
if (checked != 0) {
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
});
//script to check only one of three
$(".oneChecked").on('click', function() {
// in the handler, 'this' refers to the box clicked on
var $box = $(this);
if ($box.is(":checked")) {
var group = "input:checkbox[name='" + $box.attr("name") + "']";
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked" />
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit" />
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit" />
</div>
here is a short version
$('#checks').on('change', 'input[name="checkin"]', function (){
if( $(this).is(':checked') ){
$('#checks .oneChecked:checked').prop('checked', false);
$(this).prop('checked', true);
} else {
$('#checks .oneChecked:checked').prop('checked', false);
$(this).prop('checked', false);
}
if( $('#checks .badCheckbox:checked').is(':checked') ){
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="checks">
<input name="checkin" type="checkbox" class="oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="oneChecked"/>
</div>
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit"/>
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit"/>
</div>
Consider the following improvements.
$(function() {
function checkStuff(checked) {
if (checked) {
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
}
//script to check only one of three
$(".boxes").on('change', ".oneChecked", function() {
if ($(this).is(":checked")) {
$(".boxes input[type='checkbox']").prop("checked", false);
$(this).prop("checked", true);
checkStuff($(this).is(".badCheckbox"));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="boxes">
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked" />
</div>
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit" />
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit" />
</div>
it's because you don't have an event when user click and the third checkbox.
Your function to show/hide message work when there are an update (change) on an input with the class .badCheckbox but when you click on the third (where doesn't have the class) your function is not called.
I think you should have a class on all your checkbox and use it in your function who lister the change.
Something like this :
$('.checkbox').change(function() {
let checked = 0;
$('.badCheckbox').each(function() {
// ...
});
And your html
<input name="checkin" type="checkbox" class="checkbox oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="checkbox oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="checkbox oneChecked"/>
There is a lot of optimization that can be done to improve your code, like using the radio to remove your oneChecked function or printing the right message when the checkbox is checked instead of using show/hide two div but i think you should see it in the future
I hope this can help you and welcome to StackOverflow
First of all, obviously your checkboxes have to act like radios. As I understand, that is what you want to do. So, I modifyed your script a little bit to make checkboses to act as they are radio inputs, and in the same time to show/hide paragraph, depending on if clicked element has class badCheckbox and it's state (checkd or not). Here is the result:
//Script to hide and show div
$('.oneChecked').click( (everyOne) => {
//handles click (and change) on every element with class oneChecked
//they all has it in your example
$('.oneChecked').each( (ind, currentOne) => {
//iterate to all elements with class oneChecked
//and compare if matches clicked one
if ( !$(currentOne).is($(everyOne.target)) ) {
//other instance, not clisked one, so clear it
//to simulate behaviour of radio input
$(currentOne).prop('checked', false);
}
});
//checks if clicked element is bad or not and show/hide your p
if ($(everyOne.target).hasClass('badCheckbox') && $(everyOne.target).prop('checked')){
console.log('b-s/h');
$('#badField').show();
$('#goodField').hide();
} else {
console.log('s/b-h');
$('#badField').hide();
$('#goodField').show();
}
});
Here is an workign example in CodePen: https://codepen.io/kalatchev/pen/gOpJBOv
I have the three input checkboxes all of them have the same name attribute I want one of them is checked then others uncheck and disabled. I want to the jquery code within the function call on function and on change event like this code below or any another way work correctly.
<div class="topmenuitems">
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithouticon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithicon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemicon" />
</div>
var itemWithIconCheckbox = $('.topmenitems input');
var topItemTypesFunc = function() {
//Jquery code here
};
topItemTypesFunc();
topItemTypeCheckboxes.on( 'change', topItemTypesFunc);
You can do the function you want via radio buttons. Here, I have implemented a simple logic here. When a checkbox is changed ten uncheck checkbox other then the clicked one. Here is an working example.
$('input[name="menu-item-topitemtypes"]').on( 'change', function(){
if($(this).prop('checked')){
$('input[name="menu-item-topitemtypes"]').not($(this)).prop('checked', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="topmenuitems">
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithouticon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithicon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemicon" />
</div>
This may help full to you
$('input[type="checkbox"]').on('change', function(){
if($(this).is(':checked')){
$(this).siblings().attr('disabled', 'true');
}else{
$(this).siblings().removeAttr('disabled', 'false');
}
})
I have two checkboxes in a form. onclick if a checkbox called email is unchecked how can I get the other checkbox to also uncheck (if it is checked) ?
document.getElementById('email').onclick = function() {
if (!this.checked) {
!document.getElementById("other").checked;
} else {
// if not checked ...
}
};
Am I completey barking up the wrong tree? Any help appriciated
To synchronize the checking of the both at the same time you need just to use this.checked of the first clicked one on the checked attribute of the second one like :
document.getElementById("other").checked = this.checked;
NOTE : That will work on one way, what means the check will be synchronized just when you click on the first checkbox that you've attached the click event to.
document.getElementById('email').onclick = function() {
document.getElementById("other").checked = this.checked;
};
<input id="email" type="checkbox" /> CHECKBOX 1
<br>
<input id="other" type="checkbox" /> CHECKBOX 2
You can make it like :
<form id="test" action="#" method="post">
<div>
<input type="checkbox" name="check" id="check"/>
</div>
<div>
<input type="checkbox" name="check2" id="check2"/>
</div>
</form>
document.getElementById('check').onclick = function() {
if (!this.checked) {
document.getElementById("check2").checked = false;
} else {
// other logic ...
}};
Test it online on jsfiddle : https://jsfiddle.net/3dtq0w8x/
In your test code you are not setting the checked property of "other" to any value.
You are just reading its value, then inverting it (with !).
You could try:
document.getElementById("other").checked = false;
You can add event listener to email checkbox (which is a good practice) and then check if it is check or not and deal with the other checkbox according to that
For example
var ckb = document.getElementById('email')
ckb.addEventListener("click", function(e){
if(!e.target.checked)
document.getElementById('ot').checked = false;
})
<input type="checkbox" name="na" value="email" id="email">Email<br>
<input type="checkbox" name="na" value="other" id="ot">Other
This should help
function check() {
if(document.getElementById("email").checked){
document.getElementById("other").checked = true;
}else{
document.getElementById("other").checked = false;
}
}
HTML
<input type='checkbox' id='email' name='checkbox' onclick="check()" >email
<input type='checkbox' id='other' name='checkbox'>other
i've checkbox and text input
What I need is to enable text input when i check the checkbox and to disable text input when i uncheck the checkbox
I'm using the following code but it do the reverse enable when unchecked / disable when checked so how to adjust it fit with my needs.
<input type="checkbox" id="yourBox">
<input type="text" id="yourText">
<script>
document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').enabled = this.checked;
};
</script>
any help ~ thanks
You just need to add a ! in front of this.checked.
Here's an example that shows the change:
document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').disabled = !this.checked;
};
<input type="text" id="yourText" disabled />
<input type="checkbox" id="yourBox" />
A jQuery solution could be this one:
<script>
$('#yourBox').change(function() {
$('yourText').attr('disabled',!this.checked)
});
</script>
It is the same as Minko's answer but I find it more elegant.
Try it. If you use a label then add onmousedown to it
<form >
<input type="text" id="yourText" disabled />
<input type="checkbox" id="yourBox" onmousedown="this.form.yourText.disabled=this.checked"/>
</form>
A better solution could be:
var checkbox = document.querySelector("#yourBox");
var input = document.querySelector("#yourText");
var toogleInput = function(e){
input.disabled = !e.target.checked;
};
toogleInput({target: checkbox});
checkbox.addEventListener("change", toogleInput);
<input type="checkbox" id="yourBox">
<input type="text" id="yourText">
function createInput( chck ) {
if( jQuery(chck).is(':checked') ) {
jQuery('<input>', {
type:"text",
"name":"meta_enter[]",
"class":"meta_enter"
}).appendTo('p.checkable_options');
}
else {
jQuery("input.meta_enter").attr('disabled','disabled');
}
}
createInput( chck );
<input type="radio" name="checkable" class="checkable" value="3" />
<input type="radio" name="checkable" class="checkable" value="4" onclick="createInput(this)" />
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