Reputation: 1383
I have problem with transferring value from the object to the javascript without page refresh. I have noticed, that if my page refresh, my value disappear.
Fiddle example:
http://jsfiddle.net/pcgy3/185/
Could someone help me with this problem ? Thank You in advance :)
Upvotes: 0
Views: 83
Reputation: 910
You don't technically need the form, you could just have the elements on their own. Does this answer the question you have?
HTML:
Value(between 1 and 20):
<input type="number" id="num_of_balls" min="1" max="20">
<button id="clickBTN">Click</button>
JS:
function onClick() {
var ballCount = parseInt(document.getElementById("num_of_balls").value, 10);
if(ballCount < 1 || ballCount > 20) return; // it have to be value between 1 and 20 to continue
var i = 0;
alert("#Balls: " + ballCount);
for (i = 0; i < ballCount; i++) {
obj_t.push({
xPos : 10 + 10 * i,
yPos : 10 + 11 * i,
xVel : 0 + i / 10,
yVel : 1 + i / 10,
r : 2 + i / 5
});
}
}
var obj_t = [];
var btn = document.getElementById("clickBTN");
btn.addEventListener("click", onClick);
document.getElementById("num_of_balls").addEventListener("keypress", (evt) => {
if(evt.key === "Enter") {
onClick();
}
});
Upvotes: 2
Reputation: 2732
That is obvious, none of the changed made to the DOM stays once after the page gets reloaded, unless you are storing the the value somewhere in cookie, session, local-storage or DB.
Though here is an example of getting the value in JS. Iam using JQuery .keyup as an event which will trigger the value from
HTML:
<input type="number" id="num_of_balls" min="1" max="20">
JS
$('#num_of_balls').keyup(function(e){
if(e.which == 13) { // on Enter key pressed
alert(document.getElementById('num_of_balls').value)
}
})
Code here http://jsfiddle.net/pcgy3/189/
Upvotes: 0
Reputation: 2673
You can a listener to the input change :
var input = document.querySelector('input');
input.addEventListener('input', function()
{
obj_t=[];
for (var i = 0; i < document.getElementById('num_of_balls').value; i++) {
var obj = {
xPos : 10 + 10 * i,
yPos : 10 + 11 * i,
xVel : 0 + i / 10,
yVel : 1 + i / 10,
r : 2 + i / 5
}
obj_t.push(obj);
}
console.log(obj_t);
});
http://jsfiddle.net/pcgy3/188/
Upvotes: 0