Show and hide html element on selected option change

前端 未结 10 1600
耶瑟儿~
耶瑟儿~ 2021-01-12 04:31

In a JSP page, I have a dropdown list. When the first element of the list is selected, I want a text area to show right on click. I\'m new to Javascript/Jquery, so I\'m obvi

相关标签:
10条回答
  • 2021-01-12 04:38
    1. Use jQuery.

    2. Remove onchange="change()" function from

      <select id="show" class="form-control" name="show_text_area" onchange="change()">
      
    3. Look for change event, on your select element.

      $('#show').on('change', function () {
         var optionSelected = $("option:selected", this);
         var valueSelected = this.value;
         if(valueSelected == 1){
             $("#text_area").show();
         } else {
             $("#text_area").hide();
         }
      });
      

    Fiddle

    0 讨论(0)
  • 2021-01-12 04:43

    you can use jquery also.

    $('#show').val();
       if( $('#show').val() == "1")
        {
             $('#text_area').show(); 
                  OR
               $("#text_area").css("visibility", "visible");
       }else
       {
          $('#text_area').hide(); 
                  OR
               $("#text_area").css("visibility", "hidden");
      }
    
    0 讨论(0)
  • 2021-01-12 04:51

    You have mistake at the end of your function - remove the last );

    Finally it should be:

    <select id="show" class="form-control" name="show_text_area" onchange="change(this)">
    
    
    function change(obj) {
    
    
        var selectBox = obj;
        var selected = selectBox.options[selectBox.selectedIndex].value;
        var textarea = document.getElementById("text_area");
    
        if(selected === '1'){
            textarea.style.display = "block";
        }
        else{
            textarea.style.display = "none";
        }
    }
    
    0 讨论(0)
  • 2021-01-12 04:51

    Your function is correct, but js Element class have no show() and hide() methods. You can implement it using prototype. As an example

    Element.prototype.hide(){
    this.style.display = "hidden";
    } 
    Element.prototype.show(style){
    style = style ? style : "block";
    this.style.display = style;
    }
    

    But better use jquery or something like this.

    0 讨论(0)
  • 2021-01-12 04:52

    You can do also using jQuery as follows.

    $("#show").change(function(){
       if($(this).val()=="1")
       {    
           $("#text_area").show();
       }
       else
       {
           $("#text_area").hide();
       }
    });
    

    Demo

    0 讨论(0)
  • 2021-01-12 04:53

    you can do this in jQuery.....like " $(document).ready(function(){

    var seletVal=$('#show option:selected').val();
    if(selectVal=='1')
    $('#textareaId').show();
    else
    $('#textareaId').hide();
    });
    

    "

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