简体   繁体   中英

Get textbox input values in JS function on button click

I'm trying to get textbox inputs in my JS function on the click of a button. For some reason my console.log does not show the textbox inputs. How do I accomplish this?

Index.php:

  <input placeholder="Name" type='text' name='username' id='username'  maxlength="50" />
  <input placeholder="Password" type='password' name='password' id='password' maxlength="50" />
  <button id="testAJAX" onclick="Utilities.loadSavedGames()">Load Game</button>

js/utilties.js

var Utilities = {
    loadSavedGames : function () {

    var username = document.getElementById('username').value,
        password = document.getElementById('password').value;
    console.log(username + ", " + password); //null, blank

Possibly you have elements with duplicate ids on the same page. Try this code in the browser console: $('[id=username]').length and $('[id=password]').length . If the count is > 1, you have multiple elements with same id.

Put console.log instead of log and also make utilities as global object. I mean remove var.

   Utilities = {
    loadSavedGames : function () {

       var username = document.getElementById('username').value,
        password = document.getElementById('password').value;
       console.log(username + ", " + password); 
      }
     }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM