It would be done, if using jQuery, in the following manner.
The above script also shows how to add a new OPTION to a HTML Select Box (DropDownList/Listbox/ComboBox). It sets the value as a fixed one and html as fixed too. And then it sets the “selected” attribute to true. You can modify this method based on your requirement. Note that it uses jQuery so you should be including the appropriate jQuery.js file. It also removes the disabled attribute since the selection would not work if the control was disabled.
Would this work? If not, why?
Well! No. The reason is – the unload on the window would be invoked and by that time the form data is already posted to the server. So your goal to change the form data would not be met since the data is already posted. I have tested with document.unload as well and the result is still the same.
This would be the workaround that worked for my situation – I had a submit button which would be clicked by the user to submit the form and then then some checks has to be performed. So I invoked the addAndSet in the click event of the submit button and then it works like a charm. This makes sense since the event handler is executed before the form data is posted.
My code looks something like this.
Note that if its a listbox, then the “value” property does not return all the values selected. Instead, it just returns the first selection in your box. For my purpose, checking the length works. If no option is selected the length would be 0 and if some option is selected, the length be the “length of the value(number of characters in the value)”.