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.

3
  • possible duplicate of jQuery - Click event doesn't work on dynamically generated elements Commented Jul 11, 2013 at 2:16
  • Definitely not a duplicate @Barmar, my issue is with functionality past the click function. Commented Jul 11, 2013 at 2:28
  • The answer you accepted mainly just solves the click function. Commented Jul 11, 2013 at 2:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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?
But say I wanted to use this for their ages, would I have to convert to int
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.