2010-07-29 87 views
14

嘿,我想知道如何獲取複選框的ID時,它被檢查。獲取複選框的ID? - jQuery

這是我的HTML可能會像起初:

<div class="check_filter"> 

    <div id="filter"> 
     <input type="checkbox" id="check1" /><label for="check1">Marketing</label> 
     <input type="checkbox" id="check2" /><label for="check2">Automotive</label> 
     <input type="checkbox" id="check3" /><label for="check3">Sports</label> 
    </div> 

</div><!-- End check_filter --> 

我假設了jQuery會是這個樣子:

$(document).ready(function() {  
    $(":checkbox").click(function(){ 
     var id = $(this).attr('id'); 

     $.post("index.php", { id: id }); 
     //return false to ensure the page doesn't refresh 
     return false; 
    });  
}); 

我試圖讓檢查item id,然後在mysql查詢中發佈該id以從數據庫中獲取id的結果。

感謝您的任何幫助。

+1

我會使用'change'事件而不是'click'事件複選框。否則,它看起來像你的代碼應該工作得很好。你試過了,發現它沒有? – 2010-07-29 15:09:57

回答

15

你可能想在change事件在這裏,像這樣:

$(function() { 
    $(":checkbox").change(function(){ 
    $.post("index.php", { id: this.id, checked: this.checked }); 
    });  
}); 

無論何時複選框發生變化,PHP端都會知道這個ID以及它是否被選中。

+0

對於'this.id'等的+1,但是你忘了將'click'改爲'change'(在代碼中)。 :o)編輯:已更正。 – user113716 2010-07-29 15:14:15

+0

@patrick - Wops,fixed,@Generic - 你可以在這裏測試它:http://jsfiddle.net/nick_craver/zM4md/它可以與空格等工作:) – 2010-07-29 15:15:15

+0

我做了一個例子後,我發表了評論。道歉,看起來像去年一樣。 – GenericTypeTea 2010-07-29 15:19:08

7

您提供的jQuery工作正常嗎?您應該刪除return false顯示複選框已被選中。編輯:$.post()是一個異步請求(AJAX技術),所以不會刷新頁面。

編輯2:您可能也想看看是否複選框檢查(不僅僅是它已被點擊):

$(document).ready(function() {  
    $(":checkbox").click(function(){ 
     var id = $(this).attr('id'); 
     var isChecked = $(this).attr('checked')); 
     $.post("index.php", { id: id, isChecked: isChecked }); 
    });  
}); 
1

你可以更好地使用jQuery get而不是post。它可以讓你處理你的請求的輸出:http://api.jquery.com/jQuery.get/

例子:爲了訪問值

$(document).ready(function() {  
    $(':checkbox').click(function(){ 
     var id = $(this).attr('id'); 
     var isChecked = $(this).attr('checked')); 
     $.get(
      'getcheckbox.php', 
      { id: id, isChecked: isChecked }, 
      function(data) { 
      //return value in getcheckbox.php and use it in on complete function 
      var result = data; 
      } 
     ); 
    });  
}); 
0

爲什麼我只需要這個複選框的名字,但是$(本)

$('input:checkbox').change(function() { 
     console.log("here i am: " + this.name + " value = " + $(this).val()); 
     } 
    ); 
2

您可以使用:checkbox選擇,然後檢查id和檢查的DOM元素的屬性,像這樣:

var id = $(this).find(":checkbox")[0].id; var isChecked = $(this).find(":checkbox")[0].checked;