Reputation: 431
I am trying to use Javascript to control a web form. Here is all my Javascript code and what I am trying to achieve added to it as well.
$(document).ready(function(){
function loadPage(url){
$(".body").fadeOut(400, function(){
$(".body").load(url);
$(".body").fadeIn(400);
});
}
loadPage("pages/login.html");
$("#button").on("click", function(){
var pageTo = this.name;
loadPage("pages/" + pageTo + ".html");
});
});
The code will do more complex things later on, but it doesn't even run the above.
My form looks like this
<FORM>
<SPAN class='header'>Login</SPAN><BR/>
<LABEL for='username' class='loginLabel'>Username</LABEL>
<INPUT type='text' id='username' name='username' value='' />
<LABEL for='password'class='loginLabel'>Password</LABEL>
<INPUT type='password' id='password' name='password' value='' />
<INPUT type='hidden' name='process' value='login' />
<INPUT type='button' value='Login' name='index' id='button' />
</FORM>
Its a simple login form, but the text does not show up in the console when the button is clicked. I don't want to use a submit button and the JQuery .submit() event because I want the same code to work with multiple types of things, including links and possibly other elements.
Upvotes: 5
Views: 24455
Reputation: 816324
You are trying to bind the event handler before the element exists in the page.
Either bind the handler after you added the form by passing a callback to .load
:
$(document).ready(function(){
function loadPage(url){
$(".body").fadeOut(400, function(){
$(".body").load(url, function() {
$("#button").on("click", function(){
var pageTo = this.name;
loadPage("pages/" + pageTo + ".html");
});
});
$(".body").fadeIn(400);
});
}
loadPage("pages/login.html");
});
or use event delegation (see section Direct and delegated events in the documentation):
$(document).on("click", "#button", function(){
var pageTo = this.name;
loadPage("pages/" + pageTo + ".html");
});
Upvotes: 13
Reputation: 39704
try with .on
$("#button").on('click', function(){
console.log("Clicked");
});
Upvotes: 2
Reputation: 16190
jQuery objects have no onClick
method. Use .click
. Your code should look like this:
$("#button").click(function(){
console.log("Clicked");
});
Upvotes: 3
Reputation: 1905
Are you sure you're waiting for the document to be loaded before assigning the onclick behavior to your button? Try changing the assignment to be inside
$(document).ready(function(...))
Upvotes: 2
Reputation: 96800
$("#button")
returns a jQuery object for which there is no onclick
property/method. Use .click
:
$('#button').click(function() {
});
Upvotes: 3
Reputation: 2972
that's not the right way, to register a handler with jquery...
try
$('#button').click(function(){
console.log('test');
});
Upvotes: 3