我目前有一个ajax请求,它在提交时填充表单数据。我想进行调整,以便在表单字段(例如:ordernum)输入值时填充它。我试图调整编码以执行onChange但只是出错。
function get_data() {
// stop the form submitting
// event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var ID = this.elements.ordernum.value;
if (/\S/.test(ID)) {
ajax_request(this.action, {"action" : "fetch", "ordernum" : ID}, process_response);
}
else {
alert("No ID supplied");
}
}
// encapsulate the lot within a function scope called on document ready
window.addEventListener("DOMContentLoaded", function() {
// hook the submit action on the form
var frm = document.getElementById("quick-form");
frm.addEventListener("submit", frm_submit, false);
/**
* function to handle form submit, and request data from server
* @param {Event} event
*/
function frm_submit(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var ID = this.elements.ordernum.value;
if (/\S/.test(ID)) {
ajax_request(this.action, {"action" : "fetch", "ordernum" : ID}, process_response);
}
else {
alert("No ID supplied");
}
}
... blah ...
}
答案 0 :(得分:0)
根据您提供给我们的所有信息,我重新创建了以下内容。没有错误。它们必须在您未向我们展示的代码中的某处出现。
///// This is a dummy, simulating what you may have there in real.
function ajax_request(a, b, c) {
setTimeout(c, 500);
}
function process_response() {
alert('Hurray!');
}
///// The original code (only reformated)
function get_data() {
// stop the form submitting
// event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var ID = this.elements.ordernum.value;
if (/\S/.test(ID)) {
ajax_request(this.action, {"action" : "fetch", "ordernum" : ID}, process_response);
} else {
alert("No ID supplied");
}
}
// encapsulate the lot within a function scope called on document ready
window.addEventListener("DOMContentLoaded", function() {
// hook the submit action on the form
var frm = document.getElementById("quick-form");
frm.addEventListener("submit", frm_submit, false);
/**
* function to handle form submit, and request data from server
* @param {Event} event
*/
function frm_submit(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var ID = this.elements.ordernum.value;
if (/\S/.test(ID)) {
ajax_request(this.action, {"action" : "fetch", "ordernum" : ID}, process_response);
} else {
alert("No ID supplied");
}
}
});
<form id="quick-form">
<input type="text" name="ordernum" />
<button type="submit">Submit</button>
</form>