从uniq id收集所有值并将其传递

时间:2019-10-06 18:10:45

标签: javascript jquery html

所以我在使用JS时遇到了麻烦,如何在单击按钮时正确地收集和传递文本字段和隐藏字段中的所有值。

<input autocomplete="off" id="add_109_01000340002001010_id" name="add_109_01000340002001010[id]" type="hidden" value="113000674">

<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001010_name" name="add_109_01000340002001010[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">


<input autocomplete="off" id="add_109_01000340002001009_id" name="add_109_01000340002001009[id]" type="hidden" value="112000674">

<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001009_name" name="add_109_01000340002001009[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">


<input autocomplete="off" id="add_109_01000340002001021_id" name="add_109_01000340002001021[id]" type="hidden" value="11405181">

<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001021_name" name="add_109_01000340002001021[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">

这些是具有唯一ID的文本字段和隐藏字段。它们是“连接的”。更改文本字段中的值时,隐藏字段中的值会自动更改。

当您单击按钮时,应在js中处理将在文本字段中写入的值

function room_group() {
    $('.add').bind('click', function() {
        var hidden_values = 'something here' // Let's get all values here and pass them to the get request
        var values = 'something here' // Let's get all values here and pass them to the get request

        $.post('/link/definition', {
                val: values,
                hidden_val: hidden_values

            },
            function(response) {
                location.reload();
            }
        );
    });
}

问题是如何正确收集所有这些值?不幸的是,我不知道...

1 个答案:

答案 0 :(得分:1)

这取决于您要如何格式化值。 您可以通过使用适当的选择器搜索这些值来序列化这些值,然后可以创建一个JSON字符串作为值。

var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());

var textValues = JSON.stringify($("input[type='text']").serializeArray());

console.log(hiddenValues);
console.log(textValues);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" value="h1" name="hidden1" />
<input type="hidden" value="h2" name="hidden2" />
<input type="text"   value="t1" name="text1" />
<input type="text"   value="t2" name="text2" />

您的POST将类似于:

var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());
var textValues = JSON.stringify($("input[type='text']").serializeArray());

$.post('/link/definition', {
    val: textValues,
    hidden_val: hiddenValues
    },
    function(response) {
        location.reload();
    }
);