Gov
Gov

Reputation: 33

How pass jquery value input without single quote

This might read impossible.

How do you remove single quotes from a var when passed directly to another var.

I have jQuery var $("#test").val() grabbing the value from a input below

<input type="text"  id="test" value ="{id:66},{id:57}" />

then I pass the value from the input to another var called newproduct to its object categories

var test = $("#test").val();
    
var newproduct = {
    status: status,
    price: 500,
    regular_price: 450,
    sale_price: 0,
    categories: [ test ]
    };

The categories should be format as categories: [{id:66},{id:57}] when the script is executed.

However, the console.log is shown the categories as categories: ['{id:66},{id:57}'], the single quotes is causing it to failed.

is there a way to remove the single quotes so that the categories read as categories: [{id:66},{id:57}] when the script is runs.

Upvotes: 1

Views: 139

Answers (1)

Quentin
Quentin

Reputation: 944200

The value is a string. HTML has no way of representing an array of objects there.

There are various ways to represent an array of objects as a string, but you would need your JavaScript to take the string and parse it into the JavaScript data structure you want.

A traditional data format would be JSON and if you were using it you could simply:

var test = JSON.parse($("#test").val());

However, you are using a non-standard format so you would need to write a custom parser for it. (Or switch to storing JSON in the value).

Upvotes: 1

Related Questions