简体   繁体   中英

how to get value from array of selectbox inputs in jquery

On button click i want to fetch selected value of multiple select boxes. i can able to fetch value from array of textboxes but im not able to get select box value. it returns empty array.

 $("#add_user_button").click(function(){ var username=[]; $("input[name=username]").each(function(){ username.push($(this).val()); }); var usertype=[]; $("input[name=usertype]").each(function(){ usertype.push($(this).val()); }); var ajaxdata={"UserName":username,"UserType":usertype}; console.log(JSON.stringify(ajaxdata)); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <div id="user_group"> <input type="text" id="user_username" placeholder="User Name" name="username"> <select id="user_usertype" name="usertype"> <option value="1">Admin</option> <option value="2">Normal</option> </select> </div> <div class="clone_user_input"><div id="user_group_1"> <div class="form-group"> <input type="text" id="user_username" placeholder="User Name" name="username"> <select id="user_usertype" name="usertype"> <option value="1">Admin</option> <option value="2">Normal</option> </select> </div> </div> <button id="add_user_button">Add User</button> 

Select is not input. Use:

var usertype=[];
$("select[name=usertype]").each(function(){
    usertype.push($(this).val());
}); 

Also note that you have duplicate IDs for elements. IDs should be always unique. You can rather use same class names as an alternative to this.

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