3

So I have a selection list, and if the default value hasn't been changed from --- then return to the form false. Pretty much for validation purposes so we know they picked a title. The problem is that for some reason prop() is changing the default value to the bottom most value. Is there a way to keep this from happening? Here's a JSFiddle:

JSFiddle Link

And here's the code:

HTML

<form onSubmit="return checkSelect()">
<select id="title" name="title"> <option value="---">---</option> <option value="Administrator">Administrator</option> <option value="Asst. Admin.">Asst. Admin.</option> <option value="Director">Director</option> <option value="Asst. Director">Asst. Director</option> <option value="IT Director">IT Director</option> <option value="Manager">Manager</option> <option value="Medical Officer">Medical Officer</option> <option value="Other">Other</option> </select>
    <input type="submit" value="submit" />
</form>

JS

function checkSelect(){
try{
    var val = $('#title option').attr('selected', 'selected').val();
    alert(val);
    return false;
    }
    catch(err){
        alert(err.message);
    }
}

EDIT

I tried to change to attr() to see if that would help, but it produces the same problem :(

Howdy_McGee
  • 9,729
  • 25
  • 98
  • 172

1 Answers1

2

The attr(attribute, value) function you use is setting the attribute to a value, see the attr doc. Try changing:

var val = $('#title option').attr('selected', 'selected').val();

to:

var val = $('#title option:selected').val();

See this jsfiddle.

Jeroen
  • 53,290
  • 30
  • 172
  • 279
  • That worked, thank you! I must be confused on what prop() does. – Howdy_McGee Apr 05 '12 at 20:17
  • Glad I could help :). By the way, your code sample uses `attr`, not `prop`. They do different (but related) things for you. The [prop documentation](http://api.jquery.com/prop/) has a description of the difference. – Jeroen Apr 06 '12 at 06:12