开发者

How do I modify serialized form data in jQuery?

开发者 https://www.devze.com 2023-02-13 03:11 出处:网络
I am tr开发者_高级运维ying to submit my form in AJAX, so I have to serialize() the data. But I am using fckEditor and jQuery doesn\'t know how to deal with it, so after the serialization, I am trying

I am tr开发者_高级运维ying to submit my form in AJAX, so I have to serialize() the data. But I am using fckEditor and jQuery doesn't know how to deal with it, so after the serialization, I am trying to manually modify the value, but no luck so far... any ideas

if(content_val!=""){
    var values = $("#frmblog").serialize();
    values.content = content_val; //content_val is the manually fetched data which I am trying to insert into the serialized content.
    alert(content_val); alert(values);
}


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);

(The above assumes there will always be one value in values after the serialize call; if that's not necessarily true, determine whether to use & based on whether values is empty before you add to it.)

Alternately, if you like, you can use serializeArray and then add to the array and use jQuery.param to turn the result into a query string, but that seems a long way 'round:

// You can also do this, but it seems a long way 'round
var values = $("#frmblog").serializeArray();
values.push({
    name: "content",
    value: content_val
});
values = jQuery.param(values);

Update: In a comment added later you said:

The problem is, there is some default values being set in the 'content' key during the serilization process, so I can't just attach a new value, I have to update the one already in it"

That changes things. It's a pain to look for content within the URL-encoded string, so I'd go with the array:

var values, index;

// Get the parameters as an array
values = $("#frmblog").serializeArray();

// Find and replace `content` if there
for (index = 0; index < values.length; ++index) {
    if (values[index].name == "content") {
        values[index].value = content_val;
        break;
    }
}

// Add it if it wasn't there
if (index >= values.length) {
    values.push({
        name: "content",
        value: content_val
    });
}

// Convert to URL-encoded string
values = jQuery.param(values);

You'd probably want to make this a reusable function.


With ES15 now. You can use this instead one for editing current submitted value (the shortest one)

var values = $("#frmblog").serializeArray();
values.find(input => input.name == 'content').value = content_val;
console.log(values);

or native function

var values = $("#frmblog").serializeArray();
values.find(function(input) { 
    return input.name == 'content';
}).value = content_val;
console.log(values);


Here is a full jquery plugin based on @T.J's answer. You can call

$('form#myForm').awesomeFormSerializer({
    foo: 'bar',
})

Which will replace or add the param 'foo' with value 'bar' (or any other param you add in the object)

jQuery plugin :

// Not builtin http://stackoverflow.com/a/5075798/2832282
(function ( $ ) {
    // Pass an object of key/vals to override
    $.fn.awesomeFormSerializer = function(overrides) {
        // Get the parameters as an array
        var newParams = this.serializeArray();

        for(var key in overrides) {
            var newVal = overrides[key]
            // Find and replace `content` if there
            for (index = 0; index < newParams.length; ++index) {
                if (newParams[index].name == key) {
                    newParams[index].value = newVal;
                    break;
                }
            }

            // Add it if it wasn't there
            if (index >= newParams.length) {
                newParams.push({
                    name: key,
                    value: newVal
                });
            }
        }

        // Convert to URL-encoded string
        return $.param(newParams);
    }
}( jQuery ));


use the following function it worked for me

function(elementName,newVal)
{
    var postData = $("#formID").serialize();

var res = postData.split("&");
var str = "";

for(i=0;i<res.length;i++)
  {
    if(elementName == res[i].split("=")[0])
      {
        str += elementName + "=" + newVal+ "&";
      }
      else
      {
        str += res[i] + "&";
      }
  }
return str;
}


This is how I would accomplish what you need

formData = $('#'+formID).find(":input")
                            .filter(function (i, item) {
                                if (item.name.includes('nameToBeChanged'))
                                {
                                    item.name = item.name.replace('nameToBeChanged', 'toChangedName');
                                    return true;
                                } else {
                                    return false;
                                }
                            }).serialize();

Do realize that this will change the form element names permanently

0

精彩评论

暂无评论...
验证码 换一张
取 消