开发者

Clear val on toggle with boolean

开发者 https://www.devze.com 2023-02-25 17:42 出处:网络
I have a hidden div with form elements in it that I toggle on a radio select option (Think yes/no as the options)

I have a hidden div with form elements in it that I toggle on a radio select option (Think yes/no as the options)

If they select yes, display the div and require the fields, e开发者_开发问答lse hide div and clear the fields (if they have entered any value).

I can do all of this except clear the value with passing a boolean flag to the toggle function

Example:

$("[name=nameOfElement]").change(function() {
    var show = $('input[name=nameOfElement]:checked').val() == "true";
    $('#hiddenForm').toggle(show);
    $('#hiddenInput').toggleClass('required',show);
});

Is there something that clears the value on passed boolean option?

$("[name=nameOfElement]").change(function() {
    var show = $('input[name=nameOfElement]:checked').val() == "true";
    $('#hiddenForm').toggle(show);
    $('#hiddenInput').toggleClass('required',show).valClear(show);
});

UPDATE: Not looking for a plugin just wanted to know if I could do this without the if/else condition


Maybe

$("[name=nameOfElement]").change(function() {
var show = $('input[name=nameOfElement]:checked').val() == "true";
$('#hiddenForm').toggle(show);
$('#hiddenInput').toggleClass('required',show).val(show ? $('#hiddenInput').val() : '');
});


You could attach multiple change handlers:

$("[name=nameOfElement]").change(function() {
    var show = $('input[name=nameOfElement]:checked').val() == "true";
    $('#hiddenForm').toggle(show);
    $('#hiddenInput').toggleClass('required',show);
});
$("[name=nameOfElement]").change(function() {
    if($('input[name=nameOfElement]:checked').val() == "true")
        $('#hiddenInput').val('');
});

But that looks worse than using just one handler with a conditional to me. You could also whip up your own little plugin to add something like your valClear:

(function($) {
    $.fn.clearIf = function(clearIt) {
        if(clearIt)
            this.each(function() { $(this).val(''); });
        return this;
    };
})(jQuery);

And then:

$("[name=nameOfElement]").change(function() {
    var show = $('input[name=nameOfElement]:checked').val() == "true";
    $('#hiddenForm').toggle(show);
    $('#hiddenInput').toggleClass('required',show).clearIf(!show);
});

I'd go with Ron's ternary approach if I was just doing this in one place though.

0

精彩评论

暂无评论...
验证码 换一张
取 消