Erik Grosskurth
Erik Grosskurth

Reputation: 3932

Using .each(), I want to .append() a number value to the value .attr()ibute of an <input> in JQuery

I want to put numbers separated by a comma in the value attribute of an <input>. The problem is it erases it and puts a new number there instead of appending it to the end of the attribute. Can anyone help here???

What you won't see in this html is what the JQuery UI builds when something is dropped in to the div. The list element will look like this:

<li>Doe, John, 12787</li>
<li>Doe, Jane, 9867</li>
<li>etc...

I have extracted the number in the list element and I need to build an array of some sort then make the array of numbers the value attribute for the

The html:

<div id="teamPool">
    <h1 class="ui-widget-header">Your Branch Team</h1>
    <div class="ui-widget-content">
        <ol>
            <li class="placeholder">Add your items here</li>
        </ol>
    </div>
</div>

<div id="remove"><p>Remove</p></div>
<div id="clear"><p>Clear</p></div>
<div id="submit"><p>Submit</p></div>    

    <!--- Hidden variables --->
<div id="hiddenVariables">
    <cfoutput>
        <input type="hidden" name="uid" value="1" />
        <input id="eids" type="hidden" name="eid" value="" />
    </cfoutput>
</div>

The JS:

$('#submit').click(function(){
   $('#teamPool li').each(function() {
      var num = parseInt($(this).text().match(/\d+/)[0], 10);
      var strv = num+' ,';
      $('#eids').attr('value',strv);
   });
});

Upvotes: 0

Views: 87

Answers (1)

bevacqua
bevacqua

Reputation: 48476

You should join them outside of the each, calling .attr just once

$('#submit').click(function(){
   var nums = [];
   $('#teamPool li').each(function() {
      var num = parseInt($(this).text().match(/\d+/)[0], 10);
      nums.push(num);
   });
   var strv = nums.join(', ');
   $('#eids').attr('value',strv);
});

Upvotes: 2

Related Questions