How to convert input name to JavaScript array - javascript

I have an issue related to converting html inputs names to a javascript object.
For example I have an input:
<input type="checkbox" name="product[1]">
<input type="checkbox" name="product[2]">
and I have javascript code:
var data = {};
$('input').each(function(){
// need to do something like
data[$(this).attr('name')] = $(this).attr('checked');
})
I expect to get data object like this;
data = {
product: {
1: 'checked',
2: 'checked'
}
}
Is this possible without using regular expressions?

Replacing your variables with literal values, you get this:
data["product[1]"] = true;
The square brackets have no meaning as they are inside a string, so you won't get any result.
There are ways around this. You could use eval: eval("data."+this.name+" = "+(this.checked?"true":"false"));
However since eval is best avoided, try this:
var m = this.name.match(/(.*)\[(\d+)\]/);
data[m[0]][m[1]] = this.checked;

Yes in general it is possible. You can do the following:
var noregexp = $(this).attr('name').split("[");
if (noregexp.length==2) {
//should be
var the_name = noregexp[0];
var the_index = noregexp[1].substr(0,noregexp[1].length-1); //this will get the index with removed ]
}
I made this up from my mind. It's not a beautiful solution but one without regexp as you wished.

You can get a data structure the way you need using:
var data = {product: []};
$('input').each(function(){
data.product[$(this).attr('name').match(/product\[([\d]*)\]/)[1]] = $(this).prop('checked');
})
console.log(data);
Check thid demo

Related

How to get json data with vars in p5.js

I'm building a dictionary word definition search engine which has a #submit button and #word input. I also have a JSON dictionary(Github link). I don't know how to select what word definition to use depending on what the user types.
I have already tried putting the input.value() as a var to the json object query:
var uInVal = input.value();
document.getElementById("p1").innerHTML = words.uInVal)
Can someone help me?
My Code:
var words;
var input;
function setup() {
loadJSON("dictionary.json", gotData);
var button = select('#submit');
button.mousePressed(keyDraw);
input = select('#word');
}
function gotData(data){
words = data;
}
function keyDraw(){
document.getElementById("p1").innerHTML; //This is where the word definition should get printed
}
In the future, please try to work with a simpler example. Something like this would show your problem in a runnable example:
var jsonString = '{"x": 42, "y":100}';
var jsonObject = JSON.parse(jsonString);
This is also easier for you to work with. Now that you have this, I'd google something like "javascript get value from property name" for a ton of results.
But basically, there are two ways to get the value of a property:
var xOne = jsonObject.x;
var xTwo = jsonObject['x'];
console.log(xOne);
console.log(xTwo);
This is what you're trying to do:
var varName = 'x';
var myX = jsonObject.varName;
This won't work, because jsonObject doesn't have any field named varName. Instead, you want to access the x field. To do that, you can use bracket [] notation:
var myX = jsonObject['x'];

Javascript key value array storing

I am here today with a question to do with key value pair arrays.
my html is as follows
<input type="checkbox" class="data" id="task_checked" value="1" email="a#a.com">
<input type="checkbox" class="data" id="task_checked" value="2" email="b#b.com">
I would like to store the following data as an array like below:
"1" => "a#a.com"
"2" => "b#b.com"
My Javascript currently is as follows:
var newTasksArr = new Array();
$("#task_checked:checked").each(function() {
var email = $(this).attr("email");
var id = $(this).val();
newTasksArr['id'] = email;
});
Perhaps I am using the Jquery .each() wrong, could someone shed some light in to my question please?
Thank you for you reading.
Regards.
Two issues :
In Javascript, an Array may only have sequential, numeric keys. If you want to use strings as keys, you want an Object.
If you want to insert an element with a key equal to the value of id, then you want newTasksArr[id] = email; without the quotes.
You're almost right, you just need to remove the quotes around 'id' so that it uses the value the id variable contains, instead of the literal string 'id'.
You should also use an object ({}) instead of an array ([]).
var newTasks = {};
$("#task_checked:checked").each(function() {
var email = $(this).attr("email");
var id = $(this).val();
newTasks[id] = email;
});
Avoid duplicating Ids in your markup. The following should help, however you might want to tweek the jquery selector to include a context.
var arr = {};
$('input:checked').each(function() {
var $t = $(this);
var email = $t.attr("email");
if (!email) {
// you may wish to do something if email is missing
}
var id = $t.val();
if (!id) {
// deal with the error
}
arr[id] = email;
});

Javascript: Removing an object from array by checking it's attribute

I might have written a pretty confusing title but my question is rather simple.
I'm looking for an efficient way to remove an item from an array. But my array is full objects that has been stringified (I'm writing my app on Node.js and I'm using JSON.stringify method). So my array is like this;
"{\"userID\":\"15\",
\"possibleFollowers\":[
{\"followerID\":\"201\",\"friends\":716},
{\"followerID\":\"202\",\"friends\":11887},
{\"followerID\":\"203\",\"friends\":11887}],
\"name\":\"John\",
\"lon\":\"Doe\"}"
My question is on Javascript(or Node). If I wanted to remove the from possibleFollowers with "followerID: 202", how would I be able to do that efficiently?
var string = "…";
var obj = JSON.parse(string);
obj.possibleFollowers = obj.possibleFollowers.filter(function(fol) {
return fol.followerID != "202";
});
string = JSON.stringify(obj);
var data = "{\"userID\":\"15\",\"possibleFollowers\":[{\"followerID\":\"201\",\"friends\":716},{\"followerID\":\"202\",\"friends\":11887},{\"followerID\":\"203\",\"friends\":11887}],\"name\":\"John\",\"lon\":\"Doe\"}";
var dataObject = JSON.parse(data);
dataObject.possibleFollowers = dataObject.possibleFollowers.filter(function(follower) {
return !(follower.followerID == "202");
});
data = JSON.stringify(dataObject);
In javascript, the splice method is used to delete an array element by index.
see :
http://www.roseindia.net/java/javascript-array/javascript-array-remove-index.shtml
try just to delete it by using "delete"
for (var i in possibleFollowers) {
if (possibleFollowers[i]['followerId'] == '216') {
delete possibleFollowers[i];
}
}

jQuery deserialize form

I am using jQuery Serialize to serialize my form elements and would like to deserialize them back. Unfortunately can't find any working jQuery deserializer, any suggestions?
I wrote a version of jQuery.deserialize that supports serialized data generated from the serialize, serializeArray and serializeObject functions. It also supports all form element types, including checkboxes and radio buttons.
Try this:
function deparam(query) {
var pairs, i, keyValuePair, key, value, map = {};
// remove leading question mark if its there
if (query.slice(0, 1) === '?') {
query = query.slice(1);
}
if (query !== '') {
pairs = query.split('&');
for (i = 0; i < pairs.length; i += 1) {
keyValuePair = pairs[i].split('=');
key = decodeURIComponent(keyValuePair[0]);
value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined;
map[key] = value;
}
}
return map;
}
I was very interested in trying JQuery.deserialize, but it didn't seem to handle checkboxes at all, so it didn't serve my purposes. So I wrote my own. It turned out to be easier than I thought, because the jQuery val() function does most of the work:
jQuery.fn.deserialize = function (data) {
var f = this,
map = {},
find = function (selector) { return f.is("form") ? f.find(selector) : f.filter(selector); };
//Get map of values
jQuery.each(data.split("&"), function () {
var nv = this.split("="),
n = decodeURIComponent(nv[0]),
v = nv.length > 1 ? decodeURIComponent(nv[1]) : null;
if (!(n in map)) {
map[n] = [];
}
map[n].push(v);
})
//Set values for all form elements in the data
jQuery.each(map, function (n, v) {
find("[name='" + n + "']").val(v);
})
//Clear all form elements not in form data
find("input:text,select,textarea").each(function () {
if (!(jQuery(this).attr("name") in map)) {
jQuery(this).val("");
}
})
find("input:checkbox:checked,input:radio:checked").each(function () {
if (!(jQuery(this).attr("name") in map)) {
this.checked = false;
}
})
return this;
};
You should be able to use this like this:
$("#myform").deserialize(data);
Where data is a parameter list such as what $("#myform").serialize() would produce.
It affects all fields in the form, and it will clear the values of fields that are not contained in the data. But you can also pass any selector to affect only specific fields, as you can with the serialize function. E.g.:
$("select").deserialize(data);
Half of jQuery Serialize is param(), so half of something that deserializes a query string is going to be a deparam. Unfortunately I haven't been able to find a good standalone deparam. For now I recommend getting the jQuery BBQ library and using that. If you don't need the other stuff you can remove them. I read somewhere that Ben Alman (cowboy) planned to extract deparam into its own module.
For the rest of deserializing, you'll just need to loop through the object that deparam returns and for each key and value pair in the object, select the form element based on the key, and set the form elements value to the value.
Bit late on this one, but somebody might find this useful.
function fetchInput(identifier) {
var form_data = identifier.serialize().split('&');
var input = {};
$.each(form_data, function(key, value) {
var data = value.split('=');
input[data[0]] = decodeURIComponent(data[1]);
});
return input;
}
I'm not now answering your question but my guess is that you want to serialize it and send back to server and then use the serialized data which is why you have to deserialize it?
If that's the case you should consider using .serializeArray(). You can send it as POST data in ajax, and then access later as well because you will have object.
May be a bit late, but perhaps you are looking for something like JQuery.deserialize. Problems: no support for checkboxes or radio buttons.
Using Jack Allan's deparam function with jQuery, you can change this line:
map[key] = value;
to
$('input[name=' + key + ']').val(value);
Which will load the data back into your form fields.
this code returns an array when same key is spotted multiple times in the serialized string
chaine="single=Single1&multiple=Multiple&multiple=Multiple1&multiple=Multiple2&multiple=Multiple3&check=check2&radio=radio1"
function deserialize(txt){
myjson={}
tabparams=chaine.split('&')
var i=-1;
while (tabparams[++i]){
tabitems=tabparams[i].split('=')
if( myjson[decodeURIComponent(tabitems[0])] !== undefined ){
if( myjson[decodeURIComponent(tabitems[0])] instanceof Array ){
myjson[decodeURIComponent(tabitems[0])].push(decodeURIComponent(tabitems[1]))
}
else{
myjson[decodeURIComponent(tabitems[0])]= [myjson[decodeURIComponent(tabitems[0])],decodeURIComponent(tabitems[1])]
}
}
else{
myjson[decodeURIComponent(tabitems[0])]=decodeURIComponent(tabitems[1]);
}
}
return myjson;
}
Needed all in a single string, which can be stored in maybe COOKIE, and later read and fill the same form with input values.
Input elements seperator: ~ (use any seperator)
Input attributes seperator: | (use any seperator)
input type | input name | input value ~ input2 type | input2 name | input2 value
var formData = '';
$('#form_id').find('input, textarea, select').each(function(i, field) {
formData += field.type+'|'+field.name+'|'+field.value+'~';
});
Example:
hidden|vote_id|10~radio|option_id|~radio|option_id|427~radio|option_id|428~
If what you want is to remove the standard URL-encoded notation, you can use JavaScript's decodeURIComponent(), which will give you a regular string, just like this:
var decodedString = decodeURIComponent("Http%3A%2F%2FHello%3AWorld");
alert(decodedString);
In this case, decodedString will look like Http://Hello:World, here's a working fiddle.
Got all of this searching for this same issue, and found the answer here: How can I decode a URL with jQuery?
I know this is an old question, but doing some searches for jQuery deserialize got me here, so I might as well try to give a different approach on the issue for people with the same problem.

Looping over elements in jQuery

I want to loop over the elements of an HTML form, and store the values of the <input> fields in an object. The following code doesn't work, though:
function config() {
$("#frmMain").children().map(function() {
var child = $("this");
if (child.is(":checkbox"))
this[child.attr("name")] = child.attr("checked");
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
return null;
});
Neither does the following (inspired by jobscry's answer):
function config() {
$("#frmMain").children().each(function() {
var child = $("this");
alert(child.length);
if (child.is(":checkbox")) {
this[child.attr("name")] = child.attr("checked");
}
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
});
}
The alert always shows that child.length == 0. Manually selecting the elements works:
>>> $("#frmMain").children()
Object length=42
>>> $("#frmMain").children().filter(":checkbox")
Object length=3
Any hints on how to do the loop correctly?
don't think you need quotations on this:
var child = $("this");
try:
var child = $(this);
jQuery has an excellent function for looping through a set of elements: .each()
$('#formId').children().each(
function(){
//access to form element via $(this)
}
);
Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do...
$("#formID").serialize()
It creates a string for you with all of the values automatically.
As for looping through objects, you can also do this.
$.each($("input, select, textarea"), function(i,v) {
var theTag = v.tagName;
var theElement = $(v);
var theValue = theElement.val();
});
I have used the following before:
var my_form = $('#form-id');
var data = {};
$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
function() {
var name = $(this).attr('name');
var val = $(this).val();
if (!data.hasOwnProperty(name)) {
data[name] = new Array;
}
data[name].push(val);
}
);
This is just written from memory, so might contain mistakes, but this should make an object called data that contains the values for all your inputs.
Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.
Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).
if you want to use the each function, it should look like this:
$('#formId').children().each(
function(){
//access to form element via $(this)
}
);
Just switch out the closing curly bracket for a close paren. Thanks for pointing it out, jobscry, you saved me some time.
for me all these didn't work. What worked for me was something really simple:
$("#formID input[type=text]").each(function() {
alert($(this).val());
});
This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function.
EDIT
JSFIDDLE
The below will work
$('form[name=formName]').find('input, textarea, select').each(function() {
alert($(this).attr('name'));
});

Categories