gs11111
gs11111

Reputation: 659

how to get the first item selected on loading the listbox

i have this listbox loading items from database now i need the first item to stay selected on loading it, please help. I tried in jquery but that din't help.

@model  proj.Models.ListboxViewModel
@Html.ListBoxFor( m=> m.resourcename,Model.resourcename, new { @class = "resList",style="height: 121px;"})

<script>
    $(function () {
        $("select[name='resourcename']").removeAttr('multiple');
        $("select[name='resourcename']").attr('size', '8');
     //   $("#resourcename").find("option").attr("selected", '1'); // this is not working
   });
</script>

Upvotes: 0

Views: 556

Answers (2)

Nico
Nico

Reputation: 12683

This can be done quite quickly in JQuery

JQuery

$(function () {
    $("select[name='resourcename']").find('option:first').attr('selected', 'selected');
});

To get the value of the the select box using jquery try.

function getValue() {
    var resid = $("select[name='resourcename']").val();
    alert(resid)
}

Cheers

Upvotes: 1

Perazzo
Perazzo

Reputation: 1147

Try to use Jquery function .prop(), is the safest way to do it:

$("select[name='resourcename']").find("option:first").prop('selected',true);

Upvotes: 1

Related Questions