Reputation: 3
I'm trying to change a series of links by inserting values from a dropdown box. I found this straight forward to do with php (code below) but I'd like to be able to change the links without 1) having a page refresh (these links are near the bottom of the homepage) and 2) without a submit button if possible.
Here is the php code:
<form name="test" action="<?php echo
htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<select name="county" id="select13">
<option value="All">All</option>
<option value="County1">County1</option>
<option value="County_2">County 2</option>
...
</select>
<input type="submit" name="submit" value="Set County">
</form>
<?php
if(isset($_POST['submit']))
{
$county = $_POST['county'];
$www = "http://www.website.com/";
$food = "/topics/Food/programs.aspx";
$meals = "/topics/Meals/programs.aspx";
....
echo "<a href=$www/$county/$food>Food</a><br>";
echo "<a href=$www/$county/$meals>Meals</a><br>";
The above code works fine, but requires a page refresh. I was attempting to use jquery to just take a list of links, such as:
<a href="http://www.website.com/topics/county/Food/programs.aspx">Food</a>
And just replace "county" with the value from a dropdown box.
function changelinks(){
var countyvals = $("#county").val();
$("a[href^='http://www.webpage.com/topics/']")
.each(function(){
this.href = this.href.replace(/^http:\/\/www\.webpage\.com\/topics\//,"http://www.webpage.com/topics/"+countyvals);
});}
The above code works fine changing the link once, but after the link is changed I can't target the links anymore. I just started teaching myself jquery today, so I've no idea where to look for a better solution.
What might be the best way of changing these links? Should I try some ajax on the php code, or is there a better/simpler solution through jquery?
THANKS!
Upvotes: 0
Views: 2173
Reputation: 6237
I would use HTML 5 data attributes. Have a data-relativeurl
attribute on each anchor of interest, then you can use
function changelinks(){
var countyvals = $("#selector13").val();
$("a[href^='http://www.webpage.com/topics/']")
.each(function(){
this.href = "http://www.webpage.com/" + countyvals + $(this).attr('data-relativeurl');
});}
Upvotes: 1