How to send form input to JavaScript?

How to send form input to JavaScript?
0

#1

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.

HTML:

`

Sumbit

`

JS:

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

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


#2

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: http://codepen.io/benjaminvanzwienen/pen/PzWraQ


#3

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.


#5

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

My pen is http://codepen.io/fooby/pen/mERZyO.


#6

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.


#7

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.


#8

Hey, glad I could help. If you have only one form element it is unnecessary to use a for loop, though. See: http://codepen.io/benjaminvanzwienen/pen/oLZXva?editors=0010


#9

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