jQuery - setting the selected value of a select control via its text description

前端 未结 22 1028
夕颜
夕颜 2020-11-22 09:16

I have a select control, and in a javascript variable I have a text string.

Using jQuery I want to set the selected element of the select control to be the item with

相关标签:
22条回答
  • 2020-11-22 09:43

    Try this...to select the option with text myText

    $("#my-Select option[text=" + myText +"]").prop("selected", true);
    
    0 讨论(0)
  • 2020-11-22 09:44

    This line worked:

    $("#myDropDown option:contains(myText)").attr('selected', true);
    
    0 讨论(0)
  • 2020-11-22 09:46

    I haven't tested this, but this might work for you.

    $("select#my-select option")
       .each(function() { this.selected = (this.text == myVal); });
    
    0 讨论(0)
  • 2020-11-22 09:47

    I had a problem with the examples above, and the problem was caused by the fact that my select box values are prefilled with fixed length strings of 6 characters, but the parameter being passed in wasn't fixed length.

    I have an rpad function which will right pad a string, to the length specified, and with the specified character. So, after padding the parameter it works.

    $('#wsWorkCenter').val(rpad(wsWorkCenter, 6, ' '));
    
    
    function rpad(pStr, pLen, pPadStr) {
    if (pPadStr == '') {pPadStr == ' '};
    while (pStr.length < pLen)
        pStr = pStr + pPadStr;
    return pStr; 
    } 
    
    0 讨论(0)
  • 2020-11-22 09:48

    Here is very simple way. plz use it

    $("#free").val("y").change();
    
    0 讨论(0)
  • 2020-11-22 09:48

    Heres an easy option. Just set your list option then set its text as selected value:

    $("#ddlScheduleFrequency option").selected(text("Select One..."));
    
    0 讨论(0)
提交回复
热议问题