Skip to content

Instantly share code, notes, and snippets.

@mgaffigan
Created November 22, 2019 03:21
Show Gist options
  • Save mgaffigan/4248989603f5ac0bfa0074e3509df545 to your computer and use it in GitHub Desktop.
Save mgaffigan/4248989603f5ac0bfa0074e3509df545 to your computer and use it in GitHub Desktop.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<p>Example of a variable number of combo boxes</p>
<form>
<input type="number" id="regionCount" value="1" />
<ul id="regionList">
</ul>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script>
var selectTemplate = `<li>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</li>`;
function regionCount_onChange() {
// see if we can get a number (coerce string to number with unary + operator)
var count = +$('#regionCount').val();
// validate count to be a number (e.g.: not NaN)
if (!(count > 0 && count < 999)) {
count = 1;
}
// If #regionList has more than count elements, trim them from the end.
$('#regionList').children().toArray().slice(count).forEach(child => child.remove());
// add from end to count
while ($('#regionList').children().length < count) {
$('#regionList').append(selectTemplate);
}
};
// Wait for the page to be ready
$(document).ready(function () {
// add an event handler for the "regionCount" input box (onChange)
$('#regionCount').on('input', regionCount_onChange);
// Trigger once to add the first value
regionCount_onChange();
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment