如何使用多个下拉选项选择给定行中特定下拉列表的值?

时间:2016-05-23 13:20:39

标签: javascript jquery

我有很多表单,有两个下拉选项名称和值,我希望选择名称来自数组的变量,类似这样。

for (i = 0;i<noOfElements;i++)
           {
                var resultHtml = theModule.getHtml("rowformtemplate", {});
            //load html of form with fields **name** and **value** as dropdown
                $(section).append(resultHtml);
            //append html to a div
                var optValue = namearray[i];
            //from list of optons this value should be selected
                var form = $(section).find(".row-template");
            //find all forms in the section
                var row= form[form.length-1];
            //select latest form
            //How to select name field "name" of current row and set it to be optvalue which is a variaable something like this. but it selects name field of all form and sets it to optValue 
                $("select[name^='name'] option[value=" + optValue + "]").attr("selected","selected");
            } 

1 个答案:

答案 0 :(得分:0)

在最终的jquery选择器中,您正在查看完整的html文档而不是最新的表单。

尝试以下

$(row).find("select[name='name'] option[value='" + optValue + "']").attr("selected","selected");

或者如果使用最新的jquery

$(row).find("select[name='name'] option[value='" + optValue + "']").prop("selected",true);

同时检查 How do I select item with class within a DIV in JQuery

How do you select a particular option in a SELECT element in jQuery?