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.
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:
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>.
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.
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>
I have figured it out.
I was missing the name attribute on my input fields and for some reason .val() needed that to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With