Inline onclick JavaScript variable
Asked Answered
S

3

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();"/>
Steamship answered 7/4, 2011 at 19:58 Comment(2)
have you tried something like onclick="EditBanner(myVar)" ?Homeroom
uh, what about not in-lining your code?Homeroom
C
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" />
Charity answered 7/4, 2011 at 20:5 Comment(4)
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 projectRime
Considering he already has an ID for the button and he sets myvar somewhere in the code, we can assume he already has a <script> tag where he can add event handlers and the means to get the correct element... There's no reason he should use inline events.Charity
Of course it can work -- but so does using GOTO and 3000-line methods. Not inlining is a best fit for any project.Homeroom
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. ;)Gensler
J
5
<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>
Jemimah answered 7/4, 2011 at 20:1 Comment(2)
Shouldn't the first line be wrapped in a <script> tag?Electrify
@StevenLu: Yeah, it should. I was just trying to point out how to use the variable.Jemimah
R
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);
});
Rime answered 7/4, 2011 at 20:1 Comment(1)
This does not work, you cannot use variables like that inside HTML. Use onclick="EditBanner(bannerID);" insteadJemimah

© 2022 - 2024 — McMap. All rights reserved.