dimanche 11 juin 2017

Converting Checkbox formfields to name value pairs for form submission

I have a bunch of checkboxes that I have to submit to a serverside script that I can't change. The server is expecting values in the format scriptname?town=townA&town=townB etc. My checkboxes (dynammically generated) have the name of the town so are currently appearing in my query string as scriptname?townA=On&townB=On etc

I'd like to use jQuery to catch the form data before it is posted to change the format from one to the other. I've been trying to do this with the following code but I can't get it working:

$("#frmmap").click(function () {

        var myarr = $('#myform').getFormValues();
        $.each(myarr, function (key, value) {
            alert(key + ": " + value);
        });
  /$("#frmmap").submit();
    }); 


    jQuery.fn.getFormValues = function () {
        var formvals = {};
        jQuery.each(jQuery(':input', this).serializeArray(), function (i, obj) {
            if (formvals[obj.name] == undefined)
                formvals[obj.name] = obj.value;
            else if (typeof formvals[obj.name] == Array)
                formvals[obj.name].push(obj.value);
            else formvals[obj.name] = [formvals[obj.name], obj.value];
        });
        return formvals; 




Aucun commentaire:

Enregistrer un commentaire