数据是我从另一个页面获得的json它看起来类似于
数据:
{"BusNo":["The bus no field is required."],"CompID":["The comp id field is required."],"TotalSeats":["The total seats field is required."]}
这是我的剧本:
$(document).ready(function() {
$("#driver").click(function(event) {
var BusNo = $("#BusNo").val();
var CompID = $("#CompID").val();
var TotalSeats = $("#TotalSeats").val();
var _token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
},
function(data) {
if (data != '') {
var obj = JSON.parse(data);
$.each(obj, function(entry) {
var targetSelector = '';
if (entry == "BusNo") {
targetSelector = "#BusNo";
console.log('error in bus field');
}
if (entry == "CompID") {
targetSelector = "#CompID";
console.log('error in comp id');
}
if (entry == "TotalSeats") {
targetSelector = "#TotalSeats";
console.log('error in total seats');
}
if (targetSelector)
$(targetSelector).next("span.error").html(obj[entry]);
else {
$(targetSelector).next("span.error").text(' ');
}
});
} else {
console.log('pass');
}
});
});
});
如果if(data != '')
并且检查targetSelector = "#BusNo";
我的问题是,一旦脚本运行,它会将错误抛给特定的跨度,即BusNo,CompID等。
一旦填满,它就会继续显示错误消息
即,给定的脚本
if (targetSelector)
$(targetSelector).next("span.error").html(obj[entry]);
else {
$(targetSelector).next("span.error").text(' ');
}
此处其他部分$(targetSelector).next("span.error").text(' ');
无效,
我正在做的错误是什么,如何解决这个问题。
我知道了
$("span.error").empty();
会这样做
但是我需要突出显示带错误的输入文本框,错误应仅在悬停特定文本时显示,而不是在
中显示<input type="text" id="BusNo" name="BusNo"/><span class="error"></span>
<input type="text" id="CompID" name="CompID"/><span class="error"></span>
答案 0 :(得分:1)
代码更改:
if (targetSelector)
$(targetSelector).next("span.error").html(obj[entry][0]);
else {
$(targetSelector).next("span.error").text(' ');
}
如果你想在悬停时显示错误:
$("input").hover(function(){
var id = $(this).attr("id");
$("input").next("span.error").hide();
$("#"+id).next("span.error").show();
})