0
votes

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"

1

1 Answers

0
votes

I'm not sure why you don't just add the selected in your server code. As far as your jQuery you have several issues.

First, you have syntax problems which should be throwing errors in your browser console. Simply looking at console would have saved you this step

var currID = ('#selectAuthor').val();

Should be:

var currID = $('#selectAuthor').val();

Next syntax problem is in second version when you pass currID into the string, you are adding it as string text, not as a variable concatenated into the string.

if( $("select option[value='+currID+']").attr('selected','selected'));

However this is still a problem because you are setting the attr not getting it. Useprop` method instead an it will retuen a boolean

 if( $("select option[value='+currID+']").prop('selected'));

The problem with the first version is:

  if(('.authorId').val() == currID)

Syntax again ( use a browser console!!!) ...missing $. Even with the proper syntax you can't check all of the values in one if on a collection of elements. It will only return the value of the first one. It's like asking for a single phone number for 20 different people. You either have to loop over all of the collection using each() method and check each one with your if or use filter()

 $('.authorId').filter(function(){
       return this.value == currID;
 }).prop('selected',true)