Situation Description
My HTML form loads with a variable number of elements that have the attribute valid = "default"
.
As the user enters a value for each element, I use AJAX to validate the tag and set valid
to true or false accordingly.
When the submit button is pressed, I collect the valid
attribute values.
Problem
jQuery is only returning the initial values of valid
. Is there a way to get the updated value of valid
?
The code I'm using:
var tags = ($('.tag').map(function () { return $(this).attr('valid') })).get();
returns ["default", "default"]
even after the values have been updated and should be showing ["true", "false"]
I'm new to JavaScript, jQuery and AJAX. So, if there is a better way to do this, please let me know what you think.
$('#' + field + 'cell')
selects td
element , the parent element of input
having valid
attribute, not the input
element itself, resulting in
.attr("valid", "false")
being applied to the parent td
element , not the child input
element.
Try removing DOM
event attributes, changing selector to
$('#' + field + 'cell')
.attr("style", 'border:3px solid #FF0000')
.find("[id="+field+"]").attr("valid", "false")
$(function() {
function validate(field, query) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: {json:JSON.stringify(query)}
})
.done(function(response) {
console.log(field, response === "false", response === "true")
//response = response.replace(/[[\]]/g,'');
if(response === 'false') {
$('#' + field + 'cell')
.attr("style", 'border:3px solid #FF0000')
.find("[id="+field+"]").attr("valid", "false")
}
else {
$('#' + field + 'cell')
.attr("style", 'border: none')
.find("[id=" + field + "]")
.attr("valid", "true")
}
})
.fail(function() {
$('#response').html('error');
})
.always(checkForm) // added to verify `checkForm` at each `$.ajax` call
}
function checkForm(variable) {
var tags = $.map($(".tag"), function (el) { return $(el).attr('valid') });
console.log(tags);
}
$("#submitButton").on("click", function(e) {
checkForm()
});
$("[id^=tag]").on("blur", function(e) {
validate(e.target.id, e.target.value)
});
});
jsfiddle http://jsfiddle.net/mL8ttwc0/2/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.