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!

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Aerodynamika
  • 7,883
  • 16
  • 78
  • 137

1 Answers1

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));
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153