user7832
user7832

Reputation: 51

collecting values from inputs created dynamically

I have the following markup

<span id="add">

  <li style="float: left;margin-right: 10px;">
     <b class="bg">Nom</b><br />
     <input type="text" class="_input _input_text nom"/>
  </li>

  <li>
    <b class="bg">montant investi</b><br />
    <input type="text" class="_input _input_text montant"/>
    <a class="_button"
       onclick="$('#add').append(
          '<span>\
            <li style=\'float: left;margin-right: 10px;\'>\
              <b class=\'bg\'>Nom</b><br />\
              <input type=\'text\' class=\'_input _input_text nom\'/>\
            </li>\
            <li>\
              <b class=\'bg\'>montant investi</b><br />\
              <input type=\'text\' class=\'_input _input_text montant\'/>\
              <a class=\'_button\' style=\'float:right;margin-top:0;margin-left:5px\' \
                onclick=\'$(this).parent().parent().remove();\'>\
                <b>X</b>\
              </a>\
            </li>\
          </span>');"
       style="float: right;margin-top: 0px;margin-left: 5px;">
        Ajouter un associé
    </a>
  </li>

</span>

The onclick function creates a markup with two <li> with input text inside. There are two class of inputs: .nom, .montant.

When I try to collect them using this function:

var _nom=[];

_nom.push($("#add input.nom[type=text]").val());

$.each(_nom, function(key, value) {
  alert(key + ': ' + value);
});

I only get the values of the two inputs that are not created dynamically.

Upvotes: 0

Views: 49

Answers (1)

llamerr
llamerr

Reputation: 3186

You need to use this instead:

$("#add input.nom[type=text]")
.each(function(key, value) {
  alert(key + ': ' + $(value).val());
});

http://jsfiddle.net/4UhqL/

It gives you wrong result, because $("#add input.nom[type=text]") returns you array of elements, not the one element.

Upvotes: 1

Related Questions