开发者

Hide elements using jquery based on option select

开发者 https://www.devze.com 2023-01-31 19:59 出处:网络
I have two forms and a selector. This is my code -- <selec开发者_如何学Ct> <option value=\"1\">Pay</option>

I have two forms and a selector.

This is my code --

<selec开发者_如何学Ct>
<option value="1">Pay</option>
<option value="2">Goog</option>
</select>

<form id="pp">
<input type="text">
</form>

<form id="cc">
<input type="text">
</form>

Now if option 1 is selected i want to hide form CC. if 2 hide form PP.

How do i do it with js or jquery? thanks


Try this (using jQuery):

$("select").bind("change", function() {
    if ($(this).val() == "1") {
        $("#pp").show();
        $("#cc").hide();
    }
    else if ($(this).val() == "2") {
        $("#pp").hide();
        $("#cc").show();
    }
});

Additionally, you could hide both forms using .hide() as shown above before the user selects any option.

  • bind is attaching an event handler to the "change" event of the select box. This is fired when the user changes what option is selected.
  • Inside the handler, val is used to determine the value of the currently selected option.
  • show() and hide() are used on the correct forms, depending on which option was selected.

Working example: http://jsfiddle.net/andrewwhitaker/faqZg/


    <script>
    function Hide(val)
    {
    if(val==1)
{
    document.getElementById('cc').style.display='none';
    document.getElementById('pp').style.display='inline';
    }
    if(val==2)
{ 
   document.getElementById('pp').style.display='none';
    document.getElementById('cc').style.display='inline';
    }
} 
   </script>

    <select onchange="Hide(this.value);">
    <option value="">Please Select</option>
    <option value="1">Pay</option>
    <option value="2">Goog</option>
    </select>

    <div id="pp">
    <input type="text">
    </div>

    <div id="cc">
    <input type="text">
    </div>
0

精彩评论

暂无评论...
验证码 换一张
取 消