8

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!

1

1 Answer 1

18

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, but then how do I assemble the object I get with serializeArray back into the string?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.