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

I need to submit a form using jQuery, but before submitting it I want to change the value of one of the form fields without showing the change to the user. I know this is not the best way, but my software requires it.

I am currently using:

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

To serialize the data and then send it using

 $.post('/post', submit) 

I have serialized data:

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

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

I know that I can use Regex in a string (I canโ€™t find what?), But maybe you know a more elegant solution? For example, first serializing the form, then deserializing it, changing the desired value and serializing it again?

Thanks!

+6
source share
1 answer

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

 // 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)); 
+8
source

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


All Articles