jQuery:如果选择了一个选项,则更改css值

时间:2013-10-22 02:47:45

标签: jquery html css menu

我正在尝试创建一个选项下拉菜单,当我尝试显示文本框时,如果选择了“其他”选项,我就会陷入困境。

这就是我所拥有的:

<span id="con-country"><label for="country">Country: </label>
<select name="country" required="required">
<option value="usa">United States</option>
<option value="uk">United Kingdom</option>
<option id="other" value="other">Other</option>
</select>
</span>

<span id="con-specify">
<label for="specify">Specify: </label>
<input type="text" name="specify" id="c-specify" required="required"></input>
</span>

CSS:

#con-specify{
    margin-left: 50px;
    display: none;
}

简单吧?问题是我不知道如何在jQuery中执行代码

因此,如果用户在菜单中选择其他,则应显示文本框,我该怎么做?

3 个答案:

答案 0 :(得分:1)

尝试

//dom ready handler
jQuery(function($){
    //change event handler for the select
    $('select[name="country"]').change(function(){
        //set the visibility of the specify element based on the value of select
        $('#con-specify').toggle(this.value == 'other')
    }).change();//fire the change event so that the initial visibility is set
})

演示:Fiddle

详细了解http://api.jquery.com/

中的每种方法

答案 1 :(得分:0)

如果您已经使用过jQuery,只需使用$('#con-specify').show()$('#con-specify').hide()

即可

答案 2 :(得分:0)

您需要在html的头部添加一个jQuery链接:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">

下拉菜单应该有一个ID(即:国家/地区)。

然后你的javascript看起来像这样:

    window.onload = function() {
      $('#con-specify').hide();

      $('#country').change(function(){
        if($(this).val() == 'other') {
            $('#con-specify').show();
        } else {
            $('#con-specify').hide();
        }
      });
    };