0

I am having problems with the following code: I have n numbers of select box, whose id are differentiated by the values that the variables ModName and level take:

container.innerHTML = '<form id="listToolForm_'+ModName+level+'"><select id="listToolSelect_'+ModName+level+'" onChange="selValue(this.selectedIndex,'+ModName'+, level)"><option value="0">---</option></select></form>';

The select box is then populated by values taken from a database (this part is not really relevant here). With each form, there is a hidden input with id= idArg'+ModName+'_lev'+level, that will store the index selected by the user, using onChange and the function selValue(x): Here is the function selValue(index, ModName, level):

function selValue(index, ModName, level){
    document.getElementById("idArg"+ModName+"_lev"+level).value = index;
}

I tried the script setting var ModName = "SL", and var level = 0. I get an error: 'SL is not defined'. Another test that worked is by replacing the function that fires up onChange:

onChange="selValue(this.selectedIndex)"

and

function selValue(index){
    var level = 0;
    var ModName = "SL";
    document.getElementById("idArg"+ModName+"_lev"+level).value = index;
}

So if the function fired up onChange has one argument, the code works, but does not when using several arguments. I suspect it's because of the line:

onChange = "selValue(this.selectedIndex,'+ModName'+, level)"

I tried:

onChange="'+window["selValue"](this.selectedIndex, ModName, level)+'"

without success.

1 Answer 1

1

The following (I assumed '+ModName'+ was a typo in the question and not in the actual code):
onChange="selValue(this.selectedIndex, ' + ModName + ', level)"
causes JavaScript to substitute ModName with its value, which results in the actual HTML being:
onChange="selValue(this.selectedIndex, SL, level)"
When handling the onChange event, the JavaScript engine "thinks" SL is a variable (hence the error), but you actually want it to be a string (if I understood well).

To turn SL into a string, you should surround it with single quotes. To do that, you will need the \' escape sequence, since you're already using nested quotes. Simply replace:
onChange="selValue(this.selectedIndex, ' + ModName + ', level)"
with:
onChange="selValue(this.selectedIndex, \'' + ModName + '\', level)"

Also, didn't you mean:
onChange="selValue(this.selectedIndex, \'' + ModName + '\', ' + level + ')"
?

Sign up to request clarification or add additional context in comments.

Comments

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.