Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get and replace data from form serialize() before submitting?

I need to submit a form using jQuery but before it's submitted I want to change the value of one of the form fields without showing the change to the user. I know it's not the best way but my software demands that.

Currently I use:

var submit = $("#submitform").serialize();

To serialize data and then submit them using

$.post('/post', submit)

The serialized data I have are:

entry%5Bbody%5D=hello+and+welcome&addedContexts=presentation&context=prese ntation&selectedContexts=&statementid=&timestamp=

I simply want to change the value of entry%5Bbody%5D to something else.

I know I could use Regex on the string (I can't find which?), but maybe you know of a more elegant solution? Such as first serializing the form, then deserializing it, changing the value I need, and serializing it again?

Thanks!

like image 393
Aerodynamika Avatar asked Apr 24 '15 22:04

Aerodynamika


People also ask

How do I modify serialized form data in jQuery?

serialize returns a URL-encoded string containing the form fields. If you need to append to it, you do so using the standard URL-encoded string rules, e.g.: var values = $("#frmblog"). serialize(); values += "&content=" + encodeURIComponent(content_val);

How can I access serialized form data in PHP?

To get the POST values from serializeArray in PHP, use the serializeArray() method. The serializeArray( ) method serializes all forms and form elements like the . serialize() method but returns a JSON data structure for you to work with.

How do you serialize data in a form?

To serialize a FormData object into a query string, pass it into the new URLSearchParams() constructor. This will create a URLSearchParams object of encoded query string values. Then, call the URLSearchParams. toString() method on it to convert it into a query string.

What is the use of serialize () method in jQuery?

jQuery serialize() Method The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.


1 Answers

Use $("#submitform").serializeArray() and search for the item in the array with the name property equal to "entry[body]" and edit its value property.

// convert form data to array
var data = $("#submitform").serializeArray();

// edit data here
// using ES6
data.find(item => item.name === 'entry[body]').value = "something else";
// OR using ES5
data.forEach(function (item) {
  if (item.name === 'entry[body]') {
    item.value = "something else";
  }
});

// then POST
$.post('/post', $.param(data));
like image 93
Patrick Roberts Avatar answered Sep 22 '22 18:09

Patrick Roberts