简体   繁体   中英

Use Jquery to sum values of a specific key in json from a form value

I have a script which constructs a json object and assigns it to a form text element like so :

<input id="clientList" type="hidden" value="[{"clientID":"1","clientType":"0","clientPrice":"450.00","tourID":"9","insuranceAvailable":"0"},{"clientID":"2","clientType":"2","clientPrice":"0.00","tourID":"9","insuranceAvailable":"0"}]">

I need (with Jquery or JS), sum up all the clientPrice keys in that string.

The code I'm trying is :

var totalRoomPrices = 0;

var travellerPricesToSum = JSON.stringify($('#clientList').serializeArray());

$.each(travellerPricesToSum, function () {
     totalRoomPrices += this.clientPrice;
});

console.log(totalRoomPrices);

Can anyone provide some insight as to what I'm doing wrong and how I can fix this?

Thanks

You need to parse the value as it is a string representation of the json . JSON.stringify will convert object to string which is not the case here. Also note, " inside string wrapped in " will break the string, Either escape them or use ' inside " or vice versa.

As values are strings , += will con-cat them. To get the addition working(considering floating values), use parseFloat to convert them in float

Try this:

 var totalRoomPrices = 0; var travellerPricesToSum = JSON.parse($('#clientList').val()); $.each(travellerPricesToSum, function() { totalRoomPrices += parseFloat(this.clientPrice); }); alert(totalRoomPrices); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <input id="clientList" type="hidden" value='[{"clientID":"1","clientType":"0","clientPrice":"450.00","tourID":"9","insuranceAvailable":"0"},{"clientID":"2","clientType":"2","clientPrice":"0.00","tourID":"9","insuranceAvailable":"0"}]'> 

You cannot have same style of quotes inside a value attribute. You will have to find another way to encode structured data in a string inside a value attribute, I've seen people use | and : characters as delimeters and obviously you will have to write your own parser using str.split() .

edit: Obviously, holding entire JSON string is also an option if you mix single and double quotes as per the other answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM