I have a form containing a list of text fields
<input type="text" name="list[]" value="">
<input type="text" name="list[]" value="">
I'm running some custom jQuery to validate the input and do a few other things, before displaying a JSON chunk to the user. What I want to achieve is these elements should become a standard javascript array a la:
{"list":["something","something else"]}
Is there a simple call I can make on the specific element to pull it in as an array, something like this?
var jsonVars = {};
jsonVars['list'] = $("input[name=list]").getArray();
With the structure you have and assuming you want to get the values you could do:
var jsonVars = {};
jsonVars['list'] = $('input[name="list[]"]').map(function(){return this.value;}).get();
You can use $('input[name="list[]"]').serializeArray() but will return in a different format as array of objects (with name and value).
There's jQuery's serialize function. This topic is similar to yours and might give you some more advanced insight.
Related
I've have a CF page who's inventory search form, frm_inv post's back to itself. frm_inv's main table of records, tbl_inv, uses a tablesorter. A hidden input (sort_list) is used in conjunction with a cfparam to keep track of tbl_inv's sortList:
main.cfm
<cfparam name="form.sort_list" type="string" default="1,0">
<form id="frm_inv" action="main.cfm" method="post">
<input name="sort_list" type="hidden" value="#form.sort_list#"/>
<table id="tbl_inv" class="tablesorter">
...
</table>
</form>
When frm_inv is submitted, CF uses sort_list in $(document).ready() to restore tbl_inv's sort order:
$(document).ready(function(){
var sort_list_str = <cfoutput>"#form.sort_list#"</cfoutput>;
var sort_list = sort_list_str.split(",");
$("#tbl_inv").tablesorter({
textExtraction: ['complex'],
sortList:[[sort_list[0],sort_list[1]]]
}).bind("sortEnd", function(sorter) {
var sl = sorter.target.config.sortList;
$("input[name='sort_list']").val(sl.toString());
});
});
I would rather use arrays than convert a comma separated string into an array like I'm currently doing
<cfparam name="form.sort_list" type="string" default="1,0">
to
<cfparam name="form.sort_list" type="array" default="ArrayNew(2)">
however I need to know the proper javascript and coldfusion syntax in order pose everything that's relevant in arrays exclusively.
Copying a ColdFusion ... array into a JavaScript array
Why? For the most part, HTTP only transmits strings, so there is no translation between client and server complex types. Unless you are doing something more than just passing the sort value back and forth, converting between client and server side arrays is just an unnecessary complication. It is simpler to leave the value as a string and do any splitting or parsing on the client side.
You did not really explain what problem you are trying to solve, but .. there is nothing inherently wrong with the current approach. However, it could be simplified a bit. There is no need to cfoutput the variable again here:
(A) var sort_list_str = <cfoutput>"#form.sort_list#"</cfoutput>;
Since you already stored the current form.sort_list value in a hidden form field, the above is redundant. Instead, just read the field's value with javascript ie
(B) var sort_list_str = $("input[name='sort_list']").val();
Having said that, if you really prefer to work with arrays, you could store a JSON string representation of the arrays instead. Then use parse() and stringify() to convert the arrays back and forth. Same net effect as your current method, but a bit simpler in terms of code.
Form:
<cfparam name="form.sort_list" default="[[1,0]]">
...
<input id="sort_list" name="sort_list"
type="hidden" value="#encodeForHTML(form.sort_list)#" />
...
JQuery:
$(document).ready(function(){
$("#tbl_inv").tablesorter({
textExtraction: ['complex'],
sortList: JSON.parse($("#sort_list").val())
}).bind("sortEnd", function(sorter) {
var sort_arr = sorter.target.config.sortList;
$("#sort_list").val(JSON.stringify(sort_arr));
});
});
For creating a JavaScript variable from a ColdFusion variable, you can use toScript() function.
var #toScript(ListToArray(form.sort_list), "sort_list")#;
This can be used for wide range of variable types such as strings, arrays, structures etc.
Needs specific syntax to use an array in cfparam: ColdFusion CFParam Can Use Struct And Array Notation
<cfparam name="form.sort_list" type="array" default="#ArrayNew( 2 )#">
When adding the ng-model directive to an HTML element, I usually do so with it attached to an object. However, before sending the HTTP request, a portion of the data should be an array of objects.
In my rails-api I have a User model and an Address model. The user has many addresses and the address belongs to a user.
The goal is to just take in the parameter via strong params and save each of the addresses (received as JSON, array of objs) and have them each be related to the user.
Currently, i'm numbering them and doing some extra manipulation prior to shipping the data off to the API. Ex:
<input type="text" ng-model="form.address1">
And then for the second, ng-model="form.address2".
How can I setup an array of objects using the ng-model attribute and add objects onto the array in my HTML?
You can bind to array too:
<input type="text" ng-model="form.address[0]"> Address 1
<input type="text" ng-model="form.address[1]"> Address 2
Demo: http://plnkr.co/edit/owpAqLLlgOjBKfqHSZ4U?p=preview
I have a form with a hidden field:
<input type="hidden" name="newdesc[]" id="newdesc" />
I have an autolookup and a plus button so the plus button adds the field value of the autolookup to an array:
newdesc_a.push(document.getElementById('autocomplete1').value);
var x=document.getElementById("businesslist");
x.innerHTML=newdesc_a;
document.getElementById('newdesc').value = newdesc_a;
(newdesc_a is previously declared as an array)
It updates the div OK (businesslist) but does not assign the value to the newdesc.
I am sure it is simple but it is driving me mad!
Given the name="newdesc[]" attribute, I assume PHP on the server side. When you submit a key two or more times, only the last value is available in the script via $_REQUEST. In the case of a key ending with [] , instead, PHP builds an array and make it available to your script via $_REQUEST['key']. Note that this behavior is application-specific, there's nothing like an array at the HTTP level.
Now, you want to pass an array from the client side (Javascript) to the backend (PHP). You have two options:
Use a proprietary format, eg separate values by commas or colons, and split the string on the server side (or you can use an existing format like JSON, XML, ...)
Take advantage of the PHP syntax for passing arrays
It seems you want to adopt the 2nd way, so you will want to submit a form like the following
<input name="email[]" value="joel#example.com" />
<input name="email[]" value="mark#people.com" />
<input name="email[]" value="bill#hello.com" />
PHP will be able to access a plain array in $_REQUEST if you build your form like this. Now, you have the problem of building the form programmatically on demand. This is the best I can think of (jQuery):
var email = $("#autocomplete").value;
// if you really need to keep emails in an array, just
// emails.push(email);
$('<input type="hidden">').attr({
name: 'email[]',
value: email
}).appendTo('#myForm');
You want to assign a particular value of array to that element?
You can use like this.
document.getElementById('newdesc').value = newdesc_a.index;
where 'index' is the index of array. replace it.
I am working on a search panel, where I want to bind the data entered in these input elements to a search parameter json object. This search parameter will then be used for, you guessed it right, searching.
For example, user when searching for another person and he can specify the name, age or sex of the person on the page. I have json object which has, as its members Name, Age and Sex. I want to bind the inputs entered in the corresponding input elements on the page to this JSON object automatically, so when the user clicks on the Search I will just use whatever the json object has as a search param.
This is primarily to avoid having to - first find the corresponding element and then assign the corresponding member of the JSON object to the input in this field.
I could find jquery plugins (Databind) , which do the other way round i.e. transfer the values of a JSON object to the input elements.
Thanks in advance!!
I think you are confusing your terminology: presumably you mean a Javascript object.
Anyway, your object or json string need to be constructed when the user clicks "Search". It will be difficult/fiddly to assign these as the user enters text into the input fields. You could use the onblur event but you're just making unnecessary work for yourself.
Far easier is just to give each input field an id, and when the user clicks "Search" you build your object, then JSONify it. Here's how you might do it (not tested!):
<input type="text" id="name" />
<input type="text" id="age" />
...
var obj = { };
obj.name = document.getElementById('name').value;
obj.age = document.getElementById('age').value;
...
var json = JSON.stringify(obj);
I'm using django and have a page of search results that I want to be able to filter by category with ajax (jquery) requests. There's a filter bar on the side of the page and when someone selects certain categories and clicks submit, those corresponding results should show up on the page. My code looks something like this:
<input type="checkbox" name="category1" value="1" />
<input type="checkbox" name="category2" value="2" />
<input type="button" name="submit" onclick="{
var cats = new Array();
$(input[type=checkbox]:checked).each(function() {
cats.push($(this).val());
});
$.getJSON('page.html', {'cats':cats}, function(data) {...});
}" />
But in the django view when I try to read the cats array it returns a 500 error. I can, however, pass scalars and strings to the django view with no problem.
Any thoughts? Is there a more elegant jQuery way to do this without using a javascript array?
Rather than getting the field values manually, you can use jQuery's serializeArray() method, which turns a set of fields into an array which can be sent as JSON. Note that you'll probably want both checkboxes to have the same name, so that when it's serialised it becomes something that Django will interpret as a list.
As Steve says, to help further we'll need to know what the view is doing and what the error is.
Got it working - I downloaded the jquery-json plugin, encoded my array as a json obect to send to django, and then used simplesjon.loads() in the django view to convert that json object to a python list. However, the fact that it took so many steps and jQuery on its own doesn't even come with json encode functionality still makes me think there must be a more elegant way - if anyone has any insight, I'd love to hear it.
Thanks Daniel for pointing me in the right direction.
I guess that a workaround would be transforming your array into a string, eg in javascript:
a = new Array(0,1,2,3,4);
[0, 1, 2, 3, 4]
a.join(" ")
"0 1 2 3 4"
Then you can pass this to the python back end, split it and reconstruct the data structure you need.....