2013-04-20 34 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