HeartDisk
HeartDisk

Reputation: 47

how to append Options in Select Box Dynamically

i want to add two options in DropBox

$("#payment_method_1").append(new Option("Credit", "7"));
$("#payment_method_1").append(new Option("Debit", "6"));

when i implement that codes it's append perfectly but the problem is it's appending so many times instead of one time

    <select name="payment_method_1" id="payment_method_1" class="paysome" style="opacity: 0;">
    <option value="1" selected="selected">Cash</option>
    <option value="2">Credit Card</option>
    <option value="3">Western Union</option>
    <option value="4">Cheque</option>
    <option value="8">Bank</option>
    <option value="7">Credit</option>
    <option value="6">Debit</option>
    <option value="7">Credit</option>
    <option value="6">Debit</option>
    <option value="7">Credit</option>
    <option value="6">Debit</option>
    <option value="7">Credit</option>
    <option value="6">Debit</option>
    </select>

Here is my Loop

    $('.paysome').each(function(index, element) {   
    $("#payment_method_"+index).append(new Option("Credit", "7"));
    $("#payment_method_"+index).append(new Option("Debit", "6"));
    });

Thanks in Advance

Upvotes: 1

Views: 95

Answers (1)

Deepak Ingole
Deepak Ingole

Reputation: 15732

You can simply create an option and append to your select

$('.paysome').each(function(index, element) {        
    var index = index + 1;
    var select = document.getElementById("payment_method_"+index);
    select.appendChild(new Option("Credit", "7"));
    select.appendChild(new Option("Debit", "6"));      
}

Or,

$('.paysome').each(function(index, element) {        
    var index = index + 1;
    $("#payment_method_"+index).append(new Option("Credit", "7"));
    $("#payment_method_"+index).append(new Option("Debit", "6"));              
}

I see issue is with index.$.each index starts with zero and your id index starts with 1 so you may need to update your id or update your code .

Here is Fiddle

Upvotes: 1

Related Questions