0

I have a list of properties of which each has a reference number and I am trying to separate each reference by a comma then set them for a input field value, I am unsure if its the correct way to do it, however I am receiving a [object Object] message, my code is:

var propertyRef = $( ".reference" ).clone().append(',').contents();
$('#propertyRef').val(propertyRef);
Machavity
  • 30,841
  • 27
  • 92
  • 100
Graham Barnes
  • 235
  • 2
  • 6
  • 18
  • I think this will solve your problem [http://stackoverflow.com/questions/247023/get-an-array-of-list-element-contents-in-jquery](http://stackoverflow.com/questions/247023/get-an-array-of-list-element-contents-in-jquery) – Houmam Oct 15 '15 at 10:07
  • Thanks for that but now its not setting it as the value of the field my code to to this: `var propertyRefs = []; $(".reference").each(function() { propertyRefs.push($(this).text()) }); var propertyRef = "Shortlist: " + propertyRefs.join(', '); console.log(propertyRef); //$propertyRef.appendTo('#propertyRef');` although the code seems a lot better than what i had :) – Graham Barnes Oct 15 '15 at 10:36

1 Answers1

1

Ok, try this code:

<ul id="list">
    <li>10</li>
    <li>20</li>
    <li>30</li>
</ul>
<input type="text" id="input" />
<input type="button" value=Convert" onclick="convertList2String()" />

<script>
function convertList2String() {
    var id_list = [];
    $("#list li").each(function() {
        id_list.push($(this).text());
    });
    var id_list_str = '"' + id_list.join('", "') + '"';
    $('#input').val(id_list_str);
}
</script>

UPDATE: if you do not want to quote the id, then use this line instead:

var id_list_str = id_list.join(',');
Houmam
  • 567
  • 4
  • 11
  • That worked, I changed your code to match mine: `var propertyRefs = []; $(".reference").each(function() { propertyRefs.push($(this).text()) }); var propertyRef = "Shortlist: " + propertyRefs.join(', '); console.log(propertyRef); $('#propertyRef').val(propertyRef);` and it works great, thanks :) – Graham Barnes Oct 15 '15 at 10:39