Check/Uncheck using jQuery not working - javascript

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

Related

Adding and removing from count when checkbox is checked/unchecked with javascript/jquery?

I'm relatively new to JS, so I'm getting a little stuck with this:
Let's say I have 40 checkboxes, but a user can select no more than 10.
I have the checkboxes set out, labelled checkbox1, checkbox2 etc right up to 40. The user cannot select more than 10. How would I go about doing this?
The way I thought of doing it would be like this, but I'm unsure whether or not this would work, due to obviously having 40 fields and then what if they uncheck one?
function checkValidation() {
if (document.getElementById('checkbox1').isChecked()) {
document.getElementById('validation').value() + 1;
}
}
So every time it's checked, it would add 1 to the textbox validation and then I could do an if statement to say if validation.value() > 8 then alert out to say they can't check anymore.
I think that's not the best way, as if they uncheck the box, my function won't take this in consideration?
Hopefully this makes sense, if anything needs clarification please let me know and I can explain further.
Try the following way:
$('#myBtn').click(function(){
var countCheckd = $('input[type=checkbox]:checked').length;
if(countCheckd >= 3){
console.log('You have 3 or more checked: ' +countCheckd);
}
else{
console.log('You have less than 3 checked: ' +countCheckd);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />1
<input type="checkbox" />2
<input type="checkbox" />3
<input type="checkbox" />4
<input type="checkbox" />5
<br><br>
<input type="button" id="myBtn" value="Check"/>
You can add a class on all your considered checkboxe, called for example chk.
Then you declare your count function :
function countCheck(){
return $(".chk:checked").length;
}
Finally you add an event on your checkboxes click :
$(document).on("click",".chk",function(){
var numberChecked = countCheck();
//update your input
$("#validation").val(numberChecked );
});
Just make an event of checkbox click and check for the count of each click, in below example if the click is exceeded then 5 it gives an alert message and won't be allowed to click more checkboxes.
$(function(){
for(var i=0;i<=30;i++){
$(".test").append("checkbox "+i+"<input type='checkbox' name='chk[]' class='check' id='check_"+i+"'><br />");
}
})
$(document).on("click",".check",function(){
var checked = $(".check:checked").length
if(checked > 5){
alert("Maximum 5");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class='test'>
</div>
You can try something like this:
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 10) {
$(this).prop('checked', false);
alert("Only 10 selection is allowed");
}
});
This code is unchecking previous checkbox if checked input's length more than 10:
$('input[type="checkbox"]').on('click', function(){
var max=0;
var t=$(this);
$('input[type="checkbox"]:checked').each(function(){
if($(this).data('oops')>max){
max=$(this).data('oops');
}
});
t.data('oops', (max+1));
if($('input[type="checkbox"]:checked').length>10){
$('input[type="checkbox"]:checked').each(function(){
if($(this).data('oops')==max){
$(this).prop('checked', false);
}
});
}
});
Without adding global variable.
See
This works:
// these are global variables
var checkBoxChecks = 0;
var maxChecks = 10;
$('input[type="checkbox"]').on('click', function()
{
// if the currently clicked checkbox is now checked
if(this.checked)
{
if(checkBoxChecks < maxChecks) checkBoxChecks++;
else
{
this.checked = false;
alert("You have reached the maximum amount of " + maxChecks + " checks.");
}
}
else checkBoxChecks--;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />

By clicking on box1 change value from box2

I need your help, I'm looking for a solution of:
There is a form with several checkboxes, but only 4 of them are important. Here the html code from this 4:
<input name="opt[pool]" id="opt_pool" type="checkbox" class="searchval" value="1" onclick="submit_search()">Pool
<input name="opt[ppool]" id="opt_ppool" type="checkbox" class="searchval" value="1" onclick="submit_search()">PPool
<input name="opt[internet]" id="opt_internet" type="checkbox" class="searchval" value="1" onclick="submit_search()">Internet
<input name="opt[internetw]" id="opt_internetw" type="checkbox" class="searchval" value="1" onclick="submit_search()">InternetW
Here is the jQuery code:
function build_search(skip){
var sparam = '';
var fields = {};
$('.searchval').each(function(index){
if($(this).attr('name')==skip) {}
else if($(this).attr('type')=='checkbox'||$(this).attr('type')=='radio'){
if($(this).prop("checked")){
sparam+=$(this).attr('name')+"="+$(this).attr('value')+"&";
fields[$(this).attr('name')] = $(this).attr('value');
}
}
else if($(this).val()!=undefined&&$(this).val()!=''){
sparam+=$(this).attr('name')+"="+$(this).val()+"&";
fields[$(this).attr('name')] = $(this).val();
}
});
}
Now I would like to intervene - when clicked on pool, this checked with val=1 and ppool unchecked with val=0. And reverse when click on ppool htis checked with val=1 and pool unchecked with val=0.
This works with my code:
var boxesP = $('#opt_pool,#opt_ppool').click(function(){
boxesP.not(this).prop('checked', false);
$("#opt_pool").val( $("#opt_pool")[0].checked ? "0" : "1" );
$("#opt_ppool").val( $("#opt_ppool")[0].checked ? "0" : "1" );
});
But the problem is when i click to other checkboxes, the checked pool with val=1, remains checked but the val=0.
Where is my mistake? Thanks.
I noticed you have an existing onClick function. Would something like this work for you?
<input name="opt[pool]" id="opt_pool" type="checkbox" class="searchval" value="0" onclick="submit_search(this)">Pool
<input name="opt[ppool]" id="opt_ppool" type="checkbox" class="searchval" value="0" onclick="submit_search(this)">PPool
submit_search = function(e){
if($(e).attr('checked') == 'checked'){
$('.searchval').attr('checked',null);
$('.searchval').val(0);
$(e).attr('checked','checked');
$(e).val(1);
}else{
$(e).val(0);
}
}

How to check specific number of checbox and disable remaining using jquery?

In a specific DIV having .vipGuests that have multiple checkboxes (More than 12), I want to select maximum 12 checkboxes.
As soon as user select 12th checbox then remaining checkbox will get disabled.
My below mentioned code is only counting number of checkbox that are checked. How I can implement the functionality so that user can check maximum 12 checkbox and remaining will get disabled.
$('.vipGuests input[type=checkbox]').on('change', function () {
var totalGuest = 0;
$('.vipGuests input[type=checkbox]:checked').each(function () {
totalGuest++;
});
});
Note: The main thing is that each time during check/uncheck when counter of Checkboxes that are checked is 11 then all checkbox will be active. Only when counter is equals to 12 then the only unchecked checboxes will get disabled.
You can use :not() selector and select un-checked checkbox and disable them. Also you don't need to use .each() to get count of checkbox. Use length property instead.
$(".vipGuests :checkbox").on("change", function(){
if ($(".vipGuests :checkbox:checked").length >= 3)
$(".vipGuests :checkbox:not(:checked)").prop("disabled", true);
else
$(".vipGuests :checkbox:not(:checked)").prop("disabled", false);
});
$(".vipGuests :checkbox").on("change", function(){
$(".vipGuests :checkbox:not(:checked)").prop("disabled", $(".vipGuests :checkbox:checked").length >= 3);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vipGuests">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
You can simply rely on length of jQuery object to check if 12 items are selected.
Use :not(:checked) selector for disabling non-checked inputs.
var $checkboxes = $('.vipGuests input[type=checkbox]');
$checkboxes.on('change', function() {
if ($checkboxes.filter(":checked").length >= 12) {
$checkboxes.filter(":not(:checked)").prop("disabled", true);
} else {
$checkboxes.prop("disabled", false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vipGuests">
<input type="checkbox" checked/>1
<input type="checkbox" checked/>2
<input type="checkbox" checked/>3<br/>
<input type="checkbox" checked/>4
<input type="checkbox" checked/>5
<input type="checkbox" checked/>6<br/>
<input type="checkbox" checked/>7
<input type="checkbox" checked/>8
<input type="checkbox" checked/>9<br/>
<input type="checkbox" checked/>10
<input type="checkbox" checked/>11
<input type="checkbox" />12<br/>
<input type="checkbox" />13
<input type="checkbox" />14
<input type="checkbox" />15
</div>
You can use a global variable as below:
var totalGuest = 0;
$(".vipGuests :checkbox").on("change", function(){
this.checked?totalGuest++:totalGuest--;
$checkboxes.filter(":not(:checked)").prop("disabled", (totalGuest>=12)?true:false);
});
Hope this will help you.
JSFiddle Link
Code:
var totalGuest = 0;
$('div input[type=checkbox]').not(":radio,:submit").on('change', function () {
$(this).toggleClass("active");
if($(this).hasClass("active")) {
totalGuest ++;
}
else {
totalGuest --;
}
if(totalGuest >= 12) {
$('input[type=checkbox]').not(".active").attr("disabled","disabled");
}
else {
$('input[type=checkbox]').not(".active").removeAttr("disabled");
}
});

changing the checked attribute of checkbox using jquery

I have to control the checked status a list of checkboxes from another checkbox.
HTML:
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" name="recipe.read" type="checkbox" value="1" rel="read">
<input id="group.read" name="group.read" type="checkbox" value="1" rel="read">
<input id="ingredients.read" name="ingredients.read" type="checkbox" value="1" rel="read">
</div>
JS:
$('#readall').click(function()
{
var checkStatus = $(this).is(':checked');
var checkboxList = $('#permGrid input[rel="read"]');
$(checkboxList).attr('rel', 'read').each(function(index)
{
if(checkStatus == true)
{
$(this).attr('checked', 'checked');
console.log($(this).attr('checked'));
}
else
{
$(this).removeAttr('checked').reload();
console.log($(this).attr('checked'));
}
});
});
The above code seems fine but the check/uncheck works only for the first time. But when I click the main checkbox second time, it doesn't change the status of other checkboxes into 'checked'. Is there anything I need to do?
I found something similar here. I compared the code and mine and this code is somewhat similar but mine doesn't work.
Try using prop, and shorten the code alot like this
$('#readall').click(function () {
var checkboxList = $('#permGrid input[rel="read"]')
checkboxList.prop('checked', this.checked);
});
DEMO
You can't use a method .reload like this
$(this).removeAttr('checked').reload();
// returns Uncaught TypeError: Object #<Object> has no method 'reload'
Remove it, and it will work.
JSFiddle
Use a class for all the checkboxes which you need to change on click of some checkbox. Like:
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
I have added a class="toChange" to all the checkboxes except the first one.
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
<input id="group.read" class="toChange" name="group.read" type="checkbox" value="1" rel="read" />
<input id="ingredients.read" class="toChange" name="ingredients.read" type="checkbox" value="1" rel="read" />
</div>
Then use the following script:
$('#readall').click(function(){
var checkStatus = $(this).is(':checked');
if(checkStatus){
$(".toChange").attr('checked', 'checked');
}
else{
$(".toChange").removeAttr('checked')
}
});
Demo

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