2012-03-07 199 views
0

這真的推動了我的香蕉。這是如此簡單和容易,但我無法弄清楚它有什麼問題。獲取複選框組值

我想讓我的控制器中填充我的複選框值(用於測試目的)。

這是我的表格。

<a href='#' name='submitForm'>submit the form</a> 
//I have jquery attached to this tag and will submit the form when user clicks it 

echo form_open('test/show'); 

echo form_checkbox('checkbox[]','value1'); 
echo form_checkbox('checkbox[]','value2'); 
echo form_checkbox('checkbox[]','value3'); 
echo form_checkbox('checkbox[]','value4'); 

echo "<input type='text' name='text1' value='ddd'>"; 

echo form_close(); 


//My controller test 

public function show(){ 

$data1=$this->input->post('text1'); 
//I can get text1 value from input box 

$data2=$this->input->post('checkbox'); 
//it keeps giving me undefined index 'checkbox' 

$data3=$_POST['checkbox']; 
//same error message 
//WTH is going on here!!!!! 

} 

請幫忙。這東西讓我瘋狂!謝謝。

更新: 感謝您的幫助。更確切地說,我的提交按鈕是一個<a>標記,並且在form標記之外。看起來我必須在我的form標籤中包含<a>標籤才能使它們正常工作。真的嗎?

+2

'$ this-> input-> post('anything')'永遠不會給你「未定義的索引」,它總會返回FALSE或值。有一些關於你的問題是不對的。 – 2012-03-07 18:59:35

+0

@Madmartigan我從codeigniter錯誤報告中得到錯誤,不知道爲什麼。另請參閱我的更新說明。謝謝。 +1 – FlyingCat 2012-03-07 19:13:55

回答

2

一個複選框不會提交任何數據,如果它是沒有選上,他們不認爲是成功的(as per the w3c specification here

如果你確實在方框裏打勾,並提交,它會工作 - 事實上確實如此,我我剛剛測試過它。

您需要在isset()函數中調用$_POST

if(isset($_POST['checkbox'])) {} 

調用$this->input->post('checkbox')不應該給你一個未定義的索引錯誤與這種可能性的方法處理。 Input::post()方法返回false或複選框的值。

編輯 -

在回答您的修改你的問題,你必須使用input類型的元素與type屬性設置,以便提交到不使用Javascript等,這您提交表單數據按鈕必須位於您打算提交的<form></form>的內部。

<input type="submit" value="Submit"> 

type="submit"使瀏覽器發送數據的提交事件發生。如果你想使用另一個元素內部或表單外部來做到這一點,你需要使用Javascript。然而,這可以在每個瀏覽器/用戶的基礎上被禁用,並且因此不可靠。

// Standard Javascript 
<form name="myform"... 
<a onclick="javascript:document.myform.submit();" href="javascript:void(0)">Submit</a> 

// jQuery 
$('#my-a-tag-submit-button').live('click', function() { 
    $('#my-form').submit(); 
} 
+0

感謝您的幫助。請參閱我的更新說明。 +1 – FlyingCat 2012-03-07 19:12:45

+0

我修改了我的答案。 – 2012-03-07 19:28:27