Home > Enterprise >  after set default value attribite can't re-assign it
after set default value attribite can't re-assign it

Time:10-11

I'm trying to do so "Projectile motion" experiment.

in HTML

<div>
    <label for="angle">Angle</label>
    <input id="angle" name="angle" type="number" max="90" min="0" value=50 ></input>
    <label for="velocity">Velocity</label>
    <input id="velocity" name="velocity" type="number" value=150></input>
    <button id="launch">Launch</button>
    <button id="reset">Reset</button>
</div>

And in JS:

let v = document.getElementById("velocity").value;
let degreeAngle = document.getElementById("angle").value;

I can change the value of V and Angle in the input by this is no effect on the value. (always v is 150 and angle 50)

why ? and how can I change those values?

CodePudding user response:

You seem to be looking for a way to respond to changes in the values set by the user. What you're looking for is an event handler (https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers).

Event handlers allow you to attach a callback function to an element and have it execute whenever some event occurs.

You can attach an event handler to the click event on the #launch button and run your calculations/simulation like so:

function onLaunchClicked() {
  let v = document.getElementById("velocity").value;
  let degreeAngle = document.getElementById("angle").value;
  // Run simulation
}

let launchButton = document.getElementById("launch");
launchButton.addEventHandler("click", onLaunchClicked);

CodePudding user response:

You can make use of setAttribute to update the value of an attribute

element.setAttribute("attributeName", "value")

for instance this code will alert 3000 agains your code, while the initial value was 150

    let v = document.getElementById("velocity").value;
document.getElementById("velocity").setAttribute("value", "3000")
alert(document.getElementById("velocity").value)
  • Related