doupao2277 2017-03-10 17:10
浏览 80

使用隐藏的输入来POST JavaScript函数结果

I have a single form input on my homepage userinput. The homepage also contains a JavaScript function that uses that userinput value to calculate a result.

<form action="/run.php" method="POST" target="_blank">
    <input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
    <input type="text" name="userinput" id="userinput">
    <button type="submit" onclick="calcResult();">Go!</button>
</form>

<script>
    function calcResult() {
        var userinput = document.getElementById('userinput').value;
        var result = userinput + 10; // want to POST result in a hidden input field w/ form
</script>

I'm trying to find a way in which a user can enter their input, submit the form, the JavaScript takes that userinput and calculates a result, then that result is POST'ed along with the userinput in the form.

The problem I can forsee with this method is that:

  • The JavaScript function needs the userinput before it can calculate the result. However, the only way to get the userinput is to submit the form, which means the form data will be POSTed before the JavaScript result is returned.

My attempted solution(s):

I was wondering whether it's possible to use a button (type="button"), instead of a submit (type="submit") for the form. Then just use that button to call the JS function, then (somehow) submit the form (with the JS function result) after the JS function has completed? (either with plain JS or jQuery).

  • 写回答

5条回答 默认 最新

  • dongshou6788 2017-03-10 17:21
    关注

    there are multiple approaches to do this,

    i'm gonna use jquery here instead of pure javascript to simplify it

    [without submission] you may check the event change

    $('#userinput').change(function (e) {
        // make some calculation
        // then update the input value
    });
    

    [with form submission] you will disable the submission using the object preventDefault inside the submit event

    $('#userinput').submit(function (e) {
        e.preventDefault();
        // make some calculation
        // then update the input value
    
        // your ajax goes here OR resubmission of your form
        // to resubmit the form
        $(this).submit();
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛