0

Question: Im building a dynamic list of products which every product contains a "Product Type", im looping through each product but I need to set the selected option for an existing product

$.each(products.All(), function(index, product) {
for(p in productList) {
                $( "#"+product.itemId+"_type" ).append($("<option/>", {
                    value: productList[g].value,
                    text: productList[g].label,
//Need to add something like if(productList[g].value == p.typeId) selected:true
                }));

}

2 Answers 2

1

You should use a SelectList as you specified you are using ASP.Net MVC 4

http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist%28v=vs.118%29.aspx

Two constructors gives you the possibility of setting the selected value. Anyway

you could to this

$("<option/>").attr("selected", "selected");

or

    $.each(products.All(), function(index, product) {
    for(p in productList) {

    // declare here a variable selectedValue

    if(productList[g].value == p.typeId){

    // set here a variable selectedValue 
    }
    else {
    // set here a variable selectedValue 
    }



                $( "#"+product.itemId+"_type" ).append($("<option/>", {
                    value: productList[g].value,
                    text: productList[g].label,
                    selected: selectedValue,
                }));

}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this using javascript :

<script type="text/javascript">

$.each(products.All(), function(index, product) {
     var select = document.getElementById("YourSelect");
             for(p in productList) 
               {
                   var el = document.createElement("option");
                    el.textContent =productList[g].label;
                    el.value = productList[g].value;
                    if(productList[g].value == p.typeId)
                     {
                      el.selected = true;
                     }
                    select.appendChild(el);

               }
   });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.