Javascript for turning "on or off" a select dropdown option
<p>I recently wrote a code in PHP to read a TXT file and for every line in the TXT it would create a new  drop down list and each list would have a different name.</p>

<p>Ex. Select 1 .. Option1 Option2 Option3, Select 2 .. Option1 Option2 Option3, Select N .. Option1 Option2 Option3</p>

<p>The default Option on each list "" so that they are blank. </p>

<p>Depending on how many lines in the TXT file.</p>

<p>In the 'for' loop that writes each list, each  has the name of the counter.
So each one has a different unique name. Also each  has a 'onChange=myFunction()' attached to it.</p>

<p>example:</p>

<pre><code>for($counter ... N items in Textfile...)
{
    $select_name = "questions[".$counter."]";
    "&lt;select name=\"". $select_name ."\" onChange=\"myFunction(this)\"&gt;";  
}
</code></pre>

<p>Now my question is I want to make it so that when I click an option in a list once, I will get a value of lets say.. 'A'. If I click the same option again, the option's background will change to Red and the value of the option will be 'B'. If I select a different option it will not change, in other words I have to select and option twice in order to change it from 'A' to 'B' back to 'A' etc. </p>

<p>I wrote the following code and I was wondering if someone could take a quick glance and tell me how to improve this and/or if there is a better way to this and such. I am still kinda getting the hang of writing my own codes! I thank all of you.</p>

<pre><code>&lt;script type="text/javascript"&gt;

var previous_select;
var previous_option;

function myFunction(dropdown) 
{

    var myindex  = dropdown.selectedIndex;
    var select   = dropdown.name;
    var option   = dropdown.options[myindex].text;

    if(option == '')
        return;

    if(previous_select == select)
    {
        if(option == previous_option)
        {
            if(dropdown.options[myindex].className == 'red')
            {
                dropdown.options[myindex].className.replace( /(?:^|\s)red(?!\S)/ , '' );
            }
            else
            {
                dropdown.options[myindex].className += "red";
            }
        }
        else
        {
            previous_option = dropdown.options[myindex].text;
        }
    }
    else
    {
        previous_select = dropdown.name;
    }
}
&lt;/script&gt;
</code></pre>
