Set select option 'selected', by value

后端 未结 28 2342
攒了一身酷
攒了一身酷 2020-11-22 10:40

I have a select field with some options in it. Now I need to select one of those options with jQuery. But how can I do that when I only know the

相关标签:
28条回答
  • 2020-11-22 11:32

    Deselect all first and filter the selectable options:

    $('.id_100 option')
         .removeAttr('selected')
         .filter('[value=val1]')
             .attr('selected', true)
    
    0 讨论(0)
  • 2020-11-22 11:32
    <select name="contribution_status_id" id="contribution_status_id" class="form-select">
        <option value="1">Completed</option>
        <option value="2">Pending</option>
        <option value="3">Cancelled</option>
        <option value="4">Failed</option>
        <option value="5">In Progress</option>
        <option value="6">Overdue</option>
        <option value="7">Refunded</option>
    

    Setting to Pending Status by value

       $('#contribution_status_id').val("2");
    
    0 讨论(0)
  • 2020-11-22 11:32

    Best way is like this:

    $(`#YourSelect option[value='${YourValue}']`).prop('selected', true);
    
    0 讨论(0)
  • 2020-11-22 11:35

    Just put in this code:

    $("#Controls_ID").val(value);
    
    0 讨论(0)
  • 2020-11-22 11:35

    This works for sure for Select Control:

    $('select#ddlCountry option').each(function () {
    if ($(this).text().toLowerCase() == co.toLowerCase()) {
        this.selected = true;
        return;
    } });
    
    0 讨论(0)
  • 2020-11-22 11:36

    It's better to use change() after setting select value.

    $("div.id_100 select").val("val2").change();
    

    By doing this, the code will close to changing select by user, the explanation is included in JS Fiddle:

    JS Fiddle

    0 讨论(0)
提交回复
热议问题