开发者

Jquery attach show event to select option

开发者 https://www.devze.com 2022-12-23 21:32 出处:网络
I have a select form element with 5 options.If option 2 is selected I want to display another form input box (this has a style of display:none initially).How can I attach an event to opt开发者_如何学J

I have a select form element with 5 options. If option 2 is selected I want to display another form input box (this has a style of display:none initially). How can I attach an event to opt开发者_如何学JAVAion 2 so that whenever it is selected the input box is shown otherwise it is hidden. I have this currently but this does not handle is option 2 is already selected when the page loads

$('#type').change(function(){
        var typeSelected = $(this).val();
        if (typeSelected == 2) {
            $('#extraInput').show();
        }
    });

I know I could add another bit of code which checks what is selected on page load but wondered if there was a neater way of doing this. Also something that could handle the hiding of the input box if option 2 is not selected at the start as currently I have just hard-coded style="display:none" onto the input box but I would prefer this to be dynamic.

Thanks


You might wanna try :

  $('#type').change(function(){
            var typeSelected = $(this).val();
            if (typeSelected == 2) {
                $('#extraInput').show();
            }
            else{
            $('#extraInput').hide();
            }
        });

How does your html looks like <option>Option name</option> or

<option value="0">Option name</option>

Refer to my previous answer :

Submit form to 2 different action page

You need to have option value in order to compare which option you selected.


your code must look like this: DEMO: http://jsbin.com/ezolu4/edit

$(function() {

      $('#type').change(function() {
            var typeSelected = $(this).val();

            if (typeSelected == 2) {
                $('#extraInput').fadeIn(200);
            } else {
          $('#extraInput').fadeOut(200);
          }
        }).change();
    });

Ops.. I have the solution for you!


What if you try $('#type').trigger('change'); on page load? Does that solve the problem?

$('#type').trigger('change');
$('#type').change(function(){
    var typeSelected = $(this).val();
    if (typeSelected == 2) {
        $('#extraInput').show();
    } else {
        $('#extraInput').hide();
    }
});
0

精彩评论

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