Domanda

Code: Fetch JSON and create cart contents. Create a list of each products info, and have a form required for each product to update qty

   $.ajax({
        url: "myurl",
        type: 'POST',
        dataType: "json"

    }).done(function(response){

        $.each(response,function(k,v){
            //UL this products info list was here

            var otions = '';
            for( i=1; i<20; i++ ){

                options += '<option value="'+i+'">'+i+'</option>';

            }

            var form = '<form action="myurl" method="post" accept-charset="utf-8"><label for="products_qty">Quantity</label>'
            +'<select name="products_qty>'
            +options
            +'</select>'
            +'<input type="hidden" name="row_id" value="17e62166fc8586dfa4d1bc0e1742c08b" />'
            +'<input type="submit" name="submit_item" value="Update"  /></form>';


            $('#formWrapper').append(form);

        });

    });

The code runs well. In the for loop I need to add selected=selected to a particular option tag.How and where will this be added.

Can a if statement be achieved inside for loop?

var otions = '';
for( i=1; i<20; i++ )
{
    if(i=7)
    {
        var select = 'selected="selected"';
    }
    options += '<option value="'+i+'" '+select+'>'+i+'</option>';
}

Ive seen the following link and tried adding their stuff just before my apped, and no luck. set option "selected" attribute from dynamic created option

È stato utile?

Soluzione

Try this changes,

      var otions = '';
        for( i=1; i<20; i++ ){
            if(i==7){
               options += '<option value="'+i+'" selected="selected">'+i+'</option>';
            }
            else
               options += '<option value="'+i+'" +select+>'+i+'</option>';

        }

Altri suggerimenti

The problem with your code:

var otions = '';
for( i=1; i<20; i++ )
{
    if(i=7)
    {
        var select = 'selected="selected"';
    }
    options += '<option value="'+i+'" '+select+'>'+i+'</option>';
}

... is that select only exists inside the if statement, because that's where you're defining it.

So:

var otions = '';
for( i=1; i<20; i++ )
{
    var select;
    if(i=7)
    {
        select = 'selected="selected"';
    }
    else
    {
        select = "";
    }

    options += '<option value="'+i+'" '+select+'>'+i+'</option>';
}

Maybe this is what you want:

var select = i === 7 ? " selected='selected'" : '';
options += "<option value='"+i+"'"+select+'>'+i+'</option>';
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top