jQuery: hide and show an input element

后端 未结 6 2123
情话喂你
情话喂你 2021-02-19 09:42

I\'m trying to do is hiding/showing a certain input object if a select value is checked.

Code in JSFiddle

The HTML part of the code is here:

<         


        
相关标签:
6条回答
  • 2021-02-19 09:46

    I typically factor out the hide/show logic:

    function foobar(){
        if($(this).val() == "Other"){
            $("#add_fields_placeholderValue").show();
        }
        else{
            $("#add_fields_placeholderValue").hide();
        }
    }
    

    and call it when the page loads.

    $(document).ready(function(){
        foobar();
        $("#add_fields_placeholder").change(function(){
            foobar();
        });
    });
    

    but i'd be curious to see what other folks usually do.

    0 讨论(0)
  • 2021-02-19 09:51

    You could simply do it with CSS:

    Change the ID here:

    <input type="text" name="add_fields_placeholderValue" id="add_fields_placeholderValue">
    

    since you already use it here

    <div id="add_fields_placeholderValue">
    

    and then add this css:

    #add_fields_placeholderValue {
      display: none;       
    }​
    
    0 讨论(0)
  • 2021-02-19 09:52

    if you change the anonymous method into a callable function, you should be able to call it on Ready()

    e.g.

    $(document).ready(function () {
        $("#add_fields_placeholder").change(ShowIfOther);
        ShowIfOther();
    });
    
    function ShowIfOther() {
        if ($("#add_fields_placeholder").val() == "Other") {
            $("#add_fields_placeholderValue").show();
        } else {
            $("#add_fields_placeholderValue").hide();
        }
    }​
    
    0 讨论(0)
  • 2021-02-19 09:55

    You can use css to hide it initially

    #add_fields_placeholderValue{display:none;}
    

    http://jsfiddle.net/FarVX/20/

    Also you have multiple elements with the same id(pointed out by Brandon), which is not valid

    0 讨论(0)
  • 2021-02-19 10:02

    Place the following code beneath the placeholder elements:

    <script>$('#add_fields_placeholderValue').hide();</script>
    

    Doing it in the ready handler may induce 'flashing' of the element in certain circumstances:

    Twinkling when call hide() on document ready

    0 讨论(0)
  • 2021-02-19 10:09

    Just add:

    $("#add_fields_placeholderValue").hide();
    

    After your change event declaration on page load.

    i.e.

    $(document).ready(function()
    {
     $("#add_fields_placeholder").change(function()
     {
      if($(this).val() == "Other")
      {
       $("#add_fields_placeholderValue").show();
      }
      else
      {
       $("#add_fields_placeholderValue").hide();
      }
     });
     $("#add_fields_placeholderValue").hide();
    });
    

    Working example: http://jsfiddle.net/bZXYR/

    0 讨论(0)
提交回复
热议问题