Prop option Change default value - JQuery
So, I have a select list, and if the default has not been changed from ---
, return it to form false. Largely for verification purposes, so we know they chose the title. The problem is that for some reason it prop()
changes the default to the lowest value. Is there a way to avoid this? Here's the JSFiddle:
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 changing attr () to see if it helps, but it creates the same problem :(
+3
source to share
1 answer
The function used attr(attribute, value)
sets the attribute to value, see attr doc . Try to change:
var val = $('#title option').attr('selected', 'selected').val();
in
var val = $('#title option:selected').val();
See this jsfiddle .
+2
source to share