0

Learning to code and having a problem creating arrays from jQuery objects. I would like to give the user the option of adding as many "Favorite Books" as they want to their profile.

The UI is written in jQuery,

<script language="javascript">
    function one()
    {
        var i = 1;
        my.innerHTML = my.innerHTML +"<br><input type='text' name='title'+i[] >"
        var n = 1;
        [
        div.innerHTML = div.innerHTML +"<br><input type='text' name='author'+n[] >"
        ]
    }
</script>

I have tried:

var obj = $('input');
var arr = $.makeArray(obj);

I was hoping it was actually that easy but the output is:

<div id="div">
<br>
<input type="text" +n[]="" name="author">
<br>
<input type="text" +n[]="" name="author">
<br>
<input type="text" +n[]="" name="author">
</div>

I have tried option number two which I found here yet gave me the same output:

var author = new Array();

//get all the authors
$('.auth input').each(function (i)
{
    var author= $(this).val();

    if(author!= '')
    {
        author[author] = author;
        alert(author.length);
    }
});

and same results. I was hoping for results like this:

<div id="div">
<br>
<input type="text" name="author[0]">
<br>
<input type="text" name="author[1]">
<br>
<input type="text" name="author[2]">
</div>

so I can parse out to a PHP array.

3
  • Do you really need to store information in an array? :S Commented Sep 21, 2012 at 9:39
  • Ah! try something like <input type='text' name='author[' + n + ']+' />. I see a lot of possible typo here.. See this Commented Sep 21, 2012 at 9:41
  • Thanks but it outputs <div id="my"> <br> <input type="text" ']+'="" n="" +="" name="UnitID["> <br> <input type="text" ']+'="" n="" +="" name="UnitID["> <br> Commented Sep 21, 2012 at 11:31

1 Answer 1

0

Maybe:

<script language="javascript">
    var i = 0;
    function one(){
       $('#my').append("<br><input type='text' name='title["+i+"]'>");
       $('#div').append("<br><input type='text' name='author["+i+"]'>");
       i++;
    }
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

the variables array[0] does not increment when executed. it just shoots 5 or 10 author[0].
AHA it worked when I put the Variable outside the function. Thanks Mihai

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.