简体   繁体   English

将表单值提交给JS数组对象而不是AJAX请求

[英]Submitting form values to a JS array object rather than to an AJAX request

Been working on this issue for a while now and I just cant get my head around it. 现在已经在这个问题上工作了一段时间,但我始终无法解决。 There are a few similar answers but nothing that seems to tackle my exact issue. 有一些类似的答案,但似乎无法解决我的确切问题。

So I have a form. 所以我有一个表格。 The values from this are all going to be numbers. 来自此的值都将是数字。 I want to capture the values inside an array to perform calculations on them before sending a seperate AJAX call with the new variables. 我想在发送带有新变量的单独AJAX调用之前捕获数组内的值以对其执行计算。 Im really surprised at how hard this seems to be to get working. 我真的为这似乎很难工作感到惊讶。

My code should be outputting the values of the form into key/value pairs within array x, however this array just seems to be empty (contains {object Object} pairs for every form name/value pair. 我的代码应该将表单的值输出到数组x中的键/值对中,但是此数组似乎是空的(每个表单名/值对都包含{object Object}对。

Any ideas? 有任何想法吗? If there is a better method to achieving this, i'm all ears (or eyes, whatever!). 如果有更好的方法可以做到这一点,我将全神贯注(或眼睛,无论如何!)。 I guess an easy way would be to just bind this to a click rather than submit event, but I dont want to lose all the other user form submission abilities (pressing enter etc). 我想一个简单的方法是将其绑定到单击而不是提交事件,但是我不想失去所有其他用户表单提交功能(按Enter等)。

Javascript: 使用Javascript:

$('#zombieForm').submit(function(event) {
    event.preventDefault()
    var x = $(":input").serializeArray();
    alert(x); //currently using a sandbox without console for this
});

HTML: HTML:

<form id="zombieForm" method="post">
    <select name="multi2" required>
        <option value=""></option>
        <option value="100">placeholder value 4</option>
        <option value="50">placeholder value 3</option>
        <option value="25">placeholder value 2</option>
        <option value="0">placeholder value 1</option>
    </select>
    <input type="submit" value="Submit" id="formButton" />
</form>

You could do something like this. 你可以做这样的事情。 Is this what you're after? 这是你所追求的吗? Fiddle 小提琴

$('#zombieForm').submit(function(event) {
    event.preventDefault();
    var yourArray = {};
    $.each($(this).serializeArray(), function() {
        yourArray[this.name] = this.value;
    });
    console.log(yourArray);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM