jquery - 已选择单选按钮并更新 <span>

标签 jquery

我有一个 DIV,其中包含单选按钮列表和“选定搜索”区域( <span> )。当单击“选定的搜索”区域时,会出现一个下拉层,其中包含带有单选按钮列表的 DIV。选择单选按钮后,“所选搜索”区域将使用该单选按钮的文本进行更新,并且下拉层会折叠/消失。

这是我的 HTML 结构:

<div class="radio-btns"><span class="selected-search">A</span>
 <div class="radio-btns-wrapper">
  <label><input type="radio" value="a" id="a" checked>A</label>
  <label><input type="radio" value="b" id="b">B</label>
  <label><input type="radio" value="c" id="c">C</label>
  <label><input type="radio" value="d" id="d">D</label>
 </div>
</div>

你知道如何用 jQuery 来完成这个任务吗?任何帮助将不胜感激。

谢谢。

** 编辑 **

自从我在 2010 年提出这个问题以来,我现在在 jQuery 方面有了一些改进,所以这里有一个修改后的标记,因为上面的标记并不理想。

新的 HTML 结构:

<a href="#" class="selected-search">A</a>
<div class="radio-btns-wrapper">
    <label><input type="radio" value="a" id="a" name="radio" checked>A</label>
    <label><input type="radio" value="b" id="b" name="radio">B</label>
    <label><input type="radio" value="c" id="c" name="radio">C</label>
    <label><input type="radio" value="d" id="d" name="radio">D</label>
</div>

jQuery 脚本:

这是对下面 @Greg 答案的改进:

//If JS is available, hide the radio buttons container
$(".radio-btns-wrapper").hide();

//DIV with radio buttons will slide down when clicking on .selected-search
//The default action on the link <a> is removed (preventDefault();) to avoid having the page jump to the back top
$(".selected-search").click(function (e) {
    $(".radio-btns-wrapper").slideDown();
    e.preventDefault();
});
//Click on radio button and have target text update with radio button's text
$("input[type=radio]").click(function () {
    // Alter the text of the span to the text of the clicked label
    $(".selected-search").text($(this).parent().text());
    // Now hide the radios
    $(".radio-btns-wrapper").slideUp();
});

由于所选答案中的演示链接不再有效,因此我创建了自己的演示。您可以在这里看到它:http://jsfiddle.net/rzea/vyvLvgkh/4/

最佳答案

这是一个带有示例的 JsFiddle:

http://jsfiddle.net/g105b/VHBkP/ (演示似乎已从 jsfiddle.net 中删除)

这是一个工作演示的链接:http://jsfiddle.net/rzea/vyvLvgkh/5/ - 请参阅上面的编辑以获取改进的标记和新脚本。

$(".radio-btns").click(function() {
    $(".radio-btns-wrapper").toggle();
});

$("input[type=radio]").click(function() {
    // Alter the text of the span to the text of the clicked label.
    $(".selected-search").text($(this).parent().text());
    // Now hide the radios.
    $(".radio-btns-wrapper").hide();
});

关于jquery - 已选择单选按钮并更新 <span>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4305772/

相关文章:

javascript - BackboneJS - 导航菜单

javascript - 循环遍历一组元素 jQuery

javascript - jQuery:仅在特定 div 中触发 keydown

jquery - Grails JQuery Ajax 表单验证

php - 使用 AJAX 更新 DOM 以反射(reflect)数据库中的更改的最佳方法是什么?

javascript - 将背景图像设置为动态 svg 数据?

javascript - 动画jquery只工作一次

jquery - Chrome 在 try/catch block 中因异常而暂停,如何自动恢复?

javascript - 如何将 JQuery AJAX 函数转换为 vue.js

javascript - Wordpress Contact-form 7 - 使用 Jquery 的预订表单功能