Only one checbox checked with possibility check checkbox by div - javascript

I have several checkboxs on site. This checkboxs can be check by div too, but only one checkbox can be check at a time. That is the problem. When I want click on checbox by div - it works.
When I want only one checbox checked at a time - it works. But when I want both functions at once - it doesn't.
So here is code (for example):
<div class="sth">
<input type="checkbox" class="myCheck"><label>blabla</label>
</div>
<div class="sth">
<input type="checkbox" class="myCheck"><label>blabla</label>
</div>
<div class="sth">
<input type="checkbox" class="myCheck"><label>blabla</label>
</div>
And jQuery:
$("div.sth").on("click",function(event) {
var target = $(event.target);
if (target.is('input:checkbox')) return;
var checkbox = $(this).find("input[type='checkbox']");
if( !checkbox.prop("checked") ){
checkbox.prop("checked",true);
} else {
checkbox.prop("checked",false);
}
});
$('input:checkbox').on('change', function() {
$('input:checkbox').not(this).prop('checked', false);
});

Updated fiddle.
You should add the following line :
$('input:checkbox').not(this).prop('checked', false);
In your "div.sth" click event to uncheck the other checkboxes first then select the one related with clicked div.
Hope this helps.

Have you considered using radio buttons instead and just styling them with CSS to look however you want?
Otherwise use the other answer, mine second portion of this was me misunderstanding the goal.

Related

How to check if every checkbox in different tabs are checked?

I'm working on a project with Java as the backend tech, JSPs and JS with jQuery on the frontend. I'm new to JS and jQuery or at least I'm no pro so I'm trying to do my best here.
So the thing is: I have this screen I'm working on, it shows two users or more and some information related to them. Each user (and its information) is on a different tab. Each user/tab has a checkbox that MUST be checked in order to go to the next screen. So if we have two users, both checkboxes MUST be checked. If we have five, all five of them. The screen is something like this (keeping in mind that the pink one is the selected user):
So the thing is, sometimes, my logic works well and I can move on to the next screen after checking all the checkboxes. But other times after refreshing the page, as I discovered using some console.logs, the checkbox on the first user is executing the code for all the checkboxes while the rest of the checkboxes are not doing anything. So I can't go on to the next screen unless I check the box in all the users and the first one last. The same happens if I uncheck a checkbox on the second user, it's not doing anything because its code is not executing.
I have a JS function on change that checks if all the checkboxes are checked in order to show the arrow to the next screen. Like this:
$("#demPricesCheckbox").change(function () {
var checkboxes = document.querySelectorAll("[id='demPricesCheckbox']");
var show = true;
for (var i = 0; i < checkboxes.length && show; i++) {
if (!checkboxes[i].checked) show = false;
}
if (show) {
ContractPrices.showForwardButton();
} else {
ContractPrices.hideForwardButton();
}
});
And my checkbox HTML reads as follows:
<label class="sub-checkbox" style="margin-left: 100px; margin-top: 5px">
<input
type="checkbox"
id="demPricesCheckbox"
name="demPricesCheckbox"
value="1"
/>
<branches:message code="NAME_OF_CHECKBOX" />
</label>
Any hints? I would appreciate any ideas or explanations on why this could be happening. If you need more info just ask me.
Thank you for your time! And pardon my bad English!
Your logic is close, but there are a few things to keep in mind.
HTML elements should have unique id attributes, meaning that you should never have more than 1 element with the same id on any page.
You should check the "state" of your user interface on every interaction – this is the foundation of reactive programming, and something that jQuery/React/Vue makes easy.
I've written and annotated some code that should help clarify.
// You have jQuery installed, so let's use that instead of vanilla
// This is a CSS selector for "all checkboxes in the DOM".
$("input[type='checkbox']").change(() => {
// Count how many checkboxes you have on the page
// You can use a different method
const totalNumberOfCheckboxes = $("input[type='checkbox']").length;
let countChecked = 0;
// Now, let's loop through them all and see if they are all checked
$("input[type='checkbox']").each((index, element) => {
// Increase the counter only if the checkbox is checked
if (element.checked) {
countChecked += 1;
}
});
// Now, let's check if they are all checked!
if (totalNumberOfCheckboxes === countChecked) {
// Enable your button
console.log("Enabling the next button");
$(".btn.next").removeAttr("disabled");
} else {
// Disable the button
console.log("Disabling the next button because all the checkboxes are not checked.");
$(".btn.next").attr("disabled", "disabled");
}
});
// Next button click listener
// This will only trigger when clicked, and the button is "enabled" – i.e.: not "disabled"
$(".btn.next").click(() => {
console.log('Go to the next page :)')
// This is just for the example – it disables all the checkboxes again
$("input[type='checkbox']").each((index, element) => {
element.checked = false;
});
});
// Setup
// This is not waiting for events, so it will run
// when the page is loaded
console.log("Disabling the next button because the page has just been loaded");
$(".btn.next").attr("disabled", "disabled");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input id="user1" type="checkbox" />
<label for="user1">User 1</label>
</div>
<div>
<input id="user2" type="checkbox" />
<label for="user2">User 2</label>
</div>
<div>
<input id="user3" type="checkbox" />
<label for="user3">User 3</label>
</div>
<button class="btn next">Next</button>

How to uncheck all checkboxes except the one using jQuery?

I have a form that has multiple checkbox groups.
Each checkbox option has a custom html 5 attribute called itemtype. When the input of type="checkbox" changes, I need to evaluate the checkbox that was just selected. If the value of it's data-itemtype is equal to 'Skipper', I want to uncheck all other checkboxes that belong to the same group.
In other words, assume that I have multiple checkboxes and one of the checkbox options has a label called "None", if the user checks "None", Nothing should be selected but "None". I can't use a radio button here as I want the user to be able to check multiple options if "None" is not selected.
Here is a break down of my code
CHECKBOX GROUP 1
<input name="control_307[0][307:1003]" id="item_307_1003_0" value="307:1003" data-itemtype="Answer" type="checkbox"> Zulauf Ltd<br>
<input name="control_307[0][307:361]" id="item_307_361_0" value="307:361" data-itemtype="Answer" type="checkbox"> Ziemann, McLaughlin and Kohler
<input name="control_307[0][308:1013]" id="item_307_1013_0" value="308:1013" data-itemtype="Skipper" type="checkbox"> None<br>
CHECKBOX GROUP 2
<input name="control_1000[0][1000:999]" id="item_1000_999_0" value="307:1003" data-itemtype="Answer" type="checkbox"> First Options<br>
<input name="control_1000[0][1000:666]" id="item_1000_666_0" value="1000:666" data-itemtype="Answer" type="checkbox"> Some other option
<input name="control_1000[0][1000"123]" id="item_1000_123_0" value="308:1013" data-itemtype="Skipper" type="checkbox"> None<br>
I have create a fiddle to show you what I have done along with the entire form https://jsfiddle.net/8yf0v3xt/13/
I tried to do something like this but is is not working
$(:checkbox).change(function(){
var skipper = $("input:checkbox[data-itemtype='Skipper']");
if( skipper.is(":checked")){
$(this).attr('checked', false); //uncheck all the boxes for the current group
skipper.attr('checked', true); //re-check the box that caused everything to uncheck
}
}).change();
What can I do to unckecl all the option if "None" is selected?
Hope this would work for you
$(:checkbox).change(function(){
var skipper = $("input:checkbox[data-itemtype='Skipper']");
if( skipper.is(":checked")){
//$(":checkbox").attr('checked', false); //uncheck all the boxes for the current group
//skipper.attr('checked', true); //re-check the box that caused everything to uncheck
$(":checkbox").not(skipper).prop("checked",false);//THIS IS IMPORTANT
}
}).change();
UPDATE
WORKING FIDDLE
UPDATE 2
WORKING FIDDLE 2
$(:checkbox).change(function(){
var skipper = $("input:checkbox[data-itemtype='Skipper']");
if( skipper.is(":checked")){
//$(":checkbox").attr('checked', false); //uncheck all the boxes for the current group
//skipper.attr('checked', true); //re-check the box that caused everything to uncheck
//$(":checkbox").not(skipper).prop("checked",false);//THIS IS IMPORTANT
//THIS IS IMPORTANT
$(this).closest(".survey-control-fieldset").find(":checkbox").not(skipper).prop("checked",false);
}
}).change();
UPDATE 3
WORKING FIDDLE 3
$(:checkbox).change(function(){
var skipper = $("input:checkbox[data-itemtype='Skipper']");
if( skipper.is(":checked")){
//$(":checkbox").attr('checked', false); //uncheck all the boxes for the current group
//skipper.attr('checked', true); //re-check the box that caused everything to uncheck
//$(":checkbox").not(skipper).prop("checked",false);//THIS IS IMPORTANT
//THIS IS IMPORTANT
$(this).closest(".survey-control-fieldset").find(":checkbox").not(skipper).prop("checked",false);
}
else
{
$(this).closest(".survey-control-fieldset").find(":checkbox[data-itemtype='Skipper']").prop("checked",false);
}
}).change();
CONCLUSION
Few points I noticed wrong in your code are as follows.
You were using $(this).attr("checked",false); to uncheck all
checkboxes which is wrong. $(this) points to CURRENT SINGLE
ELEMENT only, not all.
You were using .attr("checked",false) which is also incorrect, it
should be either .attr("checked","checked") or
.prop("checked",true).

How to disable one radio input from radio group?

How can i disable the one radio input from the radio group ?
<input type="radio" name="radiogrp" value="op1" checked="checked">Option1
<input type="radio" name="radiogrp" value="op2"> Option2
<input type="radio" name="radiogrp" value="op3" > Option3
<input type="radio" name="radiogrp" value="op4"> Option4
My question is i want to disable option1 after clicking on any other button
For example:
when i select option2, than option1 should be disabled
Check this Fiddle I have just added
Let me know if this is not what you intended
As requested - posted fiddle answer
$('.rd').click(function(){
$('.rd[value="op1"]').attr('disabled', 'disabled');
});​
Try
$('input[value="op2"]').click(function(e)
{
$('input[value="op1"]').attr('disabled', 'disabled');
});
http://jsfiddle.net/3CdZU/
$(":radio").change(function(){
$(":radio[name='radiogrp']").slice(0,1).attr("disabled","disabled");
});
DEMO
var radios = $('input[type="radio"][name="radiogrp"]');
radios.change(function() {
if (this.value != "op1") {
radios.filter('[value="op1"]').prop('disabled', true);
}
});​
I cached the radio buttons, so I don't need to Query the DOM twice.
DEMO
Since, after the change, there is no way back, this is more fun way:
var radios = $('input[type="radio"][name="radiogrp"]');
var first = $('input[type="radio"][name="radiogrp"][value="op1"]');
radios.not(first).change(function() {
alert('changed'); // getting called only once.
first.prop('disabled', true);
radios.unbind('change');
});​
LIVE DEMO
I am using jquery mobile with fancy dynamic styling, and I found that after performing the disable, I needed to explicitly issue an refresh using the checkboxradio("refresh") method call so that the styling would reflect the change. You can chain the method call, though, so it might look like this:
$('.rd').click(function(){
$('.rd[value="op1"]').attr('disabled', 'disabled').checkboxradio("refresh");
});​
http://view.jquerymobile.com/1.3.2/dist/demos/faq/updating-the-value-of-enhanced-form-elements-does-not-work.html
While I appreciate gdoron's deeper, more technical, more efficient, more comprehensive approach, I believe that sometimes (just sometimes) the easier reading and shorter coding of Jibi Abraham's approach is warranted, especially in an otherwise lightweight situation.
I realize this isn't a distinct answer, but I don't have enough reputation to do a comment yet.
Its very easy, use jQuery's attribute selector. Here is an example of disabling the radio button with value op3
$('input[value="op3"]').attr('disabled', 'disabled');
Demo
Here is your solution
var radios = $('input[name=radiogrp]'); //Cache all the radio button
radios.click(function() {
//Attach a function to the click event of all radio button
if(this.value!='op1') { //Check if currently click button has value of op1
radios.filter('[value="op1"]').prop('disabled', true); //if not disable the first
}
});
Demo

jQuery and If statement to de-select radio buttons

Well, I'm stuck and have been banging my head for a little while now to try to figure what I'm doing wrong.
Scenario:
I have a question with a Yes/No answer (ie 2 radio buttons). When a user selects the either Yes or No, I call a function to .toggle() a hidden div to show a link. That works great. And if they go back and check that Yes/No again it disappears again due to the .toggle()
My issue is that if a user clicks the No (and the link is shown) but then clicks the Yes I want the link that is showing due to the No result to disappear and vice-versa.
So basically only show 1 link at a time.
I figured that maybe an If statement would work but I can't seem to get it right.
My code:
<div id="Question1">
<div>Do you kazoo?</div>
<input type="radio" ID="Q1RB1" runat="server" value="Yes" text="Yes" name="RadioGroup1"/>Yes<br />
<input type="radio" ID="Q1RB2" runat="server" value="No" text="No" name="RadioGroup1"/> No
<span id="Q1RB1Results" style="display:none"> <a href=#>Click here</a></span>
<span id="Q1RB2Results" style="display:none"> <a href=#>Click here</a></span>
</div>
My jQuery code that works for each individual radio button:
$("input[id$=Q1RB1]:radio").change(function () {
$("[id$=Q1RB1Results]").toggle();
});
$("input[id$=Q1RB2]:radio").change(function () {
$("[id$=Q1RB2Results]").toggle();
});
This is the If statement I'm trying to get to work. Amy I going about this the wrong way?
if ($("input[id$=Q1RB2]").is(":checked")) {
$("input[id$=Q1RB2]:radio").change(function () {
$("[id$=Q1RB2Results]").toggle();
});
});
Thanks for any thoughts/advice. I've tried a multitude of answers here in Stackoverflow and the 'net but can't seem to figure out what I'm doing wrong. :(
~V
Update: I put a sample form and the dialogue up on JSFiddle. http://jsfiddle.net/Valien/7uN6z/4/ I tried some of the solutions mentioned here and couldn't get them working so not sure what I'm doing wrong.
When you register an event listener in JQuery (.change, .click, .blur, etc.), the Javascript engine matches the selector and applies them at that point. With that in mind, you can rearrange your code (which is close to being right) to this, which should do the trick:
/* The function you're about to define applies to all radio button
inputs whose ID ends with Q1RB2 */
$("input[id$=Q1RB2]:radio").change(function()
{
/* Inside the change function, $(this) refers to the instance that
was changed. So, this checks to see if the instance that was just
changed is currently checked, after being changed. */
if ($(this).is(":checked"))
{
// If that was the case, then toggle the item
$("[id$=Q1RB2Results]").toggle();
}
});
Try this:
$('input:radio[name=RadioGroup1]').change(function(){
var show = "#" + $(this).attr('id') + 'Results';
$('#Question1 span').hide();
$(show).show();
});
I believe this is what you need:
// declare common variables so it's easier to target
var question = $("#Question1"),
group = question.find("input[name='RadioGroup1']"),
span = question.find("span");
// change listener for each radio button group
group.click(function(){
var id = $(this).attr("id"); // get the radio button id for reference
span.each(function(){ // loop through each span and check which one to hide/show
var item = $(this);
if (item.attr("id")===id+"Results") { item.show(); } else { item.hide(); }
});
});

select all checkboxes command jquery, javascript

I'm trying to get all of my checkboxes to be checked when clicking a link
looks like this: select all
inputs in a loop: <input type="checkbox" name="delete[$i]" value="1" />
jquery code:
var checked_status = this.checked;
$("input[name=delete]").each(function() {
this.checked = checked_status;
});
Can someone help me get it to check all.. ?
When clicking at the select all link, nothing seems to happen.. (not even an error)
Try the following.
Updated. The handler is tied to an anchor therefore there will be no this.checked attribute available.
$("#select_all").click(function(){
$("input[name^=delete]").attr('checked', 'checked');
});
jQuery Tutorial: Select All Checkbox
You're going to want to use the [name^=delete] selector ("starts with"), since your checkboxes names aren't exactly "delete", they're "delete[X]' for some number X.

Categories