6

I have something like this:

<button id="button1" onClick="someFunc('arg1','arg2')"> </button> 

Is it possible in JavaScript to change parameters of the function someFunc to look like below:

<button id="button1" onClick="someFunc('somethingDiff1','somethingDiff2')"> </button> 
4
  • 2
    so assign a need onclick method to it and remove the old one. Commented Jun 9, 2016 at 13:59
  • 3
    or use variables and set those instead Commented Jun 9, 2016 at 13:59
  • @epascarello seems a good approach. can you provide an example Commented Jun 9, 2016 at 14:01
  • developer.mozilla.org/en-US/docs/Web/API/EventTarget/… Commented Jun 9, 2016 at 14:01

4 Answers 4

10

Try this

If you want in jquery then try this

$(document).ready(function(){
   var clickfun = $("#button1").attr("onClick");
   var funname = clickfun.substring(0,clickfun.indexOf("("));       
   $("#button1").attr("onclick",funname+"('somethingDiff1',"+"'somethingDiff2')");
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1" onClick="someFunc('arg1','arg2')">Button1</button> 

If you want in JavaScript then try this:-

<script>
  window.onload=function(){
  var clickfun = document.getElementById("button1").getAttribute("onclick");
  var funname = clickfun.substring(0,clickfun.indexOf("("));       
  document.getElementById("button1").setAttribute("onclick",funname+"('somethingDiff1',"+"'somethingDiff2')");    
};
</script>

Hope This will help you.

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

2 Comments

After click the button what about 'someFunc is not defined'
Terribly easy.... I just did $('...').attr("onclick","someFunc('something1','something2')"); and it worked
5

This could also be done by writing something similiar to this:

document.getElementById('button1').setAttribute('onclick','thiswhatyouwanttohave');

But the document have to be fully loaded, or at least the button must be present to be able to access the onclick attribute.

2 Comments

Thanks. I tried this already with some issues. The button is in a table which is generated dynamically.
ok just wrap it with: window.onload = function () { } to be sure it is accesible, if it works fine also :) you can also set the onload attribute dynamically if this may help
4

Based on your requirement, we can just change arguments like below: check this working fiddle.

https://jsfiddle.net/TaEgQ/42/

button.setAttribute( "onClick", "someFunc('new1','new2')" );

Comments

1

You can just go in your script.js and type something like that:

var value = 10

$("#button1").click(function() {

 if(value < 5)
  someFunc("arg1");
 else someFunc("arg2);

});

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.