Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline onclick JavaScript variable

I have a JavaScript above this html is there any way to pass it inside EditBanner(JS Variable Here) in code below ?

//EditBanner to be changed to pass a Js variable.
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner();"/>
like image 246
Pit Digger Avatar asked Apr 07 '11 19:04

Pit Digger


3 Answers

There's an entire practice that says it's a bad idea to have inline functions/styles. Taking into account you already have an ID for your button, consider

JS

var myvar=15;
function init(){
    document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
}
window.onload=init;

HTML

<input id="EditBanner" type="button"  value="Edit Image" />
like image 56
Khez Avatar answered Oct 02 '22 23:10

Khez


Yes, JavaScript variables will exist in the scope they are created.

var bannerID = 55;

<input id="EditBanner" type="button" 
  value="Edit Image" onclick="EditBanner(bannerID);"/>


function EditBanner(id) {
   //Do something with id
}

If you use event handlers and jQuery it is simple also

$("#EditBanner").click(function() {
   EditBanner(bannerID);
});
like image 28
Bobby Borszich Avatar answered Oct 02 '22 21:10

Bobby Borszich


<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>
like image 27
Rocket Hazmat Avatar answered Oct 02 '22 21:10

Rocket Hazmat