0

I can't figure out why .value isn't working. I've also tried .querySelector instead of .getElementById, but I keep getting undefined in the console.

var submit = document.querySelector('#submit');
var name = document.getElementById('ship-name');

submit.onclick = function() {
  console.log(name.value);
};
<div class="box">
  <h2>Where do you want your stuff sent?</h2>
  <label for="ship-name">
    <input class="full text-input" id="ship-name" type="text" placeholder="Name" required>
  </label>
  <label for="ship-add-1">
    <input class="full text-input" id="ship-add-1" type="text" placeholder="Address Line 1" required>
  </label>
  <label for="ship-add-2">
    <input class="full text-input" id="ship-add-2" type="text" placeholder="Address Line 2" required>
  </label>
  <label for="ship-add-3">
    <input class="full text-input" id="ship-add-3" type="text" placeholder="Address Line 3" required>
  </label>
  <label for="ship-4">
    <input class="full text-input" id="ship-add-4" type="text" placeholder="Address Line 4" required>
  </label>
</div>

5
  • 1
    Where's an element with the ID of submit? Commented Jul 14, 2016 at 19:11
  • 3
    You cannot create a variable called name in the global scope. This will be a reference to window.name which will always be a string. Commented Jul 14, 2016 at 19:12
  • When I run the snippet in SO, it throws an error saying you can't set property 'onclick' of null - maybe this has something to do with it? Commented Jul 14, 2016 at 19:13
  • 2
    Cannot set property 'onclick' of null is due to the fact that submit does not exist in the snippet. But even if it is added, name will be a string and not an element, and a string doesn't have a value property. Just rename the variable shipName or something else, and the problem will go away. Commented Jul 14, 2016 at 19:14
  • Thank you David, that did it! Commented Jul 14, 2016 at 19:40

3 Answers 3

0

change the code in your .js file to be:

document.getElementById('submit').onclick = function () {
 console.log(document.getElementById('ship-name').value);
}

as mentioned in the comments you are misusing global space.

Also, remember to include the script after the html it is referencing.

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks everyone. David H's answer fixed the issue. I just changed the variable name to something else and it worked. He was right that you can't have a variable called name in the global scope.

Comments

-2

Have you tried?

var name = $('#ship-name').val();

And then

console.log(name);

3 Comments

Is not about jquery.
Does your button has the id property set to "submit"?
Yeah, the button is working and the click is being recognized.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.