Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  15] [ 2]  / answers: 1 / hits: 18763  / 10 Years ago, wed, june 4, 2014, 12:00:00

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 ?


More From » jquery

 Answers
26

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>

[#70722] Tuesday, June 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mitchell

Total Points: 95
Total Questions: 110
Total Answers: 87

Location: Gabon
Member since Thu, Jul 15, 2021
3 Years ago
;