3

I have the following serialized data string (Some of the contents are from checkboxes so that is why the 'brand' is repeated) coming from another page:

brand=Ford&brand=Dodge&brand=Mazda&year=2013&type=compact

and I would like to populate the div tag with the id of "results":

<div id="results">    
    <div id="brand"></div>    
    <div id="year"></div>    
    <div id="type"></div>    
</div>

I'm currently using this code to loop over the data:

$.each(SelectionData.split('&'), function (index, elem) {    
    var vals = elem.split('=');    
    $('#' + vals[0]).text(decodeURIComponent(vals[1].replace(/\+/g, ' ')));    
});

It has been working fine until we added checkboxes to the form. Now I'm only able to display the last value in a string when the names are the same as show here:

This is what we have now

<div id="results">
    <div id="brand">Mazda</div>    
    <div id="year">2013</div>    
    <div id="type">compact</div>    
</div>    

This is what we are looking for:

<div id="results">
    <div id="brand">Ford,Dodge,Mazda</div>    
    <div id="year">2013</div>    
    <div id="type">compact</div>    
</div>
HPWD
  • 2,232
  • 4
  • 31
  • 61

1 Answers1

5

I don't understand why you want the result to be formatted inside a div called results but your code attempts to change the text of a element with an id equaliing the name of the uri paramter name.

Anyway I think I've figured out what you want to do. Working Demo

The HTML:

<div id="brand"></div>
<div id="year"></div>
<div id="type"></div>

The Code:

var SelectionData = 'brand=Ford&brand=Dodge&brand=Mazda&year=2013&type=compact';

$.each(SelectionData.split('&'), function (index, elem) {
    var vals = elem.split('=');
    var $div = $("#"+vals[0]);
    var separator = '';
    if ($div.html().length > 0) {
        separator = ', ';
    }
    $div.html($div.html() + separator + decodeURIComponent(vals[1].replace(/\+/g, '  ')));
});
Seain Malkin
  • 2,273
  • 19
  • 20
  • As for the "why" behind it, the client is asking to display the users selection to the screen before continuing on to the next page. – HPWD Jan 15 '13 at 17:12
  • Nice touch with the space after the ',' separator = ', '; – HPWD Jan 15 '13 at 17:14
  • @dlackey Thats fine, but what I noticed is your code tries to change the text of an element called `#brand` or `#year` but the result you want is just contained within an element called `#results`. – Seain Malkin Jan 15 '13 at 17:16
  • Oh nice, catch! I entered the SO question and before posting made some changes in my source code and didn't revise the SO question. I'll update the question accordingly. – HPWD Jan 15 '13 at 17:18
  • Your solution worked perfectly! Especially nice job since my code wasn't clear (code has been revised for future onlookers). – HPWD Jan 15 '13 at 17:19