Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get new input value with each button press?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!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>

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading