Reputation: 119
I'm working my way through the Odin Project, attempting to make the "etch-a-sketch" type website with jQuery. The idea is to have a div with a grid inside of it that when moused over, the grid squares change color. The user should also be able to input how many grid squares they want, so if they put 16 in the form, they'll get a 16x16 grid.
I set an initial value to 16. When I input a different number and hit "go", the value just changes back to 16 and the grid remains the same. Where am I going wrong?
Thanks!
Relevant code is as follows:
HTML:
<form>
<label>Enter the width in pixels:</label>
<input id="formbox" type="text" value="16">
<input id="setWidth" class="buttons" type="submit" value="Go!">
<button id="reset" class="buttons" type="reset">Reset</button>
</form>
JS:
$('#setWidth').click(function () {
$('.box').css("background-color", "#fff");
$('.box').remove();
var $divWidth = $('#formbox').val();
for (var i = 0; i < $divWidth; i++) {
$('#canvas').append('<div class="divHolder"></div>');
$('.divHolder').css("height", Math.floor(500 / $divWidth));
}
for(var i = 0; i < $divWidth; i++) {
$('.divHolder').append('<div class="box"></div>');
$('.box').css("width", Math.floor(500 / $divWidth));
$('.box').css("height", Math.floor(500 / $divWidth));
}
});
Upvotes: 0
Views: 519
Reputation: 584
You should be able to use the preventDefault()
function on the event.
This function stops the default behaviour (in this instance, a refresh of the page is the behaviour that should be expected by default).
$('#setWidth').click(function (e) {
e.preventDefault();
$('.box').css("background-color", "#fff");
$('.box').remove();
var $divWidth = $('#formbox').val();
for (var i = 0; i < $divWidth; i++) {
$('#canvas').append('<div class="divHolder"></div>');
$('.divHolder').css("height", Math.floor(500 / $divWidth));
}
for(var i = 0; i < $divWidth; i++) {
$('.divHolder').append('<div class="box"></div>');
$('.box').css("width", Math.floor(500 / $divWidth));
$('.box').css("height", Math.floor(500 / $divWidth));
}
});
Upvotes: 2