Mindaugas Li
Mindaugas Li

Reputation: 1092

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. 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. So I naturally replaced <select name="username" id="username"> to:

<select name="username" id="username" onchange="myrequest();">

However, that doesn't work. What else should I modify?

Upvotes: 0

Views: 160

Answers (1)

mplungjan
mplungjan

Reputation: 178161

Move function myRequest outside the document.ready if you want to access it elsewhere

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);
})

Upvotes: 1

Related Questions