简体   繁体   中英

Passing Parameters from HTML Button to JavaScript Function

I have some short code for a button in html:

<input type="button" onClick="showSelectsVar('sText2id');">
<select name="sText2id" id="sText2id" value="Third">
  <option value="1st">First</option>
  <option value="2nd">Second</option>
  <option value="3rd">Third</option>
</select>
function showSelectsVar (x) {
    x=document.getElementById(x).value;
    var insertTextVar = document.createTextNode(x);
    var child = document.getElementById(x);
    child.parentNode.insertBefore(insertTextVar,child);
}

this is the Jsfidde

i think the problem is in the js, but i got stuck

I want to pass an id of a select menu to a js function, the function then inserts the current value of the selectmenu into the page dynamically.

Is there a resource that help understand when to use single, double and no quotes when passing parameters?

Thanks

If you are passing a string, then use quotes around the string. As single and double quotes are equivalent, it would make most sense to use single quotes in your example, otherwise you end up having to escape quotes and it starts getting messy.

If you are passing a literal number or the name of a variable, do not use quotes.

More information on quotes: When to Use Double or Single Quotes in JavaScript .

Fixed it, after stepping away for an hour.

I either need to re-declare the 1st "x" in the function or change the "x" to another variable. I have changed the variable to "xVar" and it is working.

Thanks anyway.

function showSelectsVar (x) {
    xVal = document.getElementById(x).value;
    var insertTextVar = document.createTextNode(xVal);
    var child = document.getElementById(x);
    child.parentNode.insertBefore(insertTextVar,child);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM