如果输入不为空,则显示按钮。

4

我不是JavaScript专家,所以需要帮助编写简单的代码。

我有一个按钮,可以清除输入框中的值。

如果输入框为空,则希望该按钮隐藏,反之亦然(如果输入框中有文本,则显示该按钮)。

解决方案可以使用纯JavaScript或jQuery,都可以。越简单越好。

5个回答

8
$("input").keyup(function () {
   if ($(this).val()) {
      $("button").show();
   }
   else {
      $("button").hide();
   }
});
$("button").click(function () {
   $("input").val('');
   $(this).hide();
});

http://jsfiddle.net/SVxbW/


我们是被鼓励还是被打击提供完整的解决方案,就像这样?(我对此并无意见,只是好奇在 Stack Overflow 上的立场是什么) - Only Bolivian Here
@SergioTapia 这并不是一个“完整”的解决方案——我认为它相当简陋。它使用通用选择器,不关心输入的值是什么……甚至没有考虑最初隐藏按钮(我会用 CSS 来实现)。 - Explosion Pills
我宁愿使用" onchange ",因为您只想在文本更改时触发切换(您可以按多个按钮而不实际触发 onchange 事件)。 - Styxxy
@Styxxy 在某些浏览器中,直到输入框失去焦点,.onchange 事件才会触发。 - Explosion Pills
确实如此,我亲自测试过。在这种情况下,你确实必须使用键盘*事件。 - Styxxy

7
if(!$('input').val()){
    $('#button').hide();
}
else {
    $('#button').show();
}

在最简单的形式中 ;)

是的,确实:D 有没有更短的方法?我正在尝试使用.toggle()来完成它。 - John
1
也许你可以把它变得更短,但为什么呢?噢,根据过去的经验,我建议不要习惯使用 .toggle()。在处理更复杂的代码时可能会引发问题。想象一下,某些原因导致该函数启动两次,切换将工作两次。如果你使用 .hide(),那么元素会被告知要隐藏两次,没什么大不了的。 - Ilya Karnaukhov
是的,你说得对 :D 我只是在想是否可能。谢谢 :) - John

2

如果不使用jQuery(实际上是其他人已经做过的相同事情,只是使用纯JS),可以这样做。这很简单,但我也添加了一些注释。

 <body>
    <input type="text" id="YourTextBox" value="" />
    <input type="button" id="YourButton" value="Click Me" />
    <script type="text/javascript">

        var textBox = null;
        var button = null;

        var textBox_Change = function(e) {
            // just calls the function that sets the visibility
            button_SetVisibility();
        };

        var button_SetVisibility = function() {
            // simply check if the visibility is set to 'visible' AND textbox hasn't been filled
            // if it's already visibile and the text is blank, hide it
            if((button.style.visibility === 'visible') && (textBox.value === '')) {
                button.style.visibility = 'hidden';
            } else {
                // show it otherwise
                button.style.visibility = 'visible';
            }
        };    

        var button_Click = function(e) {
            // absolutely not required, just to add more to the sample
            // this will set the textbox to empty and call the function that sets the visibility
            textBox.value = '';  
            button_SetVisibility();
        };                

        // wrap the calls inside anonymous function
        (function() {
            // define the references for the textbox and button here
            textBox = document.getElementById("YourTextBox");
            button = document.getElementById("YourButton");
            // some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
            if('' === button.style.visibility) { button.style.visibility = 'visible'; }
            // assign the event handlers for the change and click event
            textBox.onchange = textBox_Change;
            button.onclick = button_Click;
            // initialize calling the function to set the button visibility
            button_SetVisibility();
        })();
    </script>
</body>​

注意:我已经在IE9和Chrome中编写并测试了这个内容,请确保你在其他浏览器中进行测试。此外,我已经添加了这个fiddle,以便您可以看到它的工作原理。

1

首先在页面加载时隐藏按钮:

jQuery(document).ready(function() {
    jQuery("#myButton").hide();
});

然后附加一个onChange处理程序,当文本字段的内容为空时隐藏按钮。否则,它会显示按钮:
jQuery("#myText").change(function() {
    if(this.value.replace(/\s/g, "") === "") {
       jQuery("#myButton").hide();
    } else {
       jQuery("#myButton").show();
    }
});

您还需要在清除输入后隐藏按钮:
jQuery("#myButton").click(function() {
   jQuery("#myInput").val("");
   jQuery(this).hide();
});

1
为什么你还在使用 jQuery()?你没有转用 $ 吗? - PitaJ
习惯性的行为。$ 可以绑定到其他东西,比如 Prototype,所以我通常只使用 jQuery - Vivin Paliath
那很有道理。我通常只使用jquery,所以就不用担心这个了。 - PitaJ

1

您可以使用$('selector').hide()将元素隐藏,使用$('selector').show()将其再次显示。

更好的是,您可以使用$('selector').toggle()来使其显示和隐藏,而无需任何自定义逻辑。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接