JQuery val() quirk

I’ve had a good solid day of coding, probably my first in quite a while. Whilst I was playing round some JQuery I came across a quirk I’ve never noticed before. I call it a quick because it’s certainly not behaviour I’d expect.

When working with some HTML form elements I used the JQuery method val() to set the value of a select box. So as an example here’s a select box and the JQuery to set it.


<select name="DavesSelectBox" id="DavesSelectBox">
<option value="0">Zero</option>
<option value="1">One</option>
</select<


$(DavesSelectBox).val(1);

Now the problem arises when the form is submitted using a normal submit button and post method. I noticed whilst it visually seemed the select box was being set to the value, the posted value didn’t reflect this and posted the original value.

So after some looking around it turns out that if the element has the same name and id then .val() can sometimes be a little problematic. So the quick fix to change the name and id to different values. Strange!