Selecting number of items
This commit is contained in:
17
index.html
17
index.html
@@ -45,6 +45,23 @@
|
||||
</h2>
|
||||
<h3 id="result"></h3>
|
||||
<form>
|
||||
<select id="selectNumber">
|
||||
<option value="1">
|
||||
Pick 1
|
||||
</option>
|
||||
<option value="2">
|
||||
Pick 2
|
||||
</option>
|
||||
<option value="3">
|
||||
Pick 3
|
||||
</option>
|
||||
<option value="4">
|
||||
Pick 4
|
||||
</option>
|
||||
<option value="5">
|
||||
Pick 5
|
||||
</option>
|
||||
</select>
|
||||
<button type="submit" id="submit">Randomize</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
26
script.js
26
script.js
@@ -37,13 +37,11 @@ $(document).on('click', 'img.delete', function () {
|
||||
console.log(itemValue)
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
function addItem() {
|
||||
if (input.val().length < 1) {
|
||||
$('#inputError').html("Add an item please");
|
||||
} else {
|
||||
return
|
||||
}
|
||||
items.push($(input).val());
|
||||
let ul = $('#itemlist');
|
||||
let li = document.createElement('li');
|
||||
@@ -57,16 +55,24 @@ function addItem() {
|
||||
$(input).val('');
|
||||
$('#inputError').html("")
|
||||
}
|
||||
}
|
||||
|
||||
function displayResult() {
|
||||
if (items.length < 1) {
|
||||
$('#result').html('Error: Add atleast 1 item')
|
||||
$(input).css('border', '2px solid red');
|
||||
} else {
|
||||
result = items[Math.floor(Math.random() * items.length)];
|
||||
$('#result').html(result)
|
||||
$('#result').hide().fadeIn(1000);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let selectNumber = $('#selectNumber').val()
|
||||
const shuffled = items.sort(() => 0.5 - Math.random());
|
||||
result = shuffled.slice(0, selectNumber)
|
||||
|
||||
let resultText = '';
|
||||
result.forEach(function (item) {
|
||||
resultText += item + ', ';
|
||||
});
|
||||
|
||||
$('#result').html(resultText.slice(0, -2))
|
||||
$('#result').hide().fadeIn(1000);
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user