Reputation: 507
I have a list of options for user to choose:
<select>
<option>Twitter</option>
<option>Google</option>
</select>
After user has selected an option and pressed special button on the page, I need to transform the whole <select>
list into a link.
For example, if user selects "Google", then the whole <select>
list is replaced with:
<a href="google.com">Google</a>
If "Twitter" was selected, this will be:
<a href="twitter.com">Twitter</a>
Upvotes: 1
Views: 103
Reputation: 2399
select
with the formed link (using the grabbed value)If you want to use custom url for the selected option, just add custom value for the option like this:
<option value="yahoo.com">This is yahoo</option>
$(document).ready(function () {
$("button").click(function () {
var which = $("select").val();
var text = $('select option:selected').html();
$("select").replaceWith("<a href='http://" + which + "'>" + text + "</a>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="twitter.com">This is twitter</option>
<option value="google.com">This is google</option>
</select>
<button>Special button</button>
Upvotes: 3
Reputation: 6588
A possible solution is:
$('button').click(function(){
var select = $('select');
var value = select.val();
select.replaceWith('<a href="'+ value.toLowerCase() +'.com">'+ value +'</a>');
});
See a demo here.
EDIT:
You can set a data-something
attribute on element that you want, like:
<option data-something="apple">Smartphones</option>
Then in jQuery code:
$('button').click(function(){
var select = $('select');
var value = select.val();
var href = select.find(':selected').data('something') || value.toLowerCase();
select.replaceWith('<a href="'+ href +'.com">'+ value +'</a>');
});
Upvotes: 2