mongkon mamiw
mongkon mamiw

Reputation: 189

How to change onclick using Javascript?

How to change onclick using Javascript ?

https://jsfiddle.net/749rt0m7/1/

I tried to use this code, but it does not work. How can I do it?

<span  onclick="test_fn('aaa,bbb')" id="xx">edit</span>
<script>
    document.getElementById('xx').onclick = "test_fn(111,222)";
</script>

Upvotes: 10

Views: 47813

Answers (4)

scorgn
scorgn

Reputation: 3629

There are a couple things going on here.

First of all test_fn() is not a function in your jsfiddle. You will need to define it in order for it to be called.

Second of all you are setting the onclick attribute to be a string not a function. You would have to set it to be a function using the code below.

document.getElementById('xx').onclick = function() { test_fn(111,222) };

Here is an example of a working jsfiddle.

UPDATE

It looks like I misunderstood the question. If you would actually like to change the onclick attribute, as in, change what the HTML shows, you will want to use setAttribute(). So your code would be..

document.getElementById('xx').setAttribute( "onClick", "test_fn('111,222')" );

Here is the updated jsfiddle

As a side note, like nnnnnn says in a comment of the original post, using this you are passing 1 parameter through the function which is the string 111,222 when it seems that you might want to be passing two. If you would like to pass 111 as the first parameter and 222 as the second parameter, you would call the function with either test_fn(111,222) (passing the parameters as integers) or with test_fn('111','222') (passing the parameters as strings)

Upvotes: 27

Ahmed Eid
Ahmed Eid

Reputation: 4804

I don't see where you are defining the function test_fn you are hooking the function to the element onclick twice in the html and in js .. only one is needed , and you need to actually define the function

 <span id="xx">edit</span>
 <!-- or .. not both , they are doing pretty much the same thing--> 
 <script>
   document.getElementById('xx').onclick = function(){
     console.log('clicked')
   }
 </script>

now you need to define test_fn it will get called upon clicking the element

function test_fn(arg1 , arg2){
  condole.log(arg1 , arg2)
}

note that the html onclick version is passing one argument and the js script version is passing two argumens.

Upvotes: 0

hackerrdave
hackerrdave

Reputation: 6706

You need to set onclick to a function, that runs your code test_fn('111,222'):

<script>
  document.getElementById('xx').onclick = function() { test_fn('111,222'); }
</script>

Upvotes: 0

Kyle Lin
Kyle Lin

Reputation: 833

document.getElementById('xx').onclick = function() {
  test_fn(111, 222);
};

When setting onclick in HTML, use a string. When setting it through JS, use a function.

Upvotes: 3

Related Questions