How to save form values ​​in data () object?

Is there an easy way to store form data in an object data()after submission?

Suppose this is my form:

<form id='myform'>  
<input type='text' name='bar' value='lorem'/>  
<input type='text name='foo' value='ipsum'/>  
</form>

After sending, the data should be stored as follows:

$("#myform").data('bar','lorem');  
$("#myform").data('foo','ipsum');
+3
source share
1 answer

You can do something like this:

$('#myform').submit(function(e) {
    e.preventDefault(); // don't submit the form
    var form = $(this); // store it for later reference
    form.children('input').each(function() {
        form.data($(this).attr('name'), $(this).attr('value'));
    });
});

Change . There were some errors ( getChildren" children, myform" #myform) in my code . Now I fixed it.

Please note that this script does not submit the form. You can add some great ajax to do this :) http://docs.jquery.com/Ajax/serialize

. jQuery : form.serialize(). :

<form id="myForm">
    <input type="radio" value="A" name="foo" checked="checked" /> A<br />
    <input type="radio" value="B" name="foo" /> B
    <input type="text" name="bar" value="Bla bla" />
</form>
<script>
var queryString = $('#myForm').serialize(); //foo=A&bar=Bla+bla
</script>
+3

Source: https://habr.com/ru/post/1706636/


All Articles