assigning selected="selected" to dynamic option list
Posted
by
leemjac
on Stack Overflow
See other posts from Stack Overflow
or by leemjac
Published on 2012-11-22T04:04:56Z
Indexed on
2012/11/22
5:00 UTC
Read the original article
Hit count: 220
In an "edit article" page i have a select list which displays author first and last name, as well as authorId as the value. As well as the article context and headline and so on (fetched with a different method) - though this method also holds the authorId of the specific article.
I need to have the Author of the Article selected in the option list, instead of it defaulting to the first option in the select list.
what i have:
echo''; //loop through author names in option list $authors_name
foreach($authors_name as $nameRow){ echo'<option class="authorId" value = "' . $nameRow['AuthorID'] . '">'. $nameRow['FirstName'].'
'.$nameRow['LastName'] .''; }
echo'</select>';
and the jquery:
var currID = ('#selectAuthor').val();
if(('.authorId').val() == currID){ $('.authorId').addClass('new_class') $('.new_class').prop('selected',true); }
OR
var currID = ('#selectAuthor').val();
if($("select option[value=currID]").attr('selected','selected'));
Any help would be greatly appreciated, I hope what I am trying to do is clear. Thanks in advance
I have simplified it with just regular input and checked it in jsfiddle.net here is the HTML
';
<option value = "2">Name val 2</option> <option value = "5">Name val 5</option> <option value = "1">Name val 1</option>
and here is the jquery
var currID = $('#selectAuthor').val(); if($("select option[value='+currID+']").prop('selected',true));?
and even then it doesn't apply selected="selected" to option with value="1"
© Stack Overflow or respective owner