dongmei1828 2014-08-14 12:10
浏览 27
已采纳

使用javascript提交表单并从其他页面接收

I'm trying to submit a form to a PHP page, but the data is not accessible from this page, This is my code:

Html code:

<form method="post" id="formid" action="test.php">
    <input type="hidden" name="going" id="going" value="" /> 
</form>

Javascript:

$("#ongoing").change(function() {
    var ongoing = $(this).attr('checked');
    var input = document.getElementById('going');
    var form = document.getElementById('formid');

    if (ongoing)
        input.value = "1";
    else
        input.value = "0";

    form.submit();
});

test.php

if(isset($_POST['going']))
      echo $_POST['going'];

What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • dougao9864 2014-08-14 13:00
    关注

    Try this! It does what you want with much less code. You were having issues because the checked attribute returns a string not a boolean value.

    $("#ongoing").change(function() {
        var form = document.getElementById('formid');
        form.going.value = $(this).attr('checked').toLowerCase() == "checked" ? "1" : "0";
        form.submit();
    });
    

    The longer way looks like:

    $("#ongoing").change(function() {
        var form = document.getElementById('formid');
        var input = document.getElementById('going');
        var isChecked = $(this).attr('checked').toLowerCase() == "true";
        if(isChecked)
            input.value = "1";
        else
            input.value = "0";
        form.submit();
    });
    

    Additionally! It is good practice when writing html attributes to always type checked="true" (or "false") even though just checked is synonymous with the previous. Unpaired markup attribute-values could be mistaken by amateur coders as tag names.

    See here for more Checkboxes in Jquery

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据