最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript jQuery hide fields when opening page - Stack Overflow

programmeradmin2浏览0评论

I have the following code:

<script>
    $('#advert').live('change', function () {
        if ($(this).is(':checked')) {
            $(":text").show();
        } else {
            $(":text").hide();
        }
    });
</script>

This code shows and hides text fields when the checkbox is checked. It works perfectly but I want the text field to be hidden when the page opens.

I have the following code:

<script>
    $('#advert').live('change', function () {
        if ($(this).is(':checked')) {
            $(":text").show();
        } else {
            $(":text").hide();
        }
    });
</script>

This code shows and hides text fields when the checkbox is checked. It works perfectly but I want the text field to be hidden when the page opens.

Share Improve this question edited Mar 21, 2013 at 20:12 JSuar 21.1k4 gold badges43 silver badges85 bronze badges asked Mar 21, 2013 at 20:09 JérémyJérémy 4051 gold badge4 silver badges22 bronze badges 2
  • 1 multiple ways.. add text { display: none} css. or hide it when the document loads. $(function(){ $(':text').hide(); }); – Sujesh Arukil Commented Mar 21, 2013 at 20:12
  • You can use .toggle() and pass in the condition - $(':text').toggle(this.checked) to shorten your code – wirey00 Commented Mar 21, 2013 at 20:33
Add a ment  | 

4 Answers 4

Reset to default 5

Hide the text fields on document ready.
The document ready event, says "When I'm finished loading, execute this code". So on page load it fires .hide() on your text fields. It's very powerful!

$(document).ready( function () {
  $(":text").hide();
});

Another approach is to set the style to "display: none;" on each of these. Then they start out hidden

<script>
$(function() {
    $('#advert').live('change', function(){
    if($(this).is(':checked')){
    $(":text").show();
    } else {
    $(":text").hide();
    }
    }).trigger('change');
});
</script>

This will also handle the case when the user clicks the box, goes to another page, clicks the back button, and has the box checked by the browser automatically.

give your text fields a class of maybe .text and then use css like so:

.text{ display: none; }

or jquery like so:

$(document).ready( function () {
  $(":text").hide();
});

Exchange

.show();

and

.hide();
发布评论

评论列表(0)

  1. 暂无评论