javascript - 通过 json 结果在输入下附加表单验证消息

标签 javascript jquery

我正在尝试添加服务器端验证,这很好,但我想在每个单独的输入下显示消息。这是我的 json 返回的示例:

{  
   "title":"The title field is required",
   "description":"The description field is required",
   "price":"The price field is required",
   "startingprice":"The startingprice field is required",
   "startprice":"The startprice field is required",
   "type":"The type field needs to contain one of these values: auction",
   "condition":"The condition field needs to contain one of these values: new",
   "auctionlength":"The auctionlength field is required",
   "shortdescription":"The shortdescription field is required",
   "offers":"The offers field is required",
   "returns":"The returns field needs to contain one of these values: accept",
   "country":"The country field is required",
   "shippingcost":"The shippingcost field is required"
}

这就是我尝试通过 jquery 实现的方法:

$.each(data, function(input, message)
{
    console.log(input);
    $('input[name='+input+']').append(message);
});

还有我的表格示例:

<input type="text" name="title">
<input type="text" name="description">

我检查了控制台日志,没有收到任何错误,有什么帮助吗?

最佳答案

您想使用.after()而不是追加

$.each(data, function(name, message) {
    $('input[name='+ name +']').after('<div class="error">' + message + '</div>');
});

Demo

关于javascript - 通过 json 结果在输入下附加表单验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37929265/

相关文章:

javascript - jquery 可点击行 : how to find the value i need in ${this}

jquery - 使用 jQuery 检索按钮值

jQuery Accordion 设置处于事件状态

javascript onclick 函数调用失败

javascript - while 循环因 jquery 中的某些数学函数而崩溃

jquery - (Wordpress) 图像到 Work 的附件但未出现在 slider 中

jquery - 如何在jquery selectize插件中设置从数据库中选择值

javascript - 如何为不同的属性使用单独的缓冲区

javascript - 如何在javascript的url中传递参数?

javascript - HTML/Javascript 代码可以在 JSbin 中运行,但不能在 codepen、plunker 或 jsfiddle 中运行