I have more than fifteen checkbox inputs all with the same class, looking something like below:
I want to have only the first input be checked and stay checked when any other input with the same class is checked. If only the first input is checked you should be able to check and uncheck it freely. Only the first one has the ID, #SR01201. The rest only have the class check-12.
Right now, I can freely uncheck and check the first input, and it will get checked if any other inputs with the class check-12 are checked. But once any other input (besides the first one) is checked, it can't be unchecked.
$('.check-12:not(#SR01201)').on('change', function() {
var $this = $(this);
var SRTwelveOne = $("#SR01201");
if ($this.prop('checked', true)) {
SRTwelveOne.prop('checked', true)
} else if ($this.prop('checked', false) && $this.siblings().prop('checked', false)) {
SRTwelveOne.prop('checked', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="SR-012-01" value="SR-12-01" class="check-12" id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" class="check-12">
<input type="checkbox" name="SR-012-03" value="SR-12-03" class="check-12">
The $this.prop('checked', true) in if ($this.prop('checked', true)) is setting the checkbox to true, not checking if it's true. For that you want to use if ($this.prop('checked')). But I think your issue can be reduced to the following:
$('.check-12:not(#SR01201)').on('change', function() {
$("#SR01201").prop('checked', $('.check-12:not(#SR01201):checked').length > 0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="SR-012-01" value="SR-12-01" class="check-12" id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" class="check-12">
<input type="checkbox" name="SR-012-03" value="SR-12-03" class="check-12">
The first line selects your checkboxes with the class you specified, but not the first one. Upon changing any of them, the checkbox with the ID SR01201 changes its checked property depending on how many of the other checkboxes are checked. 1 or more? check it, otherwise uncheck it. The result of $('.check-12:not(#SR01201):checked').length > 0 will be true or false.
The problem is that you're not checking if a checkbox is checked with $this.prop('checked', true) in your if statement. You're actually checking the box. To see if it's a box is checked, use is(":checked")
Related
I have a list of checkboxes:
<input type="checkbox" name="answer" id="id_1' value="1" />
<input type="checkbox" name="answer" id="id_2' value="2" />
...
<input type="checkbox" name="answer" id="id_n' value="n" />
I can collect all the values of checked checkboxes; my question is how can get all the values of unchecked checkboxes? I tried:
$("input:unchecked").val();
to get an unchecked checkbox's value, but I got:
Syntax error, unrecognized expression: unchecked.
Can anybody shed a light on this issue?
Thank you!
As the error message states, jQuery does not include a :unchecked selector.
Instead, you need to invert the :checked selector:
$("input:checkbox:not(:checked)")
$("input:checkbox:not(:checked)") Will get you the unchecked boxes.
Also it can be achieved with pure js in such a way:
var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
You can do so by extending jQuerys functionality. This will shorten the amount of text you have to write for the selector.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
}
);
You can then use $("input:unchecked") to get all checkboxes and radio buttons that are checked.
$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () {
var a = "";
if (this.name != "chkAll") {
a = this.name + "|off";
}
return a;
}).get().join();
This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.
//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).
You can use like this :
$(":checkbox:not(:checked)")
To select by class, you can do this:
$("input.className:checkbox:not(:checked)")
$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
// enter your code here
} });
I have a form with "Does this case have IR number?"
If yes, show fields. If no, hide and show others.
I am using
validate() function.
old() to keep data after failed form submission, aka validate() error messages.
JQuery show/hide for the fields.
For the radio input, I used old() like this:
<input class="btn-check" type="radio" name="checkIR" value="haveIR" #if(!old('checkIR')) checked #endif id="haveIR" required>
<input class="btn-check" type="radio" name="checkIR" value="noIR" #if(old('checkIR')) checked #endif id="noIR">
to keep the checked as it is after failed validate(), but it's buggy, When I check "Yes" and refresh, it checks "No" when it must be as "Yes".
As for the show/hide, here is what I did:
// Show/Hide fields based on radio button option
$(document).ready(function() {
$('input[name="checkIR"]').click(function() {
var inputValue = $(this).attr("value")
var targetField = $("." + inputValue);
$(".box").not(targetField).slideUp();
$(targetField).slideDown();
});
});
With a help of css:
.box {
display: none;
}
How the code works:
If yes/haveIR radio is checked: show all fields containing class="box haveIR"
Issues trying to solve:
How to fix/improve the small bug in the input old()?
If user checked "yes", how to keep the fields of yes visibile even after failed laravel validate()?
Since the radio inputs have the same name, in both cases your session has "checkIR" and when you try to check it with old('checkIR') it will return true regardless of its value. Thats why "No" is checked.
Therefore, in order to find the old selected one, you should check by its value, not whether it exists in the session or not.
Code like this should work for you;
<input class="btn-check" type="radio" name="checkIR" value="haveIR" #if(old('checkIR') == 'haveIR') checked #endif id="haveIR" required>
<input class="btn-check" type="radio" name="checkIR" value="noIR" #if(old('checkIR') == 'noIR') checked #endif id="noIR">
Or;
You can use 0 and 1 for values. Since old('checkIR') will return '0' or '1' and PHP will interpret '0' as false and '1' as true the behaviour will be like you wanted.
And for keeping the related fields visible;
You can run some script when document ready and set related fields visible by input value.
$(document).ready(function() {
var input = $('input[name="checkIR"]:checked');
if (input) { // if any checked radio when document ready
var targetField = $("." + input.val());
$(".box").not(targetField).slideUp();
$(targetField).slideDown();
}
});
Note: didn't run the script, it may have errors but you get the point.
I want to disable and clear a textbox if a checkbox is uncheck and enable it when checked. At the same time, the checkbox should be dependent on the value on the database.
If deductstatus == 1, checkbox should be checked when loaded
If deductstatus == 2, checkbox should be unchecked when loaded
The code below is not working. Any help?
$(".dedstat").click(function() {
if ($(".dedstat").is(":checked")) {
$(".deductto").removeAttr("disabled")
} else {
$(".deductto").attr("disabled", "disabled")
var deductto = document.getElementById("deductto");
deductto.value = "";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat" value="<?php if ($dedstat == 1) echo 'checked'; ?>">
<input type="text" name="deductto" id="deductto" value="<?php echo $deductto;?>">
Checked is not a value, it is an attribute, it should be:
<input type="checkbox" name="dedstat" id="dedstat" value="" <?php if ($dedstat == 1) echo 'checked'; ?>>
When manipulating boolean attributes such as checked, disabled, multiple, you should be using .prop() instead of .attr() or .removeAttr(). Some other suggested improvements:
Use this.checked instead of $(".dedstat").is(":checked"), so that it is context specific
Use the ID selector instead of class
You can chain your jQuery methods, so you can both disable the input and empty its value at the same time
Listen to the change event instead of click for <input> elements
$("#dedstat").change(function() {
if (this.checked) {
$("#deductto").prop("disabled", false)
} else {
$("#deductto")
.prop("disabled", true)
.val('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat">
<input type="text" name="deductto" id="deductto">
If you want the state of the input to be evaluated on pageload, you will also have to perform the same logic without binding it to the onChange event. The best way is to create a function that is called by both the onChange event and DOMready/window.load event. In the example below, the method we create will accept a DOM node as an argument, so that it is contextually aware of which checkbox element you are referring to:
// Method to conditionally enable/disable input
var updateTextInput = function(el) {
if (el.checked) {
$("#deductto").prop("disabled", false)
} else {
$("#deductto")
.prop("disabled", true)
.val('');
}
}
// Call method when change event is fired from checkbox
$("#dedstat").change(function() {
updateTextInput(this);
});
// Call method on DOMready, pass DOM node (not the jQuery object)
updateTextInput($('#dedstat')[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat">
<input type="text" name="deductto" id="deductto">
And with regards to your PHP, you can simply use tenary operators to conditionally write the checked prop to your input element, i.e.:
<input type="checkbox" name="dedstat" id="dedstat" <?php echo $dedstat == 1 ? 'checked' : ''; ?>>
value attribute can not be used to keep it checked or unchecked based on database value. And bind checked or unchecked attribute separately.
So change that tag like this:
<input type="checkbox" name="dedstat" id="dedstat" onclick="isChecked()" value="1" <?php echo (isset($dedstat) && $dedstat == 1)? "checked" : "" ; ?>
More on this,
If you want to store 1 and 2 values to save checked and unchecked condition of the checkbox respectively, then what you should do is, if the checkbox is checked, you will get its value in php $_POST but if it was not checked, you will not get it in $_POST. So in that case, you should store its default value 2 into the DB column. So then only you can get 2 when you fetch its value next time from DB.
Just a little suggestion :
Is your JS at the bottom of the page ?
Plus I just noticed something :
$(".dedstat") <= you're calling a class with the dot. Your imputs have ID's.
$("#dedstat").click(function () {
if ($("#dedstat").is(":checked")) {
$("#deductto")
.removeAttr("disabled")
}
else {
$("#deductto")
.attr("disabled", "disabled")
var deductto = document.getElementById("deductto");
.deductto.value = "";
}
});
It should work a little better.
I want my #pass_through_card checkbox to be unchecked if my #ranged_pricing checkbox is unchecked as you should not be able to check #pass_through_card without having checked #ranged_pricing. The #pass_through_card checkbox does not have to be checked if #ranged_pricing is checked though, which is why I just put "Do Nothing." What am I doing wrong?
HTML
<input type="checkbox" id="ranged_pricing"/>
<label for="ranged_pricing">
Ranged Pricing
</label>
<input type="checkbox" id="pass_through_card">
<label for="pass_through_card">
Pass Through Card Association Dues and Assessments
</label>
Javascript
$(document).ready(function() {
if($('#ranged_pricing').prop(':checked')) {
//Do Nothing
} else {
$('#pass_through_card').removeAttr('checked');
}
});
It's should be just "checked", not ":checked", when you call .prop().
if ($('#ranged_pricing').prop('checked')) {
The ":checked" notation is for use in selector syntax. When you include the ":" in the call to .prop(), the result will always be false.
Try,
if($("#ranged_pricing").prop('checked') === true){
//do nothing
} else {
$("#pass_through_card").prop('checked', false);
}
You may want to bind a checked event to the ranged_pricing as well, to disable the pass_through_card element when it is not checked.
I need to use javascript so that when the one radio button is selected nothing happens but if the other one is (for example, other address) it will then validate the following fields;
street
suberb
postcode
Whilst I post this, it's probably a similar method, but when I have a checkbox and a textbox how could I make it so that the textbox must not be left empty only if the checkbox is checked...
Thanks everyone!!!! Ask for more details if needed, I'm terrible at explaining things!
/* To check radio validation in Employee Details page */
function editPage()
{
var select=document.frmEmployeeDetails.radSelect;
if (radioValidate(select,"Select an Employee"))
{
window.open("EditEmployee`enter code here`.html","_self");
}
return false;
}
Hope this example helps you friend.
Since they will be checking the radio button when they click on it, you can add an onClick event to one of the radio buttons and not the other.
<input type='radio' id='test' name='test-1' />
<input type='radio' id='test' name='test-2'onClick='Validate();'/>
For the checkbox, when a user checks the box you should set the focus to the text input field. That way if a user moves away from that field (onBlur) you can give them an error/alert to fill in the text.
<input type='checkbox' id='testChkbx' name='testChkbx' onClick=' /*Set the focus to the text box*/'/>
<input type='text' id='testText' name='testText' onBlur='/* Check to make sure the value of the checkbox is not empty. */'/>
I'll assume you might be using jQuery, since you didn't say. If not, then you can still take the concepts and port them to plain old javascript or whatever you're using.
Example markup
<form id="address-form">
<input type="radio" name="validate" id="validate_address" value="yes"> Validate<br>
<input type="radio" name="validate" value="no"> Don't Validate<br>
Street <input name="street"><br>
Suberb <input name="suberb"><br>
Postcode <input name="postcode"><br>
<input type="submit">
</form>
Conditional validation
Either somewhere on your page in a <script> tag or in a javascript file you include, create a submit event that will check the value of the radio input before doing the validation.
$('#address-form').submit(function(event) {
if ($('input[name=validate]:checked').val() === 'yes') {
if (!formValid()) {
event.preventDefault(); // Don't submit the form
}
}
});
// Perform validations
function formValid() {
if ($('input[name=street]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=suberb]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=postcode]').val().length == 0) {
// tell them ...
return false;
}
return true;
}
That should do the trick!
I created a jsfiddle you can mess with further if you want - http://jsfiddle.net/nilbus/JNnuX/2/
Using a checkbox instead
It's pretty similar to use a checkbox. Instead of this
if ($('input[name=validate]:checked').val() === 'yes') {
just check to see if your checkbox is checked.
if ($('input[name=validate]').attr('checked')) {
http://jsfiddle.net/nilbus/JNnuX/3/