[英]Changing from onclick to onchange doesn't work
I need to make a form which auto populates other fields when user selects an option from dropdown. 我需要制作一个当用户从下拉菜单中选择一个选项时自动填充其他字段的表单。 Doing lots of search here, made such a code:
在这里进行了大量搜索,编写了这样的代码:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<form method="POST" action="form-ajax.php">
<label for="username">Username: </label>
<select name="username" id="username"><option value="user1">user1</option><option value="user2">user2</option><option value="user3">user3</option></select>
<button id="fetchFields">fetch</button>
<label for="posts">Posts: </label>
<input type="text" size="20" name="posts" id="posts">
<label for="joindate">Joindate: </label>
<input type="text" size="20" name="joindate" id="joindate">
<p><input type="submit" value="Submit" name="submitBtn"></p>
</form>
<script type="text/javascript">
$(document).ready(function() {
function myrequest(e) {
var name = $('#username').val();
$.ajax({
method: "POST",
url: "autofill.php",
dataType: 'json',
cache: false,
data: {
username: name
},
success: function( responseObject ) {
$('#posts').val( responseObject.posts );
$('#joindate').val(responseObject.joindate);
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
})
</script>
</body>
</html>
I also have autofill.php
file, which selects data from MySQL database and returns it using json_encode
. 我也有
autofill.php
文件,该文件从MySQL数据库中选择数据并使用json_encode
返回。 Everything works well. 一切正常。
However, I need fields to be auto populated when user selects an item from dropdown, so he doesn't need to click fetch
button. 但是,当用户从下拉列表中选择一项时,我需要自动填充字段,因此他不需要单击
fetch
按钮。 So I naturally replaced <select name="username" id="username">
to: 因此,我自然将
<select name="username" id="username">
替换为:
<select name="username" id="username" onchange="myrequest();">
However, that doesn't work. 但是,这不起作用。 What else should I modify?
我还应该修改什么?
Move function myRequest outside the document.ready if you want to access it elsewhere 将函数myRequest移动到文档之外。准备好在其他位置访问它
If you attach the event handler in the load function it is however still available 如果您在加载函数中附加了事件处理程序,则该事件处理程序仍然可用
$(function() {
function myrequest(e) {
var name = $('#username').val();
$.ajax({
method: "POST",
url: "autofill.php",
dataType: 'json',
cache: false,
data: {
username: name
},
success: function(responseObject) {
$('#posts').val(responseObject.posts);
$('#joindate').val(responseObject.joindate);
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
$('#username').on("change", myrequest);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.