16

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();"/>
Bobby Borszich
  • 11,639
  • 9
  • 37
  • 35
Pit Digger
  • 9,618
  • 23
  • 78
  • 122

3 Answers3

29

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" />
Khez
  • 10,172
  • 2
  • 31
  • 51
  • 1
    I agree best practice is to use event handlers, but inlining can and does work (doesn't scale well), just need to see what fits best for your project – Bobby Borszich Apr 07 '11 at 20:09
  • 1
    Considering he already has an ID for the button and he sets myvar somewhere in the code, we can assume he already has a – Khez Apr 07 '11 at 20:10
  • Of course it _can_ work -- but so does using GOTO and 3000-line methods. Not inlining is a best fit for any project. – Michael Paulukonis Apr 08 '11 at 15:34
  • Michael: "Not inlining is a best fit for any project" -- just put "almost", and you are 100% correct. (Just to let me do this 5-minute throwaway hack proto "project" with 7 lines of JS code to test out some Firebase behavior without expecting the Spanish inquisition. ;) – Sz. Feb 16 '14 at 18:16
5
<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
5

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);
});
Bobby Borszich
  • 11,639
  • 9
  • 37
  • 35
  • 2
    This does not work, you cannot use variables like that inside HTML. Use `onclick="EditBanner(bannerID);"` instead – gen_Eric Apr 07 '11 at 20:04