Pre-selecting form fields when coming from different pages using jQuery
I needed to come up with a bit of code for when a client wanted their contact form to pre-select a value in a select box depending on which page they came from. This simple little bit of javascript is what I came up with in the end.
- Add the selected value to the link url after the hash like you would for an anchored link.
- Add the following code:
<script type="text/javascript">
$('document').ready(function(){
var name = window.location.hash;
if (name != ''){
// Remove the hash from the string
name = name.replace('#','');
// Add spaces
name = name.replace(/%20/g,' ');
$("#ID_TO_CHANGE").val(name);
}
});
</script>
Thats it! Simple.