I'm using the jQuery Validate plug-in and need to require a field if a certain radio button is checked. How can I determine if a certain country is selected?
For example, if the Canada radio button is checked, then require this field. This isn't right, but it's something along these lines:
depends: function(element) {
return $("input[name='country'],[value='ca'],:checked")
}
UPDATE:
I'm using #Tatu Ulmanen's code, however I'm receiving the following error after clicking outside of one of the fields that should be required when "Canada" is checked. Any ideas?
province: {
depends: function(element) {
return $("input[name='country'][value='ca']").is(':checked')
}
},
$.validator.methods[method] is
undefined [Break On This Error]
eval(function(p,a,c,k,e,d){e=function(...x5b|trigger|x21|x23'.split('|'),0,{}))
$("input[name='country'][value='ca']").is(':checked');
You can use the .is() method:
$("input[name='country'][value='ca']").is(':checked');
$("input[name='country'],[value='ca']").is(':checked');
here's a way:
if ($('#id').is(':checked')) {
alert('button is checked');
}
As well as using .is(), jQuery 1.6 introduced .prop(), see
http://api.jquery.com/prop/ for details.
Related
I need to check if a checkbox next to a textbox is checked or not, but the result I'm getting from that condition in my code is always true, so that's wrong.
I've made some tests using the next() method from jQuery. I'm pointing to the next checkbox close to the textbox, which is working fine.
This code is always returning true, whether the checkbox is checked or not:
if ($(this).next('.isFileSelected:checkbox:checked')) {
//do some other stuff...
}
I tried these changes too, but I'm getting the same results:
if ($(this).next('input:checkbox:checked')) {
//do some other stuff...
}
How can I accomplish this using jQuery or pure JavaScript code?
You're looking for the prop() attribute checked:
if ($(this).next('.isFileSelected:checkbox').prop('checked')) {
// Checked
}
Or, alternatively, you can use .is() to check for the :checked pseudo-selector:
if ($(this).next('.isFileSelected:checkbox').is(":checked")) {
// Also Checked
}
Hope this helps! :)
I am using metronic admin theme for one of my project.
http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469
I have to checked or unchecked check boxes on base of data from database but problem is that i am unable to checked or unchecked a check box in metronic theme using jquery. I have tried both ways to accomplish this task using prop and attr but nothing is working for me. If I run the same code on my custom web page it's working perfectly fine.
$("#checkbox").prop("checked",true);
$("#checkbox").attr('checked',false);
$("#checkbox").attr('checked','checked');
If you are using metronic, try adding this line after the prop:
$.uniform.update();
Metronic theme uses uniform library to modify standard form element into fancy element. If you check or uncheck element using jquery, it is updated but it is not reflected on front-end. To update this action on front-end you need to update using uniform library.
$.uniform.update() restyles the element depending on updated action.
Best way for this problem add class for input checkbox when you are using in Angular Js loop.
This works perfectly:
I also use the metroic theme,but no such problems:
I think the problem maybe is your 'unchecked' and 'checked' is not matching;my meaning is:you should
var checked = $(this).is(":checked");
$.each(function() {
if (checked) {
$(this).prop("checked", true);//or $(this).attr("checked", true);
} else {
$(this).prop("checked", false);//or $(this).attr("checked", false),can't use $(this).removeAttr('checked');
}
});
if you use removeAttr,you should
$(this).attr('checked', 'checked');
$(this).removeAttr('checked');
if above all it don't work ,you can try:
$(this)[0].checked=true;// when I use ,find return array,so add [0];
$(this)[0].checked=false;
$(this).iCheck('uncheck');
or
$(this).iCheck('check');
can be found here
I have ajax response containing two radio element.i want to check if radio element is checked in response.
I m using below code to check radio status but not working.
$('#input[type=radio]').each(function(){
alert($(this).attr('checked'));
});
as i know this is not working due to ajax response. but how to fire js code to check even in ajax resoponse.
any help would be much appreciate.
try this:
$(document).find('input[type="radio"]').each(function(){
if($(this).is(':checked')){
//your code
}
});
Try this
$('#input[type=radio]').each(function(){
if($(this).is(':checked')){
}
});
use prop
$('input[type=radio]').each(function(){
alert($(this).prop('checked'));
});
and #input only if your radio have id="input". if you want check all radio, could be only
input[type=radio]
as the example
Your issue is your selector which contains # for id:
$('#input[type=radio]')
//-^------------------------# is used to select an id not the tags
try this:
$('input[type="radio"]').each(function(){
alert(this.checked); // returns "true" if checked/ "false" if not checked
});
I used the following solution for a mailer form for my JQuery Mobile site:
http://eisabainyo.net/weblog/2011/06/29/creating-a-contact-form-in-jquery-mobile-and-php/
Everything works fine, except the "required" function does not properly parse values for HTML "select" elements:
$('.required', $contactform).each(function (i) {
if ($(this).val() === '') {
error++;
}
}); // each
In other words, whenever I add the class "required" to a "select" form element, the form will not submit because it always triggers the error "Please fill in all the mandatory fields. Mandatory fields are marked with an asterisk" regardless of what item is selected.
Source article is from June 2011, so my guess is that this function doesn't work with my version of JQuery (1.8.3) or JQM (1.3.2).
I'm not a Javascript expert, and this article unfortunately provides little documentation as to how exactly this function works. Any suggestions?
Use this instead of the line that you have:
$('.required', $contactform).not('span').each(function (i) {
I've got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.
When enabled, the values in these textboxes are required to be a valid number, but when disabled they don't need a value (obviously). I'm using the jQuery Validation plugin to do this validation, but it doesn't seem to be doing what I expect.
When I click the checkbox and disable the textbox, I still get the invalid field error despite the depends clause I've added to the rules (see code below). Oddly, what actually happens is that the error message shows for a split second then goes away.
Here is a sample of the list of checkboxes & textboxes:
<ul id="ItemList">
<li>
<label for="OneSelected">One</label><input id="OneSelected" name="OneSelected" type="checkbox" value="true" />
<input name="OneSelected" type="hidden" value="false" />
<input disabled="disabled" id="OneValue" name="OneValue" type="text" />
</li>
<li>
<label for="TwoSelected">Two</label><input id="TwoSelected" name="TwoSelected" type="checkbox" value="true" />
<input name="TwoSelected" type="hidden" value="false" />
<input disabled="disabled" id="TwoValue" name="TwoValue" type="text" />
</li>
</ul>
And here is the jQuery code I'm using
//Wire up the click event on the checkbox
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
textBox.valid();
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
});
//Add the rules to each textbox
jQuery('#ItemList :text').each(function(e) {
jQuery(this).rules('add', {
required: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
},
number: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
}
});
});
Ignore the hidden field in each li it's there because I'm using asp.net MVC's Html.Checkbox method.
Using the "ignore" option (http://docs.jquery.com/Plugins/Validation/validate#toptions) might be the easiest way for you to deal with this. Depends on what else you have on the form. For i.e. you wouldn't filter on disabled items if you had other controls that were disabled but you still needed to validate for some reason. However, if that route doesn't work, using an additional class to filter on (adding and removing with your checkboxes) should get you to where you want to go, but easier.
I.e.
$('form').validate({
ignore: ":disabled",
...
});
Usually when doing this, I skip 'depends' and just use the required jQuery Validate rule and let it handle the checking based on the given selector, as opposed to splitting the logic between the validate rules and the checkbox click handler. I put together a quick demo of how I accomplish this, using your markup.
Really, it boils down to required:'#OneSelected:checked'. This makes the field in question required only if the expression is true. In the demo, if you submit the page right away, it works, but as you check boxes, the form is unable to submit until the checked fields are filled with some input. You could still put a .valid() call in the checkbox click handler if you want the entire form to validate upon click.
(Also, I shortened up your checkbox toggling a bit, making use of jQuery's wonderful chaining feature, though your "caching" to textBox is just as effective.)
Depends parameter is not working correctly, I suppose documentation is out of date.
I managed to get this working like this:
required : function(){ return $("#register").hasClass("open")}
Following #Collin Allen answer:
The problem is that if you uncheck a checkbox when it's error message is visible, the error message doesn't go away.
I have solved it by removing the error message when disabling the field.
Take Collin's demo and make the following changes to the enable/disable process:
jQuery('#ItemList :checkbox').click(function()
{
var jqTxb = $(this).siblings(':text')
if ($(this).attr('checked'))
{
jqTxb.removeAttr('disabled').focus();
}
else
{
jqTxb.attr('disabled', 'disabled').val('');
var obj = getErrorMsgObj(jqTxb, "");
jqTxb.closest("form").validate().showErrors(obj);
}
});
function getErrorMsgObj(jqField, msg)
{
var obj = {};
var nameOfField = jqField.attr("name");
obj[nameOfField] = msg;
return obj;
}
You can see I guts remove the error message from the field when disabling it
And if you are worrying about $("form").validate(), Don't!
It doesn't revalidate the form it just returns the API object of the jQuery validation.
I don't know if this is what you were going for... but wouldn't changing .required to .wasReq (as a placeholder to differentiate this from one which maybe wouldn't be required) on checking the box do the same thing? If it's not checked, the field isn't required--you could also removeClass(number) to eliminate the error there.
To the best of my knowledge, even if a field is disabled, rules applied to it are still, well, applied. Alternatively, you could always try this...
// Removes all values from disabled fields upon submit
$(form).submit(function() {
$(input[type=text][disabled=disabled]).val();
});
I havent tried the validator plugin, but the fact that the message shows for a splitsecond sounds to me like a double bind, how do you call your binders? If you bind in a function try unbinding just before you start, like so:
$('#ItemList :checkbox').unbind("click");
...Rest of code here...
Shouldn't validate the field after disabling/enabling?
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
textBox.valid();
});
I had the exact same problem.
I solved this by having the radio-button change event handler call valid() on the entire form.
Worked perfect. The other solutions above didn't work for me.