2013-04-20 56 views
2

我有相同名称的约20复选框,但ID值是不一样的jQuery函数 - 复选框同名

<input type="checkbox" name="device" id="1_2"/> 
<input type="checkbox" name="device" id="10_4"/> 
<input type="checkbox" name="device" id="5_6"/> 
<input type="checkbox" name="device" id="4_0"/> 
<input type="checkbox" name="device" id="8_9"/> 
<input type="checkbox" name="device" id="3_4"/> 

我希望有一个功能,如果我在一个复选框单击,然后我得到一个警报ID为

例中的价值,如果我点击第一个复选框

alert("Value before _ : 1 - Value after _ : 2") 

我怎么能这样做?

+1

你不应该有名称属性具有相同值的复选框。表单发布后,您只会获得一个复选框的值。 – Ejaz 2013-04-20 18:10:03

+0

你想显示取消选择的值,然后显示新值? – 2013-04-20 18:10:12

+0

'alert(“_之前的值:1 - _之后的值:2”)'这里需要什么?这里的'1和2'是什么? – Jai 2013-04-20 18:13:08

回答

1

下面是一个例子:jsfiddle

希望它的你所需要的,有它的乐趣玩。

HTML:(一类添加到输入)

<input class='try' type="checkbox" name="device" id="1_2"/> 
<input class='try' type="checkbox" name="device" id="10_4"/> 
<input class='try' type="checkbox" name="device" id="5_6"/> 
<input class='try' type="checkbox" name="device" id="4_0"/> 
<input class='try' type="checkbox" name="device" id="8_9"/> 
<input class='try' type="checkbox" name="device" id="3_4"/> 

SCRIPT:(点击事件)

$('.try').click(function() { 
    var idd= $(this).attr('id'); 
    var explode = idd.split('_'); 
    alert('Value before:' + explode[0] + ' - Value after:' + explode[1]); 
}); 
+1

'$(this).attr('id')。split('_');'它很好,但'this.id.split('_');'好得多。 – Jai 2013-04-20 18:18:44

1

这是你在找什么

 $(document).ready(function() { 
     $('input[type="checkbox"]').click(function(){ 
      var vals = this.id.split('_'); 
      alert("Value before _ : "+vals[0]+" - Value after _ : " + vals[1]) 
     }) 
    }) 

调用此函数在每个复选框的点击。它使用javascript的split函数将分割成将id属性值转换为数组。

+1

这很棒@凯文伦。您可以通过点击旁边的勾号将最有帮助的答案标记为答案。这将有助于未来的访问者和您未来获得最佳答案。 – Ejaz 2013-04-21 10:04:07

0
$("input[type=checkbox]").click(function(){ 
    arr = $(this).attr("id").split("_"); 
    alert("Value before _ :"+arr[0]+" Value after _ :"+arr[1]); 
}); 

这里是jsFiddle

1

这是你需要什么? Demo

$('input:checkbox[name="device"]').click(function(){ 
    var id = $(this).attr('id'); 
    alert('Value before:' + id.split('_')[0] + ' - Value after:' + id.split('_')[1]); 
    }); 
0
$("input[type=checkbox]").click(function(){ 
    alert($(this).attr("id")) 
}); 
0

我希望这将有助于:

 
    $('input:checkbox[name="device"]').click(function(){ 
     var selected_data = $(this).attr('id').split('_'); 
     alert('Value before _ : ' + selected_data[0] + ' - ' + 'Value after _ : ' +  selected_data[1]); 
    }); 

+0

这段代码只会选中名称为“设备”的复选框。即使你有任何其他复选框出于任何目的,它也不会起作用。享受编码! – 2013-04-20 18:46:32