How to send form input to JavaScript?

I’m going back through the basic JavaScript course, as I’ve reached the basic algorithm section, but feel I skipped through the basics without letting them sink in properly.

It helps me a lot to use what I’m learning in a visual manner, so I’m making a new Pen for each thing I learn. I thought I’d practice if/else statements by creating a form that asks for your name, and then tells you how long it is, but I’m struggling to work out how to make the HTML talk to the JavaScript. Any ideas what I might do? I haven’t got to actually telling you how many letters there are, just trying to get the basics sorted.

I want to run the JS when clickme is clicked, taking the value of name.






var submitForm = document.getElementById(“name”);

if(submitForm.length < 10) {
console.log(“Your name is short.”)
else {
console.log(“Your name is long.”)

Hey, you can use:
submitForm.addEventListener("submit", function(e){ e.preventDefault(); //make sure the page doesn't reload //do anything you want });

Here is a working example:

1 Like

looks like you have it pretty much right, but instead getting the length of the <input> element, you probably want to get the length of the value of that element. So instead of this:

var submitForm = document.getElementById("name");

if you do this:

var submitForm = document.getElementById("name").value;

your function should work.

1 Like

Thanks, I did try adding .value, but the console still always shows the short statement.

My pen is

You don’t have an event listener for the user submitting.
Your code just runs on page load and the value is empty.
Check BenGitter’s reply.

Thanks for the help, I managed to work out what was going on in @BenGitter’s reply and do something similar.

This is the Pen if anyone is interested.

Hey, glad I could help. If you have only one form element it is unnecessary to use a for loop, though. See:

Thanks, that’s perfect. Thought there must be a way without using a loop.