tjohnson_nb
tjohnson_nb

Reputation: 70

Why is JS variable undefined?

This is strange - I must be missing something! I have this simple js thing that goes like this;

<select onchange='my_function(this.options[this.selectedIndex].value),\"my_text\"'>

and the JS is simply;

function my_function(selected, text) {
    var link="file.php?var1="+selected+"&var2="+text;
    document.write(link);
}

But I keep getting link=file.php?var1=selected&var2=undefined

I have an almost identical function which works fine!

Upvotes: 0

Views: 126

Answers (3)

David
David

Reputation: 218827

You're not passing the second value to the function. It's outside of the function call (and acting only as invalid markup). Try:

<select onchange="my_function(this.options[this.selectedIndex].value, 'my_text')">

I changed two things here:

  1. Moved the my_text value into the function call.
  2. Changed the quotes. HTML expects double-quotes, JavaScript can use either single-quotes or double-quotes. So it's clearer to use double-quotes for the HTML markup and single-quotes in the inline JavaScript in this case.

Upvotes: 1

Joshua Dwire
Joshua Dwire

Reputation: 5443

Your select html should be this instead:

<select onchange="my_function(this.options[this.selectedIndex].value,'my_text')">

You were closing your function call too early. Also, note that I've switched the outer quotes to be double and the inner quotes to be single. You don't need to escape the inside quotes, and it's more conventional for attributes to be double quoted instead of single quoted..

Upvotes: 2

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28548

replace:

<select onchange='my_function(this.options[this.selectedIndex].value),\"my_text\"'>

with this:

<select onchange='my_function(this.options[this.selectedIndex].value),"my_text"'>

because \ is a escape character, and it causing to pass your text as my_text instead of "my_text" and in first one is not the correct string.

I think you try to add " quotation over the string, but query string is by default a string you no need to add quotation if still you needs then try:

<select onchange='my_function(this.options[this.selectedIndex].value),"\"my_text\""'>

Upvotes: 0

Related Questions