2012-05-15 52 views
20

是否有辦法在複選框被選中時提交表單?當複選框被選中時提交表單

<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get"> 
    <input type ="checkbox" name="cBox[]" value = "3">3</input> 
    <input type ="checkbox" name="cBox[]" value = "4">4</input> 
    <input type ="checkbox" name="cBox[]" value = "5">5</input> 
    <input type="submit" name="submit" value="Search" /> 
</form> 

<?php 
    if(isset($_GET['submit'])){ 
     include 'displayResults.php'; 
    } 
?> 

這是我目前的,但我想提交表單沒有提交按鈕,當用戶選中或取消選中的複選框。任何幫助?

回答

40

在普通的JavaScript簡單地把

onChange="this.form.submit()" 

到表單/輸入標籤。

+0

哇,這麼簡單! –

+0

如何添加javascript確認? –

12

是的,這是可能的。

<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get"> 
    <input type ="checkbox" name="cBox[]" value = "3" onchange="document.getElementById('formName').submit()">3</input> 
    <input type ="checkbox" name="cBox[]" value = "4" onchange="document.getElementById('formName').submit()">4</input> 
    <input type ="checkbox" name="cBox[]" value = "5" onchange="document.getElementById('formName').submit()">5</input> 
    <input type="submit" name="submit" value="Search" /> 
</form> 

通過增加onchange="document.getElementById('formName').submit()"到每個複選框,你會提交複選框被更改的任何時間。

如果你使用jQuery OK,那就更簡單了(和不顯眼):

$(document).ready(function(){ 
    $("#formname").on("change", "input:checkbox", function(){ 
     $("#formname").submit(); 
    }); 
}); 

對於表單中的任意數量的複選框,當「變」事件發生時,提交表單。如果您動態創建更多複選框,這將甚至可以工作,這要感謝.on()方法。

+0

我已經實現了這個代碼,但是當我檢查複選框時,搜索結果不顯示。我需要改變php代碼嗎? – user1394849

+0

它與PHP無關 - 請檢查您的JavaScript控制檯以確保沒有錯誤。如果您點擊提交,它會起作用嗎? –

+0

完全沒有錯誤,我已經嘗試了您給我的兩條建議。 – user1394849

3
$(document).ready(
    function() 
    { 
     $("input:checkbox").change(
      function() 
      { 
       if($(this).is(":checked")) 
       { 
        $("#formName").submit(); 
       } 
      } 
     ) 
    } 
); 

雖然它很可能是更好的類添加到每一個複選框,並做

$(".checkbox_class").change(); 

,讓您可以選擇複選框提交表單,而不是所有的人都這樣做。

0

我一直在爲此亂搞四個小時左右,並決定與你分享。

你可以通過點擊一個複選框來提交表單,但奇怪的是,當檢查提交在PHP中,你會希望當你檢查或取消選中複選框時設置表單。但是這個不是真的。只有當您確實在檢查複選框時,表單纔會被設置,如果取消選中它,它將不會被設置。 複選框輸入類型末尾選中的單詞將導致複選框顯示爲選中狀態,所以如果您的字段已被選中,它將不得不反映如下例所示。當它被取消選中時,php會更新字段狀態,這會導致檢查字消失。

你的HTML應該是這樣的:

<form method='post' action='#'> 
<input type='checkbox' name='checkbox' onChange='submit();' 
<?php if($page->checkbox_state == 1) { echo 'checked' }; ?>> 
</form> 

和PHP:

if(isset($_POST['checkbox'])) { 
    // the checkbox has just been checked 
    // save the new state of the checkbox somewhere 
    $page->checkbox_state == 1; 
} else { 
    // the checkbox has just been unchecked 
    // if you have another form ont the page which uses than you should 
     make sure that is not the one thats causing the page to handle in input 
     otherwise the submission of the other form will uncheck your checkbox 
    // so this this line is optional: 
     if(!isset($_POST['submit'])) { 
      $page->checkbox_state == 0; 
     } 
} 
相關問題