Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

missing : after property id - javascript

I have what I thought was a simple function but I can't figure out what I'm missing here. There error I'm getting is missing : after property id and it references:

var data = { "'" + $(this).attr('id') + "'" : "'" + $(this).val() + "'" };

Here's the function:

function ArrayPush($group) {
    var arr = new Array();
    $group.find('input[type=text],textarea').each(function () {
        var data = { "'" + $(this).attr('id') + "'" : "'" + $(this).val() + "'" };
        arr.push(data);
    });
    return arr;
}
like image 860
bflemi3 Avatar asked Mar 04 '26 13:03

bflemi3


1 Answers

You can't create an object like that - the "key" in an object literal must be a constant, not a variable or expression.

If the key is a variable you need the array-like syntax instead:

myArray[key] = value;

Hence you need:

var data = {};  // empty object
data[$(this).attr('id')] = $(this).val();

However as all of your fields are actually plain HTMLInputElement or HTMLTextAreaElement objects, you should really use this and avoid those expensive jQuery calls:

var data = {};  // empty object
data[this.id] = this.value;

I'd also question why you're creating an array of objects - as the keys should all be unique, I would normally expect to return a single object:

function formObjectBuild($group) {
    var obj = {};
    $group.find('input[type=text],textarea').each(function () {
        obj[this.id] = this.value;
    });
    return obj;
}
like image 74
Alnitak Avatar answered Mar 06 '26 03:03

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!