0

I'm working on a game and there is a form input where the user enters the number of characters. Once this happens more inputs appear for each character's name. My problem right now is reading those names into an array.

When the new inputs are created also a new button called nameButton is created and that is my issue, when I attempt to click that nothing happens when the values should be stored in an array. I put a prompt at the end of the function just to check and that does not even get called.

If you all have any suggestions please let me know here is the jsFiddle

    function nameRecording(names,$this){
    var addRows='<tr id=newRows>';
    for(var i =1; i<=names; i++)
    { var nearTr=$this.closest('tr');
            addRows=addRows+'<td>Name one:</td><td><form><input type="text" name="charcItem" class = "newR"/></form></td>';
    }
    addRows=addRows+'<td><div class="button" id="nameButton"> Add! </div></td></tr>';
    nearTr.after(addRows);
};    
$('#nameButton').click(function(){
    names=$(".newR").map(function(){
        return $(this).val();
    });
    prompt(names);
});

And there are some of my functions.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bala
  • 107
  • 9
  • possible duplicate of [jQuery - Click event doesn't work on dynamically generated elements](http://stackoverflow.com/questions/6658752/jquery-click-event-doesnt-work-on-dynamically-generated-elements) – Barmar Jul 11 '13 at 02:16
  • Definitely not a duplicate @Barmar, my issue is with functionality past the click function. – bala Jul 11 '13 at 02:28
  • The answer you accepted mainly just solves the click function. – Barmar Jul 11 '13 at 02:34

1 Answers1

2

Try this way:

$(".form").on('click', '#nameButton', function () {
    names = $(".newR").map(function () {
        return this.value;
    }).get();
    prompt(names);
});
  • You can use event delegation using on for dynamic elements
  • You need to do a .get() on .map() result to convert the collection object into array.

Demo

PSL
  • 123,204
  • 21
  • 253
  • 243
  • You're a live saver, by the way, will I have to convert these to int's if I plan on using them as so? – bala Jul 11 '13 at 02:25
  • But say I wanted to use this for their ages, would I have to convert to int – bala Jul 11 '13 at 02:29
  • Yeah better to do so, you can just do `return +this.value;` inside the map. Prefix it with unary plus or just use `parseInt(this.value, 10)`. If it cannot be converted to integer it will return `NaN` – PSL Jul 11 '13 at 02:30