Joe Pigott
Joe Pigott

Reputation: 8459

alert not displaying when using button onclick

Here's the fiddle.

I'm trying to make it so when you click the button it alerts 'You tried to search... ...whatever you typed...!', but the button doesn't alert the message.

I've already tried using:

var a = document.getElementById('input').value;
    alert("You tried to search " + a + "!");

and it still doesn't alert the message, please answer?

Upvotes: 0

Views: 1327

Answers (3)

Steely Wing
Steely Wing

Reputation: 17597

If you using jQuery, you should bind click event using jQuery, it will be better, http://jsfiddle.net/dmsrY/13/

remove onclick

<button id="clickme" type="button" title="Search" value="Search">Search</button>

and you can call the search() in same scope

$('#clickme').click(function () {
    search( $('#input').val() );
});

// make search function more flexible
function search(s) {
    alert(s);
}

if you want to access search() everywhere

// create jQuery plugin function
$.search = function (s) {
    alert(s);
}

// now you can call search like this
$.search('search string');

Upvotes: 0

gameboy90
gameboy90

Reputation: 303

you code will run as soon as this page is loading,you can optimize your code like this [use jquery]:

$(document).ready(function(){
  $('#search').onclick(function() {
          var a = document.getElementById('input').value;
          alert("You tried to search " + a + "!");
      });
});

Upvotes: 1

sabof
sabof

Reputation: 8192

Your function is inaccessible outside of it's closure. It should be

window.search = function() {
    var a = document.getElementById('input').value;
    alert("You tried to search " + a + "!");
}

Upvotes: 2

Related Questions