使用jQuery检查文本输入并使第二个文本成为必需

时间:2016-03-17 15:18:51

标签: jquery html forms validation

如果time字段包含任何文字,我正在尝试让jQuery强制我的phone字段可见并且必需。基本上,一旦用户开始填充Phone字段,我希望显示下一个字段(Time)

<form id="contact-form" method="POST" target="files/contact.php">
  <label for="full_name">Your Name: </label><input type="text" name="full_name" required="required" /><br />
  <label for="phone">Phone Number: </label><input type="text" id="phone" name="phone" /><br />
  <div id="time">
    <label for="time">Best time to call: </label><input type="text" name="time" /><br />
  </div>
  <input type="submit" name="submit" class="submit-btn" />
</form>
$(document).ready(function() {
  $("#time").hide();
});

var inp = $("#phone").val();
if ($.trim(inp).length > 0) {
  $("#time").show();
  $("#time").addClass('required');
}

Codepen Link

1 个答案:

答案 0 :(得分:3)

DEMO - &gt; http://codepen.io/anon/pen/wGgrOB

使用.on(keyup, myFunction)

$(document).ready(function() {
  $("#time").hide();
});

$('#phone').on("keyup", function() {
  if (this.value.length > 0) {
    $("#time").show();
    $("#time").find("[name=time]").attr('required', 'required');
  } else {
    $("#time").hide();
  }
});