简体   繁体   中英

How to change a hidden_field array using Javascript without losing its correct format?

In my Rails controller, I need an array direct_filter_params in a format like this (multi dimentional array, could have n elements):

direct_filter_params = [['gender','equals','male'], ['age','range',21,25]]

I am getting this from a form, having a hidden_field_tag :direct_filter_params:

<%= form_tag(user_demography__path, :method => :get, :remote => true) do %>
<%= hidden_field_tag :direct_filter_params %>
<%= render :partial => "user_demography_filters" %>
<%= submit_tag "Find Users", :class => "btn" %>
<% end %>

I need to get the values into this from the form. I can get the values in the javascript file after the click() event fires, but the problem I am having is that Javascript/Jquery doesn't set the value in the proper format. I know it is confusing, so I will give a short example.

var a = [];
attribute = 'gender';
condition = 'equals';
value = 'Male';
var b = [attribute, condition, value];
$("direct_filter_params").val(b);
c=$("#direct_filter_params").val();
$("#direct_filter_params").val(c+b);

This sets the value of the element as:

<input type="hidden" name="direct_filter_params" id="direct_filter_params" value="gender,equals,Maleage,range,21,25">

Note the value is "gender,equals,Maleage,range,21,21". What I need is the value in the original format mentioned at the top. I have searched for hours, but I am unable to resolve this and am stuck at this small point despite all logic being complete.

Try this

var b = [attribute, condition, value],
    c = $("#direct_filter_params").val(),
    a = [b,c];
$("#direct_filter_params").val(JSON.stringify(a));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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