SitePoint Sponsor |
|
User Tag List
Results 1 to 5 of 5
-
Dec 8, 2007, 07:21 #1
- Join Date
- Oct 2006
- Location
- Queensland, Australia
- Posts
- 852
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Update Link Depending on Drop-Down Selection
Is it possible to have part of a link (or the whole link) to change depending on the selected item in a drop-down menu within a form?
Here's what my link will look like...
HTML Code:<a href="http://www.calculator.com/calculate.php?weight=2.5kg&country=England">Calculator</a>
HTML Code:<select onchange="change_link(link)"> <option value="Australia">Australia</option> <option value="England">England</option> </select> <a href="http://www.calculator.com/calculate.php?weight=2.5kg&country=England" id="link">Calculator</a>
Thanks!
-
Dec 8, 2007, 16:10 #2
- Join Date
- Jan 2007
- Location
- Christchurch, New Zealand
- Posts
- 14,729
- Mentioned
- 104 Post(s)
- Tagged
- 4 Thread(s)
The simplest way is to place a large chunk of the link in the script.
Code JavaScript:function change_link(link) { var href = 'http://www.calculator.com/calculate.php?weight=2.5kg&country=' + link; document.getElementById('link').setAttribute('href', href); }
More complex ways can split off the required part of the existing link, modify it then place it back again.
An unoptimised way of doing this is
Code JavaScript:function change_link(value) { var a = document.getElementById('link'); var hrefParts = a.getAttribute('href').split('?'); var pairs = hrefSplit[1].split('&'); var pairSplit; for (var i = 0, l = pairs.length; i < l; i++) { pairSplit = pairs[i].split('='); if ('country' == pairSplit[0]) { pairSplit[1] = value; pairs[i] = pairSplit.join('='); hrefParts[1] = pairs.join('&'); a.setAttribute('href', hrefParts.join('?')); } } }
If you're going to be doing this kind of thing on a regular basis, there is a good querystring class that makes the job a whole lot easier for you.Last edited by paul_wilkins; Dec 8, 2007 at 20:16.
-
Dec 8, 2007, 20:04 #3
- Join Date
- Oct 2006
- Location
- Queensland, Australia
- Posts
- 852
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Thanks, but you haven't told me how I get the selected value of the drop-down, into the function.
-
Dec 8, 2007, 20:12 #4
- Join Date
- Jan 2007
- Location
- Christchurch, New Zealand
- Posts
- 14,729
- Mentioned
- 104 Post(s)
- Tagged
- 4 Thread(s)
Code HTML4Strict:<select onchange="change_link(this.value)">
-
Dec 9, 2007, 06:17 #5
- Join Date
- Oct 2006
- Location
- Queensland, Australia
- Posts
- 852
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Thanks for that, works a charm.
Bookmarks