简体   繁体   中英

onclick doesn't store variable

I'm trying to store the value of a input field into a variable. But it doesn't seem to work. What am I doing wrong? I know there are other ways and I will probably change it later anyway. But right now I'm just really curious why this doesn't work:

http://codepen.io/ttimon/pen/PGYapa

<div id="searchInput" class="form-group">
  <input type="text" class="form-control" id="usr" placeholder="Type your search term here...">
  </div>
  <button id="search" class="button" onclick="searchWiki();">Search</button>

</div>



$( document ).ready(function() {
    function searchWiki() {
      var search = document.getElementbyId("usr").value;
      alert(search);
} 

});

thanks for your help

For searchWiki to be invokable from onclick it needs to be in global scope.

Declare searchWiki outside document.ready

$( document ).ready(function() {

});
function searchWiki() 
{
  var search = document.getElementById("usr").value;
  alert(search);
} 

You must be getting an error because the searchWiki function is not in scope. Move it out of the document.ready function...

function searchWiki() {
      var search = document.getElementbyId("usr").value;
      alert(search);
} 

$( document ).ready(function() {


});

First off, stop using Javascript inside your HTML. It is generally considered a good practice to follow Unobtrusive Javascript where you separate the Javascript and HTML and don't insert Javascript into your HTML, but rather use Javascript run at initialization time to "hook up" to your HTML.

Your existing code is getting an error because function names inserted inside the HTML must exist in the global scope, but your searchWiki() function is not in the global scope - it's inside the .ready() handler function so the symbol searchWiki doesn't exist in the global scope.

Then, since you already have jQuery, you can just hook up the click handler with jQuery.

HTML:

<div id="searchInput" class="form-group">
  <input type="text" class="form-control" id="usr" placeholder="Type your search term here...">
  </div>
  <button id="search" class="button">Search</button>
</div>

Javascript:

$(document).ready(function() {
    $("#search").click(function() {
        var search = $("#usr").val();
        alert(search);
    });
});
<head>
<script src="prepare.js"></script>
</head>

<body>
    <div id="searchInput" class="form-group">
      <input type="text" class="form-control" id="usr" placeholder="...">
    </div>
    <button id="search" class="button">Search</button>

    <script src="pageready.js"></script>
</body>

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