Home > Net >  How to get new input value with each button press?
How to get new input value with each button press?

Time:12-01

Upon clicking the button it displays an alert from the input value a custom string. My issue is that after clicking the button and changing the input value, clicking the button again displays the old value instead of the new.

Javascript

function test() {
var message = document.getElementById("name").value;
var newMessage = message   " "   "HELLO!";
document.getElementById("send").addEventListener("click", function (e) {
e.stopImmediatePropagation();
alert(newMessage);
console.log(newMessage);
});
}

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="main.js"></script>
<link rel="stylesheet" href="style.css">
<title>Greet your friend</title>
</head>
<body>
<label class="main">Enter the name of your friend you want to greet</label>
<input class="main" type="text" name="name" id="name" value="George">
<button class="main" id="send" onclick=test()>DONE</button> 
</body>
</html>

CodePudding user response:

You had uncountable syntax problems which I fixed them. You don't need to use stopImmediatePropagation here.

function test() {
  var message = document.getElementById("name").value;
  var newMessage = message   " "   "HELLO!";
  
  // -- You don't need a new variable to apply them --
  // message  = " "   "HELLO!";
  
  // -- Or this one which is better and newer. Called 'String Literals' --
  // message = `${message} HELLO!`;

  alert(newMessage);
  console.log(newMessage);
};
<label class="main">Enter the name of your friend you want to greet</label>
<input class="main" type="text" id="name" />
<button class="main" id="send" onclick="test()">DONE</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related