2011-03-29 105 views
1

我尝试获取当我单击指定复选框时它将用复选框的标签替换指定div中的文本,并且如果选中了多个复选框它将把他们一个,如果文字是长时间与搭起量之后...使用复选框中的特定信息填充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并不是完整的,就像复选框的功能一样,因为它是我在这里看到的另一个例子,但是没有正确回答。

+0

“标签”在哪里? – mattsven 2011-03-29 02:26:48

+0

我把它们放在我的页面上,我只是写出了真正的快速对不起的基本例子。 – Bobby 2011-03-29 02:30:21

+0

请将它们添加到示例HTML中,这样我们可以帮助...另外,您需要清楚您想要将标签的文本插入 – mattsven 2011-03-29 02:34:08

回答

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 /> 
+0

这正是我正在寻找的,但我怎么会只有一套复选框的工作,然后显示标签到TXT? – Bobby 2011-03-29 02:44:43

+0

@NexxeuS - 是的,你是对的。我只是将它改为从复选框后面的元素中获取文本。如果他真的在每个复选框后面紧贴标签... – Brandon 2011-03-29 02:47:53

+0

@Bobby - 为这些复选框添加一个特殊的类(,比如“groupA”),然后在上面的代码中将“输入:复选框”更改为“input.groupA:复选框”这两个地方。 – Brandon 2011-03-29 02:50:48

0
$("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