javascript - traverse the dom an select each inputbox pair in order to create js object -
i'm adding dynamic number of input boxes inside view selection combobox.
if choose 1 combobox add 2 input boxes inside view, 2 adds 4, 1 selection adding 1 pair of input boxes has it's unique id's:
<input id="mytextbox1" type="text"> <input id="mytextboxcomp1" type="text"> <input id="mytextbox2" type="text"> <input id="mytextboxcomp2" type="text">
... , on.
let's want create js object values in inputboxes. how can traverse dom select each inputbox pair in order create js object, example:
var myobj = { propone:"x", proptwo:y };
it's want?
<!doctype html> <html> <head lang="en"> <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.3.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ var n = 0; $('#combobox').change(function() { for(i = 0; < $(this).val(); i++) { $('#view').append( '<input id="mytextbox' + n + '" type="text"> ' + '<input id="mytextboxcomp' + n + '" type="text">'); n++; } }); $('#show-json').click(function() { var r = []; for(var = 0; true; i++) { var mytextboxi = $('#mytextbox' + i); var mytextboxcompi = $('#mytextboxcomp' + i); if(mytextboxi.length) { var propi = {}; propi['propone' + i] = mytextboxi.val(); propi['proptwo' + i] = mytextboxcompi.val(); r.push(propi); } else { break; } } $('#json').html(json.stringify(r)); }); }); </script> <style type="text/css"> input { display: block; } </style> </head> <body> <select id="combobox"> <option value="0" selected>none</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <div id="view"> </div> <button id="show-json">show json</button> <pre id="json"> </pre> </body> </html>