Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .val() not working for input fields

Tags:

I'm trying to capture value of my input fields and have following method in my form class to do that:

getData: function() {     var fields = ['name', 'email', 'message'];     $.each(fields, function(index, el) {         form.data[el] = $('#'+el).val();         console.log(form.data[el]);     }); }, 

(nevermind the 'select' field, that's a custom made select box and I'll have to handle that one differently) I perform the capture on form change event. The input fields all have proper id's, they look something like this:

<input type="text" id="name"> <input type="email" id="email"> <textarea name="message" id="message"></textarea> 

Now, when I type something in the fields I only get value from the textarea, while other inputs give me undefined.

I'll also note that the form is being loaded with Ajax, but since it captures the change event on the fields normally I doubt that this is the problem.

like image 816
Nicolas Avatar asked Jan 28 '14 13:01

Nicolas


People also ask

How to get the value from an input field using jQuery?

To get the value from an input field, we can use the jQuery valmethod. We can also use the val() method to set the value of an input field. var userInput = $("input").val(); Let’s say we have the following HTML:

What does val () method do in jQuery?

This method is typically used to set the values of form fields. val () allows you to pass an array of element values. This is useful when working on a jQuery object containing elements like <input type="checkbox">, <input type="radio">, and <option> s inside of a <select>.

What is the return type of Val () in jQuery?

When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .val () returns an array containing the value of each selected option. As of jQuery 3.0, if no options are selected, it returns an empty array; prior to jQuery 3.0, it returns null.

How to set the value of an input field in HTML?

We can also use the val() method to set the value of an input field. var userInput = $("input").val(); Let’s say we have the following HTML: <form> <label for="fname">Full Name:</label> <input type="text" id="fname" name="fname"> <button type="submit" value="Submit">Submit</button> </form>


1 Answers

I have figured it out.

I was missing the name attribute on my input fields and for some reason .val() needed that to work.

like image 181
Nicolas Avatar answered Sep 21 '22 19:09

Nicolas