views:

112

answers:

3

I need to change a value in a javascript object.

var wba_product = {
    sku:'12ZB7',
    availability:'Usually ships in 1-2 business days',
}

I want to change this using javascript.

<script language="javascript" type="text/javascript>
if(wba_product.sku == '12ZB7') wba_product.availability + ' Items are charged to your credit card only when they ship. Your credit card will not be charged until the item is shipped to you. ';
</script>

But this syntax is not working.

A: 

I think what you want is

if(wba_product.sku == '12ZB7') {
    wba_product.availability += 'Items are charged to...';
}
Rob
Equals does not work. And I would like to concatenate.
Jeff
The `+=` operator concatenates. I edited my post.
Rob
+4  A: 

Two points:

  1. You have a trailing comma at the end of the availability member, IE doesn't tolerates that.

  2. To assign values to variables and object members, use the = assignment operator.


var wba_product = {
    sku:'12ZB7',
    availability:'Usually ships in 1-2 business days' // notice the comma removed
}

if(wba_product.sku == '12ZB7') {
  wba_product.availability = 'new value';  // assign a new value
}

And if you want to concatenate a string at the end of the availability member, you can do it like this:

 wba_product.availability += ' concatenated at the end.';
CMS
I shortened the var declaration for brevity. the problem is not the comma. Thanks.
Jeff
Ok, I told you only because is a common mistake.
CMS
By the way wba_product isn't an associative array, it's an object literal.
CMS
I was wondering what to call it. Thank you.
Jeff
A: 

According to the developer at Amazon.

"You can't change the value this way, you have set the DOM element directly, changing the json object only changes json object not the DOM element."

Which is what I ended up doing. I concatenated with div.innerHtml += "My added copy";

J.

Jeff