表单选择选项动态吸引

form select option dynamic attr

本文关键字:动态 选项 选择 表单      更新时间:2023-09-26

>我需要使用选项值选择名称,以选择特定的值或索引。 来自数据库的数据在值"{{设计}}"中。我确实立即获得了该值,但我无法在当前选项值上设置"选定"。这是代码:

console.log("{{design}}");
$(document).ready(function () {
       var options = $('select').children('option');
    var size =    $('select').children('option').length;
    for (i=0;i<size;i++)
    {
        if ( options[i].innerHTML==="{{design}}")
        {
            options.selectedIndex=i;
        }
    }
});

该 HTML 是 :

      <select name="design" required id="design"  >
                <option value="1">flowers</option>
                <option value="2">classic</option>
                <option value="3">roses</option>
            </select>

我需要使 {{design}} 值生成,假设它是 2,所以它会<option value="2" selected>classic</option>

谢谢!

解决

嗨,找到了问题的解决方案,如果有人遇到麻烦。

 $(document).ready(function () {
            var options =      $('select').children('option');
        var size =    $('select').children('option').length;
        for (i=0;i<size;i++)
        {
            if ( $('select').children('option')[i].value === "{{design}}")
            {
                 $('select').children('option')[i].selected=true;
            }
        }
    });

当前方法是找到正确的选项值,然后> [i].selected=true

祝你好运

试试这个

var selectedvalue=2; //option with value 2 should be selected
$("#design option[value=selectedvalue]").attr("selected","selected");

希望这有帮助...

如果我理解正确,你走在正确的道路上,只是走了一个小弯路。试试这个:

if ( options[i].innerHTML==="{{design}}")
    {
        options.attr('selected', 'selected');
    }

.each() 用法的例子:

$(document).ready(function(){
    $('select option').each(function(i){
        if( i.value === "{{design}}"){
            $(this).attr('selected','selected');
        }
    });
});

试试这个:

$(document).ready(function(){
    $('select option').each(function(i){
       //if this option contains the word "{{design}}" Then this is selected
        if( $(this).html().indexOf("{{design}}") != -1)
            $(this).attr('selected',true);
    });
});