根据用户输入使用 Jquery 显示/隐藏字段

发布于 2024-11-17 13:18:43 字数 619 浏览 3 评论 0原文

  <li class="numeric optional" id="contest_max_retweet_input"><label for="contest_max_retweet">Winning retweet number</label><input id="contest_max_retweet" name="contest[max_retweet]" size="50" type="text" /></li> 
  <li class="numeric optional" id="contest_numofwinners_input"><label for="contest_numofwinners">Number of winners (1-100)</label><input id="contest_numofwinners" name="contest[numofwinners]" size="50" type="text" /></li> 

如果用户在“contest_max_retweet_input”字段中指定了一个值,如何使用 JQuery 隐藏“contest_numofwinners_input”字段?

  <li class="numeric optional" id="contest_max_retweet_input"><label for="contest_max_retweet">Winning retweet number</label><input id="contest_max_retweet" name="contest[max_retweet]" size="50" type="text" /></li> 
  <li class="numeric optional" id="contest_numofwinners_input"><label for="contest_numofwinners">Number of winners (1-100)</label><input id="contest_numofwinners" name="contest[numofwinners]" size="50" type="text" /></li> 

How can I use JQuery to Hide the field: contest_numofwinners_input if there is a value specified by the user in the field: contest_max_retweet_input?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

地狱即天堂 2024-11-24 13:18:43

您可以尝试类似的操作:

$('#contest_max_retweet').change(
    function(){
    if ($(this).val().length) {
        $('#contest_numofwinners').hide();
    }
    else {
        $('#contest_numofwinners').show();
    }
});

JS Fiddle demo

这仅隐藏 input 元素其本身,不是包含 li 或相应的label 元素。

You could try something like:

$('#contest_max_retweet').change(
    function(){
    if ($(this).val().length) {
        $('#contest_numofwinners').hide();
    }
    else {
        $('#contest_numofwinners').show();
    }
});

JS Fiddle demo

This hides only the input element itself, not the containing li, or corresponding label, element.

相权↑美人 2024-11-24 13:18:43

像这样的东西

$("#contest_max_retweet").change(function() {
   if($(this).val().length) {
      $("#contest_numofwinners").hide();
   }
   else {
      $("#contest_numofwinners").show();
   }
})
.trigger("change");

Something like

$("#contest_max_retweet").change(function() {
   if($(this).val().length) {
      $("#contest_numofwinners").hide();
   }
   else {
      $("#contest_numofwinners").show();
   }
})
.trigger("change");
蓝梦月影 2024-11-24 13:18:43
$('#contest_max_retweet').change(function() {
    if($('#contest_numofwinners').val() != "")
        $('#contest_numofwinners').hide();
});
$('#contest_max_retweet').change(function() {
    if($('#contest_numofwinners').val() != "")
        $('#contest_numofwinners').hide();
});
随风而去 2024-11-24 13:18:43

更改的问题是您必须保留输入(模糊)才能触发该函数。这就是为什么我更喜欢keyup

$("#contest_max_retweet").keyup(function() {
       if($(this).val().length > 0) {
          $("#contest_numofwinners").hide();
       }
       else {
          $("#contest_numofwinners").show();
       }
    });

The problem with change is that you have to leave the input (blur) in order for the function to fire. That's why I prefer keyup.

$("#contest_max_retweet").keyup(function() {
       if($(this).val().length > 0) {
          $("#contest_numofwinners").hide();
       }
       else {
          $("#contest_numofwinners").show();
       }
    });
放肆 2024-11-24 13:18:43

我会根据变化值的否定进行切换。我还将继续并在加载时触发事件处理程序以提供初始显示/隐藏状态(使用名称空间事件以避免导致其他绑定功能执行)。

(编辑:我喜欢布兰登·布恩(Brandon Boone)关于即时操作的按键操作所做的事情,并向我的代码中的事件名称添加了注释。但是,它会增加一点开销,因为该函数针对键盘上的每个笔划运行,如下所示与字段模糊时相反。)

演示:

http://jsfiddle.net/JAAulde/fUKfb/3/

代码:

var namespaced_event = 'change.hideRetweet', //use `keyup.hideRetweet` here to avoid waiting for the input to be blurred
    contest_max_retweet_wrapper = $( '#contest_max_retweet' ).closest( 'li' ); //hides entire input, label, and container--could be pared down if desired

$( '#contest_numofwinners' )
  .bind( namespaced_event, function()
  {
      contest_max_retweet_wrapper.toggle( ! $( this ).val()  );
  } )
  .triggerHandler( namespaced_event );

I would toggle based on negation of value at change. I'd also go ahead and trigger the event handler at load to give an initial show/hide state (using a name-spaced event to avoid causing other bound functionality executing).

(Edit: I like what Brandon Boone did regarding keyup for instant action and added a comment to the event name on my code. It will, however, add a little overhead as the function is run for every stroke on the keyboard as opposed to when the field is blurred.)

Demo:

http://jsfiddle.net/JAAulde/fUKfb/3/

Code:

var namespaced_event = 'change.hideRetweet', //use `keyup.hideRetweet` here to avoid waiting for the input to be blurred
    contest_max_retweet_wrapper = $( '#contest_max_retweet' ).closest( 'li' ); //hides entire input, label, and container--could be pared down if desired

$( '#contest_numofwinners' )
  .bind( namespaced_event, function()
  {
      contest_max_retweet_wrapper.toggle( ! $( this ).val()  );
  } )
  .triggerHandler( namespaced_event );
眸中客 2024-11-24 13:18:43

大卫·托马斯的答案当然很有效,我会在简单的情况下使用它。

但是,我一直在开发一个插件,它可以在多个条件和多个元素下执行此操作。我现在想分享这一点。

这是适合您问题的jsfiddle: http://jsfiddle.net/natedavisolds/rVehh/3/ 本质上

,加载插件然后加载:

var React = $.extend({}, $.fn.reactor.helpers); // Easier to work with helpers
$('#contest_numofwinners_input').reactIf('#contest_max_retweet', React.IsBlank);

好处是您可以将reactIf语句链接到一组规则。

这是插件。

(function($){

    $.fn.reactTo = function(selector) {
        var $elements = $(selector),
             $reactor_element = $(this),
             _proxy_event = function() {
                $reactor_element.trigger('change.reactor');
            };

        $elements.filter('select').bind('change.reactor', _proxy_event);
        $elements.filter('input').bind('keyup.reactor', _proxy_event);    

        return this;
    };

    $.fn.reactIf = function(sel, exp_func) {

        var $sel = $(sel);
        var _func = function() {
            return exp_func.apply($sel);                               
        };

        this.each(function() {
            if (!$(this).hasClass('reactor')) { $(this).reactor(); }

            var conditions_arry = $(this).data('conditions.reactor');
            if (!$.isArray(conditions_arry)) { conditions_arry = []};

            conditions_arry.push(_func);

            $(this).data('conditions.reactor', conditions_arry);
        });    

        $(this).reactTo(sel);

        return this;
    };

    $.fn.react = function() {

        this.each(function() {
           $(this).trigger('change.reactor')
        });    

        return this;
    };

    $.fn.reactor = function(options) {
        var settings = $.extend({}, $.fn.reactor.defaults, options);

        this.each(function() {
            // var opts = $.meta ? $.extend({}, settings, $this.data()) : settings;

            var $element = $(this);

            if (!$element.hasClass('reactor')) { $element.data('conditions.reactor', []).addClass('reactor'); }

            var is_reactionary = function() {  
                var conditionalArray = $(this).data('conditions.reactor');
                var r = true;

                $.each(conditionalArray, function() {
                    r = (r && this.call());
                });



                return r;                                
            }

            var reaction = function(evt) {
                evt.stopPropagation();
                if (is_reactionary.apply(this)) {
                   settings.compliant.apply($element);
                } else {
                   settings.uncompliant.apply($element);
                }
            }

            $element.bind('change.reactor', reaction);
        });

        return this;  
    };

    $.fn.reactor.defaults = {
        compliant: function() {
            $(this).show();
        },
        uncompliant: function() {
            $(this).hide();    
        }        
    };

    $.fn.reactor.helpers = {

        NotBlank: function() {
            return( $(this).val().toString() != "" )
        },

        IsBlank: function() {
            return( $(this).val().toString() == "" )
        },

        EqualTo: function(matchStr) {
            var _func = function() {
                var v = $(this).val();
                if (v) { return( v.toString() == matchStr ); }
                else { return false; }
            }
            return _func;
        },

        LessThan: function(number) {
            var _func = function() {
                var v = $(this).val();
                return(!(v && parseInt(v) > number));
            }
            return _func;   
        },

        MoreThan: function(number) {
            var _func = function() {
                var v = $(this).val();
                return(!(v && parseInt(v) < number));
            }
            return _func;  
        },

        Between: function(min, max) {
            var _func = function() {
                var v = $(this).val();
                return(!(v && (parseInt(v) > max || parseInt(v) < min)));
            }
            return _func;
        },

        BetweenSameLength: function(min, max) {
            var len = min.toString().length;
            var _func = function() {
                var v = $(this).val();
                return(!(v && v.length == len && (parseInt(v) > max || parseInt(v) < min)));
            }
            return _func;
        }
    };

})(jQuery);

David Thomas's answer certainly works well and I would use this for simple cases.

However, I've been working on a plugin that does this with multiple conditions and with multiple elements. I would like to share that now.

Here is the jsfiddle that works for your problem: http://jsfiddle.net/natedavisolds/rVehh/3/

Essentially, load the plugin then on load:

var React = $.extend({}, $.fn.reactor.helpers); // Easier to work with helpers
$('#contest_numofwinners_input').reactIf('#contest_max_retweet', React.IsBlank);

The nice thing is that you can chain the reactIf statement to a set of rules.

Here's the plugin.

(function($){

    $.fn.reactTo = function(selector) {
        var $elements = $(selector),
             $reactor_element = $(this),
             _proxy_event = function() {
                $reactor_element.trigger('change.reactor');
            };

        $elements.filter('select').bind('change.reactor', _proxy_event);
        $elements.filter('input').bind('keyup.reactor', _proxy_event);    

        return this;
    };

    $.fn.reactIf = function(sel, exp_func) {

        var $sel = $(sel);
        var _func = function() {
            return exp_func.apply($sel);                               
        };

        this.each(function() {
            if (!$(this).hasClass('reactor')) { $(this).reactor(); }

            var conditions_arry = $(this).data('conditions.reactor');
            if (!$.isArray(conditions_arry)) { conditions_arry = []};

            conditions_arry.push(_func);

            $(this).data('conditions.reactor', conditions_arry);
        });    

        $(this).reactTo(sel);

        return this;
    };

    $.fn.react = function() {

        this.each(function() {
           $(this).trigger('change.reactor')
        });    

        return this;
    };

    $.fn.reactor = function(options) {
        var settings = $.extend({}, $.fn.reactor.defaults, options);

        this.each(function() {
            // var opts = $.meta ? $.extend({}, settings, $this.data()) : settings;

            var $element = $(this);

            if (!$element.hasClass('reactor')) { $element.data('conditions.reactor', []).addClass('reactor'); }

            var is_reactionary = function() {  
                var conditionalArray = $(this).data('conditions.reactor');
                var r = true;

                $.each(conditionalArray, function() {
                    r = (r && this.call());
                });



                return r;                                
            }

            var reaction = function(evt) {
                evt.stopPropagation();
                if (is_reactionary.apply(this)) {
                   settings.compliant.apply($element);
                } else {
                   settings.uncompliant.apply($element);
                }
            }

            $element.bind('change.reactor', reaction);
        });

        return this;  
    };

    $.fn.reactor.defaults = {
        compliant: function() {
            $(this).show();
        },
        uncompliant: function() {
            $(this).hide();    
        }        
    };

    $.fn.reactor.helpers = {

        NotBlank: function() {
            return( $(this).val().toString() != "" )
        },

        IsBlank: function() {
            return( $(this).val().toString() == "" )
        },

        EqualTo: function(matchStr) {
            var _func = function() {
                var v = $(this).val();
                if (v) { return( v.toString() == matchStr ); }
                else { return false; }
            }
            return _func;
        },

        LessThan: function(number) {
            var _func = function() {
                var v = $(this).val();
                return(!(v && parseInt(v) > number));
            }
            return _func;   
        },

        MoreThan: function(number) {
            var _func = function() {
                var v = $(this).val();
                return(!(v && parseInt(v) < number));
            }
            return _func;  
        },

        Between: function(min, max) {
            var _func = function() {
                var v = $(this).val();
                return(!(v && (parseInt(v) > max || parseInt(v) < min)));
            }
            return _func;
        },

        BetweenSameLength: function(min, max) {
            var len = min.toString().length;
            var _func = function() {
                var v = $(this).val();
                return(!(v && v.length == len && (parseInt(v) > max || parseInt(v) < min)));
            }
            return _func;
        }
    };

})(jQuery);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文