2

I am trying t create dynamic dropdown using a value of array but values are appending inline in option

<body onload="getdata()">
  <select class="form-control"   id="focusedinput" name="sBranchName"  required>
    <option name="sBranchName" id="branch_list" ></option>
  </select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ></script>

<script>
function getdata () {
	var data =['rajkot','surat','delhi']
	var mySelect = $('#branch_list'); 
  	for(let value of data){
    console.log(value)
       mySelect.append("<option>" + value + "</option>")
    }
};
</script>
</body>

Can anyone suggest the proper way?

1 Answer 1

3

See this line:

mySelect.append("<option>" + value + "<option>")

You're missing a /.

You're also appending to the option rather than to the select. Try selecting the select instead:

$('#focusedinput').append("<option>" + value + "</option>")

function getdata() {
  const data = ['rajkot', 'surat', 'delhi']
  const mySelect = $('#focusedinput');
  data.forEach((value) => {
    mySelect.append("<option>" + value + "</option>");
  });
}

getdata();
<select class="form-control" id="focusedinput" name="sBranchName" required>
  <option name="sBranchName" id="branch_list" ></option>
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

1 Comment

Made a live snippet, works for me. (though your initial option is still blank, don't know what you want to do with that)

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.