PHP不会使用Checkbox数组结果回显HTML

时间:2017-08-24 15:04:27

标签: php html checkbox echo

我很难过!我得到了漂亮的结果,但我无法显示相关的文字"只有"当用户选择某事时。就像现在一样,文本是静态的,并且无论是否有用户选择的答案都会一直显示。

实施例。 "什么样的动物:"在结果页面上,即使用户没有选择答案!如果没有相关答案,则需要显示的是什么。

我的HTML:

    <!-- SHOW/HIDE TEXT FIELD -->
    <!-- IF BITTEN ANIMAL="YES" or BITTEN "BOTH" Show Field -->
<div id="hidden_textfield10" style="display:none;">
    <p class="data_bold">What Kind of Animal</p><div class="data_small">What kind of animal has your pet bitten? Check all that apply:</div>
    <label for="Wild"><input class="form_style" type="checkbox" value="Wild" id="Wild" name="whatKindofAnimal[5]" />Wild</label><br />
    <label for="Bird"><input class="form_style" type="checkbox" value="Bird" id="Bird" name="whatKindofAnimal[4]" />Bird</label><br />
    <label for="Cat"><input class="form_style" type="checkbox" value="Cat" id="Cat" name="whatKindofAnimal[3]" />Cat</label><br />
    <label for="Dog"><input class="form_style" type="checkbox" value="Dog" id="Dog" name="whatKindofAnimal[2]" />Dog</label><br />
    <label for="Other-Animal"><input class="form_style" type="checkbox" id="Other-Animal" name="whatKindofAnimal[1]" onclick="if(!this.checked) document.getElementById('otherKindofAnimal').value='' " />Other</label>
    <!-- IF BITTEN ANIMAL="Other" Show Field -->
<div class="Other-Animal" style="display:none;">
    <input class="form_style" type="text" placeholder="Please Specify" id="otherKindofAnimal" name="whatKindofAnimal[1]" />
</div>
    <!-- END "Other" Field -->

PHP:

        <p class="data_answers">
    <?php if (isset($_POST['whatKindofAnimal'])) {echo '<strong>What Kind of Animal:</strong> '; $name = $whatKindofAnimal = implode(', ', array_filter($_POST['whatKindofAnimal'])); echo htmlspecialchars($whatKindofAnimal);} ?>

我一直在整个页面中使用这个PHP代码的第一部分用于单选按钮,它完美无缺!这就是我在其他地方为单选按钮设置的方式......并且相关文本仅在用户实际选择答案时显示。

  <p class="data_answers">
    <?php if (isset($_POST['bite-reported-human'])) {echo '<strong>Bite Reported:</strong> '; echo htmlspecialchars($_POST['bite-reported-human']);} ?></p>

在这种情况下,&#34; Bite Reported:&#34;除非已为其选择了答案,否则在结果页面上仍然不可见。

请帮忙????

先谢谢你, 崔西

2 个答案:

答案 0 :(得分:0)

Dude问题是输入字段

<input class="form_style" type="text" placeholder="Please Specify" id="otherKindofAnimal" name="whatKindofAnimal[1]" />

即使此字段为空,它也会通过$ _POST发送数据,您可以通过print_r($_POST)对其进行测试,空字符串将位于 $ _ POST ['whatKindofAnimal'] [1] 所以试试这个

替换

if (isset($_POST['whatKindofAnimal']))

if (count($_POST['whatKindofAnimal'])>1)

因为isset($ _ POST ['whatKindofAnimal'])将始终为true,因为 $ _ POST ['whatKindofAnimal'] [1]

中将始终存在值

答案 1 :(得分:0)

由于'Other-Animal'是一个文本字段,即使是空的也会被提交,使$ _POST ['whatKindofAnimal'] == array([1] =&gt;''),因此isset代码将运行

可能有很多解决方案,但快速的方法是更改​​其他动物字段的名称并显示如果选中其他

DatePicker

如果选择了其他,则结果显示为其他:{input},如果没有单击任何复选框,则根本不会显示。

相关问题