jQuery - 如果文本框和下拉列表都为空,则显示段落

时间:2017-03-02 16:51:55

标签: javascript jquery

我想在文本框和下拉列表都为空时显示一个段落。我让他们分开工作,但不知道如何将它们结合起来。

所以基本上,我想要下拉列表和文本框,只有一个段落,当其他字段都为空时将显示。

到目前为止我得到了什么:

<label>Place of birth</label>
<select id="placeOfBirth">
    <option value=""></option>
    <option value="01">City 1</option>
    <option value="02">City 2</option>
    <option value="03">City 3</option>
</select>
<p class="show_dd"> show this if dropdown is not selected </p> <br><br>

<label>Other</label>
<input id="other"><br>
<p class="show_text"> show this if field is empty </p> <br><br>


$('#placeOfBirth').change(function() {
    if($("#placeOfBirth").val()===""){ 
       $('.show_dd').show();
    } else {
       $('.show_dd').hide();
    }
});

$('#other').keyup(function() {
    if ($('#other').val().length == 0) {
        $('.show_text').show();
        $('#test').val($('#other').val());
    } else {
       $('.show_text').hide();
    }
 }).keyup(); 

JSFIDDLE

1 个答案:

答案 0 :(得分:0)

我更新了您的小提琴,以便select和textbox隐藏并根据是否填充了值来显示段落。

$('#placeOfBirth').change(hideParagraph);
$('#other').keyup(hideParagraph).keyup(); 

function hideParagraph() {
  if ($('#other').val().length == 0 && $("#placeOfBirth").val() === "") {
    $('.show_text').show();
  } else {
    $('.show_text').hide();
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>Place of birth</label>
<select id="placeOfBirth">
    <option value=""></option>
    <option value="01">City 1</option>
    <option value="02">City 2</option>
    <option value="03">City 3</option>
</select>

<label>Other</label>
<input id="other"><br>
<p class="show_text"> Show this if one field is populated </p> <br><br>

相关问题