Shubham
Shubham

Reputation: 449

how to select a particular value from drop down

i am trying to select a value from a drop down menu. my code currently looks like this:

var pnam= $(this).parent().parent().find("td").eq(1).html().trim();
    $("#parentModule_name").find("option").each(function(){
          if ($(this).text()==pnam) {
              $(this).attr('selected','selected');
          }
    });

the flow goes in the inner loop where the attribute is being selected correctly. however the expected result is not being achieved. funnily, on my page when i inspect the element this is what i get

<select id="parentModule_name" name="parentId">
                        <option value="0">Please Select</option>                                    
                                    <option value="12">Admin</option>




                                    <option value="13">Util</option>




                                    <option value="15" selected="selected">Vendor</option>




                                    <option value="16">Shubham</option>



                        </select>

so as u can see. the value is being selected correctly but not being displayed on the page. any help would be appreciated. thank you

Upvotes: 1

Views: 1617

Answers (4)

Agnihotri
Agnihotri

Reputation: 1

$(document).ready(function () {

        $("#parentModule_name").change(function () {
              var temp=  $(this).find("option:selected").text();
              alert(temp);
               });
        });

Upvotes: 0

Richard
Richard

Reputation: 8280

An alternative approach is to filter the options and simply set the selected property;

$('#parentModule_name > option')
    .filter(function() { return $(this).text() == pnam; })
    .prop('selected', true);

jsFiddle demo

Upvotes: 1

K D
K D

Reputation: 5989

Try this

$(function(){
      $('#parentModule_name')
      .find('option[text="'+ pnam +'"]')
      .attr('selected','selected');
});

Upvotes: -1

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

The markup (or at least the selection portion of it) and script appear to be working: http://jsfiddle.net/7RGgA/

If you are executing this on page load, have you wrapped your script with $(document).ready();

$(document).ready(function(){
   var pnam= $(this).parent().parent().find("td").eq(1).html().trim();
    $("#parentModule_name").find("option").each(function(){
          if ($(this).text()==pnam) {
              $(this).attr('selected','selected');
          }
    });
});

Upvotes: 3

Related Questions