0

I created one button dynamically in JavaScript and I am unable to set action for that button..

var but = document.createElement("input");
but.type = "button"
but.value = "NewButton";
but.onClick = check();
var newElement = document.getElementById("addButton"); //span element id
newElement.appendChild(but);

The function 'check()' is not called when button is clicked

1
  • 2
    What is returned by check()? If you want check to be invoked upon a button click, remove the parenthesis: but.onClick = check; Commented Jun 12, 2012 at 10:54

4 Answers 4

3

You have 2 problems with your code. The first is that the event is not capitalized, the second is that you want to assign the event to the function rather than the results of the function. It should look like:

but.onclick = check;

This will actually assign the event to the address of the function rather than the expected result of the function (which would do nothing).

Sign up to request clarification or add additional context in comments.

Comments

1

check() executes the function, and will assign whatever that function returns to but.onClick. To assign the function to an event, specify it by name (without the parens).

Comments

0

I think yours check function not returns function which is needed to assign as callback for onclick event, then

but.onclick = check; 

for example in case:

var check = function() {   
     return function(){
        /* some logic eg. dependent of arguments 'parent' function' */  
    }  }
//works
but.onclick = check('somethingImportant');

All right, but there is a problem if you wanted to assign several callbacks for these event :) It would be better if you know about addEventListener / attachEvent

but.addEventListener( 'click', check,true );
but.addEventListener( 'click', check2,true );

Afterwards if needed use removeEventLister or detachEvent to detach function(s);

However - try to play with jquery :)

var check = function(){/* do something */};
        $('#addButton').append(
           $('<input type="button" value="New Button"/>') 
        ).click( check );​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

or

    $('#addButton').append( 
           $('<input/>' ).attr( 'type', 'button' ).val( 'New Button' ) )
                .click( function(){ /* do something */ } ) ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
    );

then

$('#addButton').unbind(  'click' ) // unbind( 'click',check )  

And much more posibilities to doing that :)

1 Comment

Thank You Abuduba for all your answers
0

Small case onclick:

but.onclick = check();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.