Last active
October 17, 2019 12:33
-
-
Save frzsombor/45823512ab99696231bd4018def1816c to your computer and use it in GitHub Desktop.
jQuery form deserialize from serialize()-d string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Based on: https://stackoverflow.com/a/24441276/2953830 | |
//Few things fixed by frzsombor | |
$.fn.deserialize = function(serializedString) { | |
var $form = $(this); | |
$form[0].reset(); // (A) optional | |
serializedString = serializedString.replace(/\+/g, '%20'); // (B) | |
var formFieldArray = serializedString.split('&'); | |
if (!serializedString) { | |
return this; | |
} | |
// Loop over all name-value pairs | |
$.each(formFieldArray, function(i, pair){ | |
var nameValue = pair.split('='); | |
var name = decodeURIComponent(nameValue[0]); // (C) | |
var value = decodeURIComponent(nameValue[1]); | |
// Find one or more fields | |
var $field = $form.find('[name="' + name + '"]'); | |
// Checkboxes and Radio types need to be handled differently | |
if ($field[0].type === 'radio' || $field[0].type === 'checkbox') | |
{ | |
var $fieldWithValue = $field.filter('[value="' + value + '"]'); | |
var isFound = ($fieldWithValue.length > 0); | |
// Special case if the value is not defined; value will be "on" | |
if (!isFound && value === 'on') { | |
$field.first().prop('checked', true); | |
} else { | |
$fieldWithValue.prop('checked', isFound); | |
} | |
} else { // input, textarea | |
$field.val(value); | |
} | |
}); | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment