Jump to content

Alert not working


Iven

Recommended Posts

Hello 

I am trying to use an <input ..... /> tag and javascript to get user input and then alert() the user input.

However doesn't matter what I do I either get  either nothing,"undefined" or "null"?

Here is an example of what exactly I am trying to do( if you run this in w3Schools TryIt editor then the alert box will show nothing) :

<!DOCTYPE html>
<html>
<body>

<p>Click the button to demonstrate line-breaks in an alert box.</p>
<input type=text" id="txt" placeholder="Enter" />
<button onclick="myFunction()">Try it</button>

<script>
var x = document.getElementById("txt").value;


function myFunction() {
    alert(x);
}
</script>

</body>
</html>

Any help will be appreciated .

I would also like to know why this is reacting like this as I fount solutions exactly like this on the internet but it seems not work at all.

Link to comment
Share on other sites

Looks like you're missing the opening double quote for type="text".

Your browser developer tools is very useful for these situations or any situation. 😉

Edited by Don E
  • Like 1
Link to comment
Share on other sites

Haha thanks for the reply.

I changed the syntax error but it still seems to still give the same result (alert says nothing when it comes up)

 

As well can you give an example or link a reference using browser developer tools for debugging syntax errors because I am still new and I do make a lot of those mistakes and it takes me 10-15min on average just to find these stupid mistakes.

Link to comment
Share on other sites

You need the defining of x to be in the function itself.

At the moment as the page loads from top to bottom and when it reaches the var x = bit, the input at that time is blank, and it never gets updated when function is triggered.

Edited by dsonesuk
  • Thanks 1
Link to comment
Share on other sites

Thank you SO much for the reply it actually worked.

The user Don E said I could use "browser developer tools" to find syntax errors?

Any links or examples on that? It would help me a ton for the future.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...