I have an array with N elements and I have a function to draw these elements in an specific format, all the elements from 0, 2, 4, 6....n
into a div and all the elements from 1, 3, 5, 7...n
into another, I do this with two for cycles, I don’t have troubles with this, the problem is that I need to put together this values at the same way from the beginning, for example I have this array: 5, 6, 5, 6
my html output is this:
Div 1:
5
5
Div2:
6
6
What I tried was creating an array and then fill it with this function:
$('#MyDiv input').each(function () {
array.push(this.value);
});
But whit this I get the following array: 5,5,6,6
instead of 5,6,5,6
, how can I solve this?
Here is my example code:
var sampled = [];
$(document).ready(function () {
$('#btn').click(function () {
load();
});
$('#btn2').click(function () {
select();
});
});
function load() {
var array = "5, 6, 5, 6, 5, 6";
var lines = "";
var lines2 = "";
var lines3 = "";
var splitString;
splitString = array.split(",");
var total = splitString.length;
for (var x = 1; x <=total / 2; x++) {
lines += '<div class="col-md-12 text-center">';
lines += '<span class="form-control">Piece #' + x + '</span></div>';
}
//(1, 3, 5, 6, 7....)
for (var i = 0; i < total; i++) {
lines2 += '<div class="col-md-12 form-group">';
lines2 += '<input id="Input' + i + '" value="' + splitString[i] + '" class="form-control" /></div>';
i++;
}
//(0, 2, 4, 6....)
for (var s = 0; s < total; s++) {
s++;
lines3 += '<div class="col-md-12 form-group">';
lines3 += '<input id="Input' + s + '" value="' + splitString[s] + '" class="form-control" /></div>';
}
$('#Number').html(lines);
$('#Sampled').html(lines2);
$('#Dimen').html(lines3);
}
function select() {
$('#Inputs input').each(function () {
sampled.push(this.value);
});
alert(sampled);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="col-md-12" id="Inputs">
<div id="Number" class="col-md-4">
</div>
<div id="Sampled" class="col-md-4">
</div>
<div id="Dimen" class="col-md-4">
</div>
</div>
<button id="btn">Click</button>
<button id="btn2">Select</button>
And a here is my example
2
Answers
This should work for two inputs of equal size. You can add your own logic for handling different sizes or more than two divs depending on what you need.
You could collapse your three
for
loops into one like in this rewritten version, so you wouldn’t have to change the way you create thesampled
array.