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?

gilbertbw
  • 634
  • 2
  • 9
  • 27

4 Answers4

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

Community
  • 1
  • 1
devang
  • 5,376
  • 7
  • 34
  • 49
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)

Alberto
  • 4,212
  • 5
  • 22
  • 36
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

Nickydonna
  • 802
  • 1
  • 5
  • 18
0

use JQuery Validation plugin. Have a look here

Bishnu Paudel
  • 2,083
  • 1
  • 21
  • 39