jquery post and redirect onclick
javascript, jquery, post, window.location
Solution
Let me try to explain to you what you did and what you need to do to make your code work in the way you intended.
<script>
$('#wpsl-search-button1') // jQuery method to retrieve an element with the ID "wpsl-search-button1"
.click(function() { // Attach a "click" listener to the element
var url = '/pages/location-search/?'; // Declare a variable with the name "url" containing a string "/pages/location-search/?"
$('#wpsl-search-input1') // retrieving the element with the id "wpsl-search-input1"
.each(function() { // looping over all elements found by the id selector (ID's are unique, so the query above should always return one jQuery element. No need for a loop here)
url += 'zip=' + $(this).val() + "&"; // append a "zip" parameter with the value of the found element (this is refering to the current element of the iteration -> the input)
});
window.location.replace(url); // replace the current resource with the one in the "url" variable
});
</script>
If you just want to redirect to a url based by the input value use this code:
<script>
$('#wpsl-search-button1').click(function() { // you dont need the .each, because you are selecting by id
var inputURL = $('#wpsl-search-input1').val();
window.location.href = `/pages/location-search/?zip=${inputURL}`; // Redirecting to the passed url (also working relative to the current URL)
return false; // Cheap way to call the "event.preventDefault()" method
});
</script>
Problem
I have this html code ``` <div> <div><input id="wpsl-search-input1"/></div> <div><a id="wpsl-search-button1" href="#" target="_self">submit</a></div> </div> ``` And this jquery ``` <script> $('#wpsl-search-button1').click(function() { var url = '/pages/location-search/?'; $('#wpsl-search-input1').each(function() { url += 'zip=' + $(this).val() + "&"; }); window.location.replace(url); }); </script> ``` But for some reason it doesn't work. Any help ?