本文介绍了如何获得与复选框关联的标签的值(我是否破坏了jsfiddle)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要构建用户选择的部门编号的csv.

I need to build a csv of dept numbers the user selects.

我从以下HTML开始:

I started off with this HTML:

<button id="btnDept">select Depts</button>
<div id="dialog" title="Select the Depts you want to include in the report" style="display:none;">
    <div>
        <label for="ckbx2">2</label>
        <input type="checkbox" id="ckbx2" />
        <label for="ckbx3" id="lbl3">3</label>
        <input type="checkbox" id="ckbx3" />
    </div>
</div>

...还有这个jQuery:

...and this jQuery:

var deptsSelected = '';
$("#btnDept").click(function () {
    $("#dialog").dialog({
        modal: true
    });
    $('checkbox').click(function() {
        deptsSelected += this.val + ',';
        alert(deptsSelected);
    });
});

...对于显示选定的部门毫无用处-并且很有道理,因为"this"可能是复选框,当然也不是标签.在此对话框中,我将有数十个复选框,并且不想编写这样的内容:

...that does nothing about showing depts selected -- and that makes sense, as "this" is presumably the checkbox, and certainly not the label. I am going to have dozens of checkboxes in this dialog, and don't want to have to write something like this:

$('#ckbx3').click(function(){ deptsSelected + = $('lbl3').val +','; 警报(deptsSelected);});

$('#ckbx3').click(function() { deptsSelected += $('lbl3').val + ','; alert(deptsSelected);});

...对于每个复选框/标签对(即使使用这种蛮力方法,上面的代码也显示了此警报,而不是我期望的/希望的:

...for each and every checkbox/label pair (even with this brute force approach, though, the code above showed this alert, not what I was expecting/hoping for:

天堂般的Murgatroid/什么是kerfluffle?!

Heavens to Murgatroid/what the kerfluffle?!?

jsfiddle在这里: http://jsfiddle.net/clayshannon/aWpPN/

The jsfiddle is here: http://jsfiddle.net/clayshannon/aWpPN/

推荐答案

请尝试以下操作:

var deptsSelected = '';
$("#btnDept").click(function () {
    $("#dialog").dialog({
        modal: true
    });
    $("input:checkbox").click(function () {
        deptsSelected += $("label[for='" + this.id + "']").text() + ',';
        alert(deptsSelected);
    });
});

这是它的小提琴: http://jsfiddle.net/yFB6W/

这篇关于如何获得与复选框关联的标签的值(我是否破坏了jsfiddle)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 21:39