aboot jquery单选按钮验证

时间:2019-05-22 13:54:45

标签: jquery

我有一个文本框和两个单选按钮,例如IP和域,我想根据选择的单选按钮验证文本框,

    

    <input type="radio" id="ip" name="radio_options" value="option1">
    <label for="option1">IP</label><br>

    <input type="radio" id="domain" name="radio_options" value="option2">
    <label for="option2">Domain</label><br>
<label for="required_later"></label>
    <input type="text" name="text_input_field"  id="required_later" disabled><br>

    <input type="submit" name="submit" value="Submit">
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
 $("#ip").click(function() {
        $("#required_later").prop("required", true);
        $("#required_later").prop("disabled", false);
          $( "#required_later" ).attr("pattern",  "((^|\.)((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?\d))){4}$" );       


    });
    $("#domain").click(function() {
        $("#required_later").prop("required", true);
        $("#required_later").prop("disabled", false);
        $("#required_later").focus();
       $( "#required_later" ).attr("pattern",'/^(http(s)?\/\/:)?(www\.)?[a-zA-Z\-]{3,}(\.(com|net|org))?$/');
    });

1 个答案:

答案 0 :(得分:0)

您可以使用$('input[name="radio_options"]')作为选择器并使用change事件。设置一个if条件以测试单选按钮的值。

$('input[name="radio_options"]').change(function() {
  var value = $(this).val();

  if (value == "option1") {                         //IP selected
    $("#required_later").prop("required", false);
    $("#required_later").prop("disabled", true);
  } else {                                          //Domain Selected
    $("#required_later").prop("required", true);
    $("#required_later").prop("disabled", false);
    $("#required_later").focus();
  }

});
<body>
  <form action="" method="post">


    <input type="radio" id="ip" name="radio_options" value="option1">
    <label for="option1">IP</label><br>

    <input type="radio" id="domain" name="radio_options" value="option2">
    <label for="option2">Domain</label><br>
    <label for="required_later"></label>
    <input type="text" name="text_input_field" id="required_later" disabled><br>

    <input type="submit" name="submit" value="Submit">
  </form>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


</body>