基于选择项隐藏表单项

Javascript jQuery Hide Form Items Based on Select Item

本文关键字:隐藏 表单 选择 于选择      更新时间:2023-09-26

我试图使一个表单中,当有人选择"其他"作为他们的标题,他们得到一个框出现输入标题。我的脚本的第一部分工作是为了使div开始隐藏,但我不能完全让第二部分工作,其中选择"Other"使文本框出现。

如有任何帮助,不胜感激。

这是我的HTML:
            <div>
                <label for="title" class="label">Title</label>
                <select name="title" id="title">
                <option></option>
                <option value="mr">Mr.</option>
                <option value="mrs">Mrs.</option>
                <option value="miss">Miss.</option>
                <option value="ms">Ms.</option>
                <option value="dr">Dr.</option>
                <option value="lady">Lady.</option>
                <option value="rev">Rev.</option>
                <option value="sir">Sir.</option>
                <option value="other">Other</option>
                </select>
                <input name="other_title" style="margin-left:10px;" type="text" id="other_title" size="10">
            </div>
这是我的Javascript/jQuery:
<script>
    jQuery(function( $ ) {
        $('#other_title').hide('fast');
        $(function() {
            if ($('#title option:selected').text() == 'other') {
                $('#other_title').show('fast');
            }
        }); // end function
    });
</script>

这对你有帮助吗?

$('#title').on('change', function() {
    if ($(this).val() == 'other') $('#other_title').show('fast');
    else $('#other_title').hide('fast'); // This too?
});

Edit:修复语法错误。: p

尝试使用change event并替换

if ($('#title option:selected').text() == 'other')

if ($('#title>option:selected').text() == 'other')

可以参考plunkr:https://plnkr.co/edit/R2w25NEwUbiw00r2lEs3