Reputation:
I want to open link using Jquery by clicking on anchor by using its anchor id in change function. Please help me to open it
<div id="div1" style="display:none">
<a id="0" href="http://www.friferie.dk/inspiration/Belgien">Belgium</a>
<a id="1" href="http://www.friferie.dk/inspiration/Bulgarien">Bulgarien</a>
<a id="2" href="http://www.friferie.dk/inspiration/Danmark">Danmark</a>
</div>
**I want to pass id then open particular href into it**
$ ("").change(function () {
}
Upvotes: 0
Views: 5401
Reputation: 21
<div id="div1" style="display:none">
<a id="0" href="#" onclick="onChange(this)">Belgium</a>
<a id="1" href="#" onclick="onChange(this)">Bulgarien</a>
<a id="2" href="#" onclick="onChange(this)">Danmark</a>
</div>
<script>
function onChange(obj){
var id= $(obj).attr("id");
switch(id){
case "0":
window.location.href="http://www.friferie.dk/inspiration/Belgien";
break;
case "1":
window.location.href="http://www.friferie.dk/inspiration/Bulgarien";
break;
case "2":
window.location.href="http://www.friferie.dk/inspiration/Danmark";
break;
}
}
</script>
Upvotes: 0
Reputation: 93561
Long version (for readability):
$ ("#someselector").change(function () {
// Get selected value
var val = $(this).val();
// Use the selected value to create a jQuery ID selector to get the link
var link = $('#' + val);
// get the href value
var href = link.attr("href");
// Change the browser location
window.location = link;
});
Or simulate a link click:
$ ("#someselector").change(function () {
// Get selected value
var val = $(this).val();
// Use the selected value to create a jQuery ID selector and get the link
var link = $('#' + val);
// Click the link
link[0].click();
});
I tend to use [0].click()
and not the jQuery click()
here as it hits the underlying browser implementation (and we won't care about the jQuery extras as the page will change).
e.g.
$ ("#someselector").change(function () {
window.location = $('#' + $(this).val()).attr("href");
});
or
$ ("#someselector").change(function () {
$('#' + $(this).val())[0].click(); // Or `).click()` is you want it shorter
});
Upvotes: 1
Reputation: 74738
yes with select by a dropdown of a dropdownlist using its id
As per this comment, you can do this :
$("#dropdown").change(function(e){ // change event on dropdown
$('#'+this.value).click(); // and apply the click on specific anchor
// $('#'+this.value).get(0).click(); // comparing to selected value
});
Upvotes: 0