Reputation: 31
My friend made his own random number generator on his website and challenged me to find a way to make some sort of script that could automatically answer the random number generator. I'm an engineer, not a programmer, so I don't really know anything about this and I would like to learn. So far what I have seen is that the random number generator puts 4 different spans into a division so they all appear in their own boxes. They all have the same class name and I would somehow like to make a script that automaically retrieves the information from the spans and inputs it into a text box.
<div id="numgen">
<div class="numgen-content">
<span class="numgen-number">3</span>
<span class="numgen-number">7</span>
<span class="numgen-number">1</span>
<span class="numgen-number">9</span>
<input name="numgen-input" type="text" id="numgen-input">
</div>
</div>
After searching around on the internet and learning a bit about jquery I found this small script that I could use
$("span[class='numgen-number']");
however, when I used it, it returned
<span class="numgen-number">3</span>
Having little knowledge of this, I would like some assistance.
Upvotes: 3
Views: 875
Reputation: 1141
something like this should do the trick:
function getNumbers() {
$output = $("#numgen-input");
$(".numgen-number").each(function(index, item) {
$output.val($output.val() + $(item).text());
});
}
then add a button or something to call getNumbers()
Demo: http://jsfiddle.net/Ag7La/2/
Upvotes: 0
Reputation: 8249
No jQuery or library required:
var textArray = Array.prototype.slice.call(document.querySelectorAll('.numgen-number')).map(function(span){
return span.textContent;
});
Upvotes: 1