获取选中复选框 [] 的输入值

Get value of input where checkbox[] is checked

我有一个问题,我需要在选中他的复选框时获取输入(文本)的值。

<form method=GET>

<input type =checkbox name = checkbox[]>
<input type = 'text' name=? >

<input type =checkbox name = checkbox[]>
<input type ='text' name=? >

<input type =checkbox name = checkbox[]>
<input type = 'text' name=? >

<input type = 'submit' name='Submit' >

</form> 

这正是我想要的

If(checkbox == checked)
{
Echo the entered input text value
}

提前致谢。

复选框和单选类型字段在未选中或未选中时不会提交。

因此您需要检查 get/request 对象对象中是否存在复选框名称。

喜欢

if(isset($_GET['checkbox'])){

}

复选框的值仅 returns 布尔值(即 true 或 false)。 你应该使用

if(isset($_GET["checkbox"]))

而不是

if(checkbox == checked)

当你勾选checkbox时你可以得到下一个输入框的值。

$("input:checkbox").change(function(){
    if(this.checked){
       alert($(this).next("input").val());
    }
});

Demo

我假设你的意思是在提交到 PHP 脚本之后。
我只是把它放在一起,还没有测试过,但看起来很简单。

它也可以与 <input type=checkbox name="c[]"> 一起使用,但只是有点担心文本和复选框与数组的同步。

HTML

<form action="./chkbx.php" method=GET>
<input type=checkbox name="c1" value="1"/>
<input type="text" name="t1" />
<input type=checkbox name="c2" value="2"/>
<input type="text" name="t2" />
<input type=checkbox name="c3" value="3"/>
<input type="text" name="t3" >
<input type="submit" name='Submit' />
</form>

PHP

foreach ($_GET as $key => $val){
  $chk[substr($key,0,1)] = intval(substr($key,1,1));
  $txt[substr($key,0,1)][intval(substr($key,1,1))] = $val;
}
echo '<h2>Text=' .  $txt['t'][$chk['c']] . '<h2>'; 

测试代码

<?php
echo <<<EOT
<!DOCTYPE html>
<html lang="en"><head><title>Menu Test</title><meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style type="text/css">
</style></head><body>

<form action="./chkbx.php" method=GET>
<input type=checkbox name="c1" value="1"/>
<input type="text" name="t1" />
<input type=checkbox name="c2" value="2"/>
<input type="text" name="t2" />
<input type=checkbox name="c3" value="3"/>
<input type="text" name="t3" >
<input type="submit" name='Submit' />
</form>
EOT;
foreach ($_GET as $key => $val){
  $chk[substr($key,0,1)] = intval(substr($key,1,1));
  $txt[substr($key,0,1)][intval(substr($key,1,1))] = $val;
}
echo '<h2>' .  $txt['t'][$chk['c']] . '<h2>';
echo '<pre>';
var_export($chk);
echo"-------------------\n";
var_export($txt);
echo '</pre></body></html>';

结果:

选中复选框 c2 且文本框包含 "Text One" "Text Two" "Text Three"

下面的输出是 echo '<h2>Text=' . $txt['t'][$chk['c']] . '<h2>';

文字二

$chk (
  't' => 3,
  'c' => 2,
  'S' => 0,
)-------------------
$txt (
  't' => 
  array (
    1 => 'Text One',
    2 => 'Text Two',
    3 => 'Text Three',
  ),
  'c' => 
  array (
    2 => '2',
  ),
  'S' => 
  array (
    0 => 'Submit',
  ),
)

总结:

提交的复选框值存储在$chk['c']
提交的文本在$txt['t'][0], $txt['t'][2], $txt['t'][3]恭敬

因此可以通过$txt['t'][$chk['c']

检索文本

循环和回显在 0.000054 秒内执行。 54 微秒,还不错。