-
-
Save ivan-kalachikov/5bf83924ef00ee70e4796366ef59de91 to your computer and use it in GitHub Desktop.
Serialize and get request
This file contains hidden or 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
$('.search-product a.btn-submit').click(function (e) { | |
e.preventDefault(); | |
var data = $(this).closest('form').serialize(); | |
var url = $(this).attr('href'); | |
url = url + '?products-filters&' + data; | |
window.open(url,"_self") | |
}) | |
$('.section-product form').change(function () { | |
var data = $(this).serialize(); | |
history.replaceState(null, null, window.location.protocol + "//" + window.location.host + window.location.pathname + '?products-filters&' + data); | |
}) | |
$.fn.deserialize = function (serializedString) { | |
var $form = $(this); | |
$form[0].reset(); | |
serializedString = serializedString.replace(/\+/g, '%20'); // (B) | |
var formFieldArray = serializedString.split("&"); | |
// Loop over all name-value pairs | |
$.each(formFieldArray, function(i, pair){ | |
var nameValue = pair.split('='); | |
var name = decodeURIComponent(nameValue[0]); | |
var value = decodeURIComponent(nameValue[1]); | |
// Find one or more fields | |
var $field = $form.find('[name=' + name + ']'); | |
if ( ! $field.length ) { | |
return; | |
} | |
// 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 if ($field.prop('tagName') =='SELECT') { //select | |
$field.find('option[value="' + value + '"]' ).attr('selected', 'selected'); | |
} else { // input, textarea | |
$field.val(value); | |
} | |
}); | |
return this; | |
} | |
if (location.search.substr(1).indexOf('products-filters') == 0) { | |
$('.section-product form').deserialize(location.search.substr(1)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment