-2

I have many forms with two dropdown options name and value and I want option of name to be selected be a variable from an array, something like this.

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");
            } 
user3778989
  • 127
  • 1
  • 2
  • 8

1 Answers1

0

In your final jquery selector, you are looking through the full html document instead of the latest form.

Try the following

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

or if using latest jquery

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

Also check 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?

Community
  • 1
  • 1