Javascript Hidden Input Array

孤人 提交于 2019-11-29 10:53:12

Your best option would be to stringify the array and then assign it.

element.value = JSON.stringify( ["Hello", "World"] );

The resulting value will be a JSON string that can then be parsed on the server, recreating the array. This approach works for objects as well if you wish to have something resembling an associative array.

I should note that while JSON has fairly good support across browsers today, older browsers may not support it. You can polyfill the feature fairly easily in those cases:

However you set it in Javascript, you'll have to parse it on the server. That probably means splitting the value by "," into a C# array, then accessing it as you want. All values sent in a form submission are sent as a string exactly as-is.

You might want to use http://www.w3schools.com/jsref/jsref_join.asp to set the value of the hidden input. It's not necessary though - it seems to be fine without using .join(). But it's important to remember that the value will be a string on the server, not an array.

You can only pass a string as a parameter, as well as to an input's value. That means you Array will automatically be converted to a string by joining it with ";", you could do that manually with the .join() method, too.

Serverside you then will need to split that string by the chosen delimiter.

If you want to send them as an array, afaik you will need two input elements:

<input type="hidden" name="hiddenInp[]"<!-- should be more descriptive --> value="a" />
<input type="hidden" name="hiddenInp[]"<!-- the same name --> value="b" />
Randika Vishman

I found the answer in via the following link.

When you want to assign any JavaScript Object or an Array do it as follows:

var javascript_variable = 'object' or ['fruit1', 'fruit2', 'fruit3'];
$( '#hiden_input_element_unique_id' ).val( JSON.stringify(javascript_variable) );

After form submission, in the serverside we have to decode it as follows:

$fruits_array = json_decode( $_POST['hiden_input_element_unique_name'] );

This way you can get any JavaScript array in the server-side, which you set it inside to a form element via JavaScript, in the client-side!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!