简体   繁体   中英

how to get values from select option box using for loop [select option box is created dynamically]

I'm trying to get values from select option box. but i get the first option box value only.

i want all option box values which is selected.suppose in code there is 10 select option box is created, when user clicks on button then i want all that 10 select option box values and get stored in a variables or display that options which is selected by the user.

i have done some code please refer my work from comment section it is on the jsfiddle website. for more better understanding you can refer that. sorry for my rookie language, i'm new to stackoverflow. please don't hesitate to edit my information i would like that.

The id for all the elements are same in your code. Use document.querySelectorAll to get the list of elements.

 function getdata() { var num = document.getElementById("number").value; console.log(num); $(document).ready(function() { for (var i = 0; i < num; i++) { $('<div><select id="select-meal-type' + i + '"><option value="TYPE A">TYPE A</option><option value="TYPE B">TYPE B</option><option value="TYPE C">TYPE C</option></select><br></div>').appendTo('#container'); } }); } function getValues() { var nodeList = document.querySelectorAll("[id^=select-meal-type]") var values = Array.from(nodeList).map(val => val.value) console.log(values); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <br><br> type a number<input type="text" id="number"> <br><br> <div id="container"></div> <button onclick="getdata()">GET DATA</button> <button onclick="getValues()">GET VALUES</button>

Have a look on the following jsfiddle link: [jsfiddle.net/ypb9zLe8/][1]

[1]: http://jsfiddle.net/ypb9zLe8/

Removed some code and inserted one extra button. Have a look.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM