Malloc
Malloc

Reputation: 16276

click event on input button

I try to bind a function to the click event on input button, but it doesn't seems to work and method is not called:

<div id='back'>


     <input type="button"/>

     </div>

jQuery:

 $('#back').click(clickOnBackbutton);

              function clickOnBackbutton(){

                console.log('back to menu'); //function not called 

              }

I do not prefer to use onClick event, instead i prefer to use that approach. Thanx in advance.

Upvotes: 2

Views: 48518

Answers (8)

Andrey Kuzmin
Andrey Kuzmin

Reputation: 4479

If you want div#back to capture clicked button event, then with the recent jquery you have to do this:

$('#back').on("click", "input[type=button]", clickOnBackbutton);

Note that you have to put script tag in the end of body, or wrap your code in $(document).ready event.

Upvotes: 1

epascarello
epascarello

Reputation: 207501

JQuery 1.7+ you should attach the event using on.

function clickOnBackbutton(){
    console.log('back to menu'); //function not called 
}
$(document).on("click", "#back", clickOnBackbutton);

Running example

Upvotes: 1

Ram
Ram

Reputation: 144689

You should put your code within document ready handler. also note that you are selecting the div tag instead of the input element.

$(document).ready(function(){
   $('#back input[type=button]').click(clickOnBackbutton);
   // $('#back input[type=button]').click(function(){
   //    or do something here
   // });
})

Upvotes: 5

RDK
RDK

Reputation: 4560

Also you can use:

$('#back').on('click', function(){
  // some action
});

Upvotes: 1

Sam Timalsina
Sam Timalsina

Reputation: 457

Button:

<div id='back'>
    <input type="button" id='back-button'/>
</div>

jQuery:

$(document).ready(function(){
    $('#back-button').click(function(){
       console.log('Back to Menu');
    });
})

Upvotes: 3

markbaldy
markbaldy

Reputation: 2543

You could do this

$('#back').click(function(){
    clickOnBackButton();
});

I don't think there's such a thing as an input type="button". Maybe type="submit" ?

Upvotes: 1

Jonathan Muller
Jonathan Muller

Reputation: 7516

This should work:

function clickOnBackButton(){
  console.log("back to menu");
}

$('#back').click(function(){
  clickOnBackButton();
});

Upvotes: 1

Pow-Ian
Pow-Ian

Reputation: 3635

You bound to the div not the button.

give the button a name or select it as a child then bind the click event.

<div id='back'>
    <input id='backbutton' type="button"/>
</div>

JQuery

$('#backbutton').click(clickOnBackbutton);

function clickOnBackbutton(){
    console.log('back to menu'); //function not called 
}

Upvotes: 1

Related Questions