[英]How do I get the selected value from a select box, and use it in a HTML link?
So, I have a select box in HTML. 因此,我在HTML中有一个选择框。 What I want to do is take the value of whatever item is selected, and put into a HTML link.
我想做的是获取所选项目的值,并将其放入HTML链接中。 Here's my code so far:
到目前为止,这是我的代码:
<script>
$('#cds').change(function() {
var selectVal = $('#cds :selected').val();
});
</script>
I've tried this document.getElementById("demo").innerHTML = selectVal;
我已经尝试过这个
document.getElementById("demo").innerHTML = selectVal;
, which outputs the selected item to the demo div, so I know it works, but how would I be able to output/echo the result into a link (eg: <a href="output it here">mylink</a>
), or is this even possible? ,它将所选项目输出到演示div,因此我知道它可以工作,但是如何将结果输出/回显到链接中(例如:
<a href="output it here">mylink</a>
),甚至有可能吗?
Try this: 尝试这个:
<script>
$('#cds').change(function() {
var selectVal = $(this).val();
$("a#linkToChange").attr("href", selectVal);
});
</script>
or 要么
<script>
$('#cds').change(function() {
$("a#linkToChange").attr("href", $(this).val(););
});
</script>
If you want to create the link, try this: 如果要创建链接,请尝试以下操作:
<script>
$('#cds').change(function() {
var selectVal = $(this).val();
$("div#demoDiv").append("<a href='" + selectVal + "'>Result Link</a>");
});
</script>
or 要么
<script>
$('#cds').change(function() {
$("div#demoDiv").append("<a href='" + $(this).val() + "'>Result Link</a>");
});
</script>
If you want to manipulate the existing link, try the following: 如果要操作现有链接,请尝试以下操作:
<script>
$('#cds').change(function() {
var selectVal = $(this).val();
var url = $("a#linkToChange").attr("href");
url += "/" + selectVal + "/"; // you can replace the slashes with whatever you want to prepend/append to the selected value
$("a#linkToChange").attr("href", url);
});
</script>
NOTE: As stated in the comments, leave the a
and the div
out of the selectors, in front of the #
, as they are redundant. 注意:如注释中所述,将
a
和div
保留在#
前面的选择器之外,因为它们是多余的。 I included them only so that you could see that they are <a>
and <div>
elements. 我仅包括它们,以便您可以看到它们是
<a>
和<div>
元素。
The select
's value will always be the same as the selected option, so you can use that and insert it as an anchors href directly : select
的值将始终与所选选项相同,因此您可以使用该值并将其直接作为anchor href插入:
$('#cds').on('change', function() {
$('#anchorID').attr('href', this.value);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.