You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在a标签的href中获取单选框input的选中值?

解决方案:将选中单选框的值赋值给a标签的href

你可以通过原生JavaScript监听单选框的选中状态变化,动态更新a标签的href属性,具体实现步骤如下:

步骤1:调整HTML结构

给目标a标签添加唯一ID,方便后续JS获取元素;同时修正button的类型避免默认表单提交行为:

<?php 
$url = 'wwww.exemplo.com/checkout1';
$url2 = 'wwww.exemplo.com/checkout2';
$url3 = 'wwww.exemplo.com/checkout3';
$url4 = 'wwww.exemplo.com/checkout4';
?>
<form>
  <input type="radio" name="opcao" id="1" value="<?php echo $url;?>">
  <input type="radio" name="opcao" id="2" value="<?php echo $url2;?>">
  <input type="radio" name="opcao" id="3" value="<?php echo $url3;?>">
  <input type="radio" name="opcao" id="4" value="<?php echo $url4;?>">    
  <a href="" id="checkout-link"><button id="submit" type="button">Submit</button></a>
</form>

步骤2:添加JavaScript逻辑

监听所有单选框的change事件,当单选框被选中时,将其value(即PHP生成的结账链接)赋值给a标签的href:

// 获取所有单选框和目标a标签
const radioButtons = document.querySelectorAll('input[name="opcao"]');
const checkoutLink = document.getElementById('checkout-link');

// 监听单选框选中变化
radioButtons.forEach(radio => {
  radio.addEventListener('change', function() {
    if (this.checked) {
      checkoutLink.href = this.value;
    }
  });
});

// 页面加载时初始化默认选中项(可选)
document.addEventListener('DOMContentLoaded', function() {
  const defaultChecked = document.querySelector('input[name="opcao"]:checked');
  if (defaultChecked) {
    checkoutLink.href = defaultChecked.value;
  }
});

补充说明

  • 如果需要默认选中某个选项,给对应的单选框添加checked属性即可,比如<input type="radio" name="opcao" id="1" value="<?php echo $url;?>" checked>
  • 若不需要表单提交功能,可以移除<form>标签,不影响功能实现

内容的提问来源于stack exchange,提问作者Iago Arrelias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 01:57:54