QGA
QGA

Reputation: 3192

Change onClick function arguments dynamically

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> 

Upvotes: 6

Views: 20676

Answers (4)

Sharique Hussain Ansari
Sharique Hussain Ansari

Reputation: 1456

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.

Upvotes: 10

Don
Don

Reputation: 1334

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')" );

Upvotes: 4

prizm1
prizm1

Reputation: 373

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.

Upvotes: 5

Standard
Standard

Reputation: 1522

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);

});

Upvotes: 1

Related Questions