【问题标题】:Populate a div with specific info from a checkbox使用复选框中的特定信息填充 div
【发布时间】:2011-03-29 02:21:29
【问题描述】:

当我点击一个指定的复选框时,我试图得到它将用复选框的标签替换我指定的 div 中的文本,如果选中了多个复选框,它将把它们放在一个 ,如果文本是长的,加上后面的金额...

我的 html 看起来像:

<div style="cursor:pointer" id="st"><div id="txtst">&#9660; No Preference</div>
</div><div id="divst" style="display:none;font-size:smaller">
<input type="checkbox" name="s1" value="S"> <label for="s1">Repairs</label><br>
<input type="checkbox" name="s2" value="I"> <label for="s2">Orders</label><br>
<input type="checkbox" name="s3" value="M"> <label for="s3">Technician</label><br>

我的 js 为:

$(function(){
    $('#lf').click(function () {
        $('#divlf').toggle();
    });
    $('#st').click(function () {
        $('#divst').toggle();
    });
});
$(function(){
    $('#divst').click(function() {
        if ( $(input[checkbox]).length > 0) {
            $("#txtst").hide();
        } else {
            $("#txtst").show();
        }
    }); 
});

我知道这个 js 就复选框功能而言并不完整,因为这是我在这里看到的另一个示例,但远未正确回答。

【问题讨论】:

  • 我的页面上有它们,我只是写了基本的例子真的很抱歉。
  • 请将它们添加到示例 HTML 中,以便我们提供帮助...另外,您需要清楚 div 您尝试将标签的文本插入到什么
  • 我想将它添加到#txtst,但我发现它的示例只是显示它隐藏了那个 div。我已经添加了标签。

标签: jquery html checkbox title


【解决方案1】:

类似...

$(document).ready(function() {
    $('body').delegate('input:checkbox', 'change', function() {
        var txt = "";
        $('input:checkbox:checked').each(function(i) {
            if (txt) { txt += ","; }
            txt += $(this).next().text();

            // see if txt is too long
            if (txt.length > 50)
            {
               txt = txt.substring(0, 47) + "...";
               return false; // stop the each() loop
            }
        });
        if (!txt) { txt = "No Preference"; }
        $('#txtst').text(txt);
    });
});

如果您的复选框后面确实有标签,这将起作用:

<input type='checkbox' id='cb1'><label>Checkbox 1</label><br />
<input type='checkbox' id='cb2'><label>Checkbox 2</label><br />

【讨论】:

  • 这正是我正在寻找的,但我如何让它只工作一组复选框,然后将标签显示到 txt 中?
  • @NexxeuS - 你是对的。我只是将其更改为在复选框之后立即从元素中获取文本。如果他真的在每个复选框后面都有标签,那将起作用...
  • @Bobby - 为这些复选框添加一个特殊类(,例如“groupA”,然后将“input:checkbox”更改为"input.groupA:checkbox" 这两个地方都在上面的代码中。
【解决方案2】:
$("input[type='checkbox']").change(function(){
    if(!$("input[type='checkbox']").length > 0){
        $("#divst").html( $("label[for='"+$(this).html()+"']") );
    } else {
        $("#divst").html("You Have No Preference");
    }
});

为了让这组特殊的复选框起作用,您需要将class="group_1" 添加到您的复选框中,并将"input[type='checkbox']" 替换为.group_1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多