0

Given a user-defined variable jstatus, I want that that particular variable should be selected in a given list of options.

My list is like this:

<select name='job_status' id='job_status'>
    <option>Pre-press</option>
    <option>Printers</option>
    <option>Cutting</option>
    <option>Final touches</option>
    <option>Delivery</option>
    <option>Ready</option>
</select>

And somewhere in my javascript code after setting the value of jstatus, this is my jquery:

$("#job_status option[value='"+jstatus+"']").attr('selected','selected');

But it's not working. What's the right way to do it?

1
  • 2
    Please, provide value attribute to each <option> tag Commented Apr 2, 2013 at 14:18

4 Answers 4

4

Easiest way is to set the value directly:

jQuery("#job_status").val(jstatus);
Sign up to request clarification or add additional context in comments.

Comments

2

You need to add value to selector first.

<option value="Pre-press">Pre-press</option>

Comments

1

The problem is that your select list has no "value"-property on its options

<select name='job_status' id='job_status'>
     <option value="val1">Pre-press</option>
     <option value="val2">Printers</option>
     <option value="val3">Cutting</option>
     <option value="val4">Final touches</option>
     <option value="val5">Delivery</option>
     <option value="val6">Ready</option>
</select>

<script>
    $( 'select option[value="val3"]' ).attr( 'selected', 'selected' );
</script>

You can also use jQuery's val() method

$( 'select' ).val( 'val3' )

this would have the same effect as the above

Comments

1

If you still prefer using a direct selector, there's :contains for you to select element by its contents. For your case it goes pretty much like this:

$("#job_status option:contains("+jstatus+")").attr('selected','selected');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.