TK-421
TK-421

Reputation: 349

How do I access input name in php code through Javascript?

I have a PHP form with some rows. These rows have fields which look like this:

<input type="text" name="addresses[n][0]" value="mail " id="address" class="validate">

I have the following code in Javascript to add and and delete rows:

                    $(document).ready(function () {
                        $('select').material_select();
                    });
                    $(function ()
                    {

                        $(document).on('click', '.btn-add', function (e)
                        {
                            e.preventDefault();

                            var controlForm = $('.controls form:first'),
                                    currentEntry = $(this).parents('.entry:first'),
                                    newEntry = $(currentEntry.clone()).appendTo(controlForm);

                            newEntry.find('input').val('');
                        }).on('click', '.btn-remove', function (e)
                        {
                            $(this).parents('.entry:first').remove();

                            e.preventDefault();
                            return false;
                        });
                    });

My problem is, that after sending this form in POST with added rows, the added ones have the same 'n' index, because they are cloned. How can I access the 'name' attribute of them in the newEntry variable, which is a div of the whole row?

I have tried things like

newEntry.find('name').val('addressesNewName')
newEntry.find('input').getAttribute('name') = 'addressesNewName'
newEntry.find('name').setAttribute("name","addressesNewName");
newEntry.find('input').find('name').val('addressesNewName');
newEntry.find('input').attr('name') = 'newaddresses';
newEntry.find('input').attr('name').val('newaddresses');

But nothing changes the name in the field.

I don't need help with what n values to assign and so on, only how to change the name of the input field.

Upvotes: 1

Views: 419

Answers (1)

junglarr
junglarr

Reputation: 26

Have you tried?

newEntry.attr('name', 'addressesNewName');

Since you're using jQuery, accessing node attributes is easily done via:

$(node).attr('attributeName'); // get attribute value
$(node).attr('attributeName', 'newValue'); // set attribute value

jQuery API

Upvotes: 1

Related Questions