5

I have a form that I'm trying to get data from a form using jquery and validate it. What is the best way to take data from a form to a variable using jquery?

2

4 Answers 4

5

Here is the snippet that you can use -

$('#myForm').submit(function() {
    // get all the inputs into an array.
    var $inputs = $('#myForm :input');

    // not sure if you wanted this, but I thought I'd add it.
    // get an associative array of just the values.
    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });

});

Got it from stackoverflow-link

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

Comments

2

Well here we go

This is the jQuery script:

function getData () {

$(document).ready(function() {
   var myTextFieldValue = $('#myTextField').value;
   alert('The value is: '+myTextFieldValue);
 });

}

This is the HTML

<form action='#' method='whatever'>
 <input type='text' id='myTextField' />
 <input type='submit' onClick='getData()' />
</form>

NOTE: In order to make your script working you must import the jQuery Libraries

Like this:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>

I Did not try the script so there could be some errors. Hope i was helpful to you Bye.

(For any help pm me)

1 Comment

how can somebody PM you. we can just leave comments.
0

there no way to get all the data from a form in one line of code. You have to retrieve it value by value. if you have a <input id='some-id' > just use var someId = $('#some-id').val();. Now someId hold the value of the input

The val() function only return the value of the first matched element (if you don't know what i mean take a look at jquery selector (http://api.jquery.com/category/selectors/) take a look at http://api.jquery.com/val/ to see the val function, it has some weird thing with the <textarea> tag

And remember to always validate server side, even if you already did it client side, js securrity is very easy to bypass

3 Comments

there is a way to get all the data from a form in one line of code using '$('#myform').serialize();'
@BishnuPaudel how do you then take serialized data and use it?
@gilbertbw serializeArray() might be useful in your use case. api.jquery.com/serializeArray
0

use JQuery Validation plugin. Have a look here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.