How to get the text written in text input

I'm trying to grab the txt I wrote inside the my <input type="text"> but it is returning undefined , I tried many ways such as .text() or .html() or e.target.value , all of them returned undefined including this innerHTML too

   $('input[type=text]').keyup(function(e){
      if(e.which == 13){
        alert($('input[type=text]').innerHTML);

      }
   });

Upvotes: 2

Views: 683

Answers (1)

Kinglish
Kinglish

Reputation: 23654

You are mixing jQuery with Vanilla and they aren't the same. First of all, this was not going to work either way because form elements have values, not HTML. However, lets say you had tried this: alert($('input[type=text]').value);

value is a property of an html input element, but does not exist in a jQuery object. The jQuery object represents the form element, but wraps it in an extra set of properties and methods. If you truly wanted to mix them you could reference the form element from the jQuery object like:

alert($('input[type=text]')[0].value);

But it's better for legibility and consistency to stay with one or the other, which in jQuery would be

alert($('input[type=text]').val());

but as you're inside a jQuery event handler for that element, you can get it with

alert($(this).val());

Upvotes: 1

Related Questions