Upon receiving the json data from another page, it typically resembles:
data :
{"BusNo":["The bus no field is required."],"CompID":["The comp id field is required."],"TotalSeats":["The total seats field is required."]}
Below is my Script :
$(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');
}
});
});
});
The script looks for errors within the condition if(data != '')
and assigns a specific selector such as targetSelector = "#BusNo";
An issue arises where error messages persist even after input fields are corrected.
In this part of the script:
if (targetSelector)
$(targetSelector).next("span.error").html(obj[entry]);
else {
$(targetSelector).next("span.error").text(' ');
}
The statement
$(targetSelector).next("span.error").text(' ');
in the else section does not function as intended.
I have discovered that
$("span.error").empty();
would resolve this issue.
However, I aim to highlight the input text box with errors and display the error message only on hovering over the respective field. Here's an example markup:
<input type="text" id="BusNo" name="BusNo"/><span class="error"></span>
<input type="text" id="CompID" name="CompID"/><span class="error"></span>