user1234
user1234

Reputation: 3159

how to set a value of a dropdown to that value having a class as "selected"-Jquery

I'm trying to set the value in a dropdown who has a classname = "selected". here is the html:

 <select style="width:180px;" class="chosen-select" id="range">
<option value="7 days">7days</option>
<option value="20days" class="selected">20days</option>
<option value="30days">30days</option>
</select>

now here is what im trying to work out: js:

 $("#range_select").find('option.selected'); //gives me:
     <option value="20days" class="selected">20days</option>

below is a psedo code:

 if($("#range_select").find('option').hasClass("selected")){
    //set the value of the dropdown to "20days"
   //currently showing the default value "7days"
 }

https://jsfiddle.net/xwo10r7k/

how can i achieve this? Thanks for help!!

Upvotes: 0

Views: 29

Answers (2)

Amit.rk3
Amit.rk3

Reputation: 2417

use

 $("#range").find('option.selected').attr("selected","selected");

updated fiddle https://jsfiddle.net/xwo10r7k/1/

Upvotes: 0

Travis J
Travis J

Reputation: 82287

jsFiddle Demo

Store the range element, use it as a parent to find the class, and then set the range element's value as the child's value

var $r = $("#range");
$r.val($(".selected",$r).val());

Upvotes: 1

Related Questions