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);
2
  • I think this will solve your problem http://stackoverflow.com/questions/247023/get-an-array-of-list-element-contents-in-jquery Commented Oct 15, 2015 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 :) Commented Oct 15, 2015 at 10:36

1 Answer 1

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(',');
Sign up to request clarification or add additional context in comments.

1 Comment

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 :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.