jQuery not() selector problem
I have a depended radio groups, where by clicking on input#radio10, input#radio16 .form-block-cms should slide down. And no problems with that.
Problem is when I select input#radio16. form-block-cms slides down and back up straight away. I tried to use cond statements else if input#r开发者_StackOverflow社区adio16 not selected, but it is still doing this.
How can I get around it please?
if ($('input#radio10, input#radio16').is(':checked')) {
$('.rsform-block-cms').slideDown().addClass('additionalField')
}
else if ($('input#radio16').not(':checked')) {
$('.rsform-block-cms').slideUp();
};
.not()
filters elements (but still returns a jQuery object, so it'll be ~= true), what you need instead is !
and .is()
, like this:
!$('input#radio16').is(':checked')
Or a bit simpler:
if ($('#radio10, #radio16').is(':checked')) {
$('.rsform-block-cms').slideDown().addClass('additionalField')
} else if (!$('#radio16')[0].checked) {
$('.rsform-block-cms').slideUp();
}
You may also want to use variables, so that you don't search for the same element twice...
var radio10 = $("#radio10")[0] || {};
var radio16 = $("#radio16")[0] || {};
var $rsfrom = $("#.rsform-block-cms");
if ( radio10.checked && radio16.checked ) {
$rsform.slideDown().addClass("additionalField");
} else if ( !radio16.checked ) {
$rsform.slideUp();
}
Not only does this have better performance, but it's also more readable :)
精彩评论