4

您好,有一个包含几个字段的表格。其中:

<div>
    <label for="phoneNumber" class="label">Phone Number</label>
    <input name="phoneNumber" type="text" id="phoneNumber" size="13"  style="float:left;margin-right:10px;">
</div>
<div>
    <input type="checkbox" name="activePN" id="activePN" checked >
    <label for="activePN">Active</label>
</div>

提交表单时,我想验证输入并在每个字段旁边写下未验证的字段。像这样:

$('#submit').click(function () {
    var proceed = true;
    var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
    if (strippedPN.length !== 10) {
        $('#phoneNumber').text('<p>Phone number has to be 10 digits long.</p>')
        proceed = false;
    }
...
...
...
});

我希望添加这些<p> </p>标签可以做到这一点。但他们没有......注意:我也尝试过 withhtml()而不是text()和 withactivePN而不是phoneNumber

4

3 回答 3

13

使用.after().

$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')

将一个类也添加到您的p标签中可能是明智的,因此您可以在将数字编辑为正确时删除它们。

于 2013-08-15T23:13:12.913 回答
2

尝试:

$('#submit').click(function(){
  var proceed = true;
  var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, ''); //strips non-digits from the string - already a String
  if(strippedPN.length !== 10){
    $('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
     proceed = false;
  }
}
于 2013-08-15T23:23:56.450 回答
0

最好使用jqueryvalidation插件。

但在某些情况下,您可能需要使用自定义代码显示验证消息,那么下面可能会有所帮助。

代码

var errorSeen = false;

$('#txtname').keyup(function (e) {

var validInput = false; // TODO set your validation here

if (!validInput) {

  var errorMessageVisible = $(".validationMessage").is(":visible");

  if (errorSeen === false && errorMessageVisible === false) {

      $('#txtname').style.borderColor = "red";

        $('#txtname').after("<span class='validationMessage' style='color:red;'>
                            Name is required.</span>");

        errorSeen = true;
    }


  }
   else {

   $('#txtname').style.borderColor = "";

     var errorMessageVisible = $(".validationMessage").is(":visible");

     if (errorMessageVisible)
        $(".validationMessage").remove();

        errorSeen = false;
  }

});
于 2019-05-30T14:21:04.110 回答