1

I want to append option value=0 in my dropdown list. Here is my code:

for (i = 1; i < = wardcount; i++) {
    var option = $('<option/>');
    option.attr({
        'value': i
    }).text(i);

    $('#ward_no').append(option);
}
2
  • Start the loop from i = 0 Commented Oct 15, 2020 at 7:35
  • no i should be 1.I want to append <option value=0>select</option> in my dropdown Commented Oct 15, 2020 at 7:38

3 Answers 3

2

Just consider it as text.

let zero  =`<option value="0">Select</option>`
$('#ward_no').append(zero);
for (i = 1; i <= wardcount; i++) {
    let option = `<option value="${i}">${i}</option>`
    $('#ward_no').append(option);

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

Comments

0
- for (i = 1; i <= wardcount; i++)
+ for (i = 0; i < wardcount; i++)

1 Comment

Although this code might solve the problem, a good answer should also explain what the code does and how it helps.
0

Do it before the loop.

$("#ward_no").empty();
$("#ward_no").append($("<option>", {value: 1, text: "select"}));
for (i = 1; i < = wardcount; i++) {
    var option = $('<option/>', {value: i, text: i});
    $('#ward_no').append(option);
}

2 Comments

when i use $('#ward_no').html(""); this before loop default option is missing.but i want empty the dropdown before choose another option
You do this after you empty the dropdown and before you add all the numbered options.

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.