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();"/>
2
  • 3
    have you tried something like onclick="EditBanner(myVar)" ? Commented Apr 7, 2011 at 20:01
  • 2
    uh, what about not in-lining your code? Commented Apr 7, 2011 at 20:01

3 Answers 3

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" />
Sign up to request clarification or add additional context in comments.

4 Comments

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
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.
Of course it can work -- but so does using GOTO and 3000-line methods. Not inlining is a best fit for any project.
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. ;)
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);
});

1 Comment

This does not work, you cannot use variables like that inside HTML. Use onclick="EditBanner(bannerID);" instead
5
<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>

2 Comments

Shouldn't the first line be wrapped in a <script> tag?
@StevenLu: Yeah, it should. I was just trying to point out how to use the variable.

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.