Karlo
Karlo

Reputation: 152

jQuery changing attribute elements

I'm working on a form where when user clicks "add server" a div block is repeated. I managed to work that out. But if I have only one server block I want the attribute name="servername" and if there are more elements that attribute should be name="servername[]" on all blocks.

I tried and only thing that works is when clicked add server first and second block gets name="servername[]", but when I click one more time first block gets name="servername[][]".

$('#addserver').click(function() {
var num  = $('.clone').length;  // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1);  // the numeric ID of the new input field being added

// Create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#server1').clone().attr('id', 'server' + newNum);

// Insert the new element after the last "duplicatable" input field  
$('#server' + num).after(newElem);

// Add [] for PHP array
$('#server' + num + ' input', '#server' + newNum + ' input').attr('name', function() {
 return this.name + '[]';
});

// Enable the "remove" button
$('#delserver').attr('disabled','');

// You can only add 5 elements
if (newNum == 5) $('#addserver').attr('disabled','disabled');
});

$('#delserver').click(function() {
var num = $('.clone').length; // how many "duplicatable" input fields we currently have
$('#server' + num).remove(); // remove the last element

// enable the "add" button
$('#addserver').attr('disabled','');

// If only one element remains
if (num-1 == 1) {

    // Remove [] because it's not php array anymore
    $('#server1 input').attr('name', function() {
        s = this.name.substring(0, this.name.length - 2);
        return s;
    });

    // Disable "remove" button
    $('#delserver').attr('disabled','disabled');
}
});

$('#delserver').attr('disabled','disabled');

Here's html example:

<div class="clone" id="server1">
  <input type="text" name="servername" size="40" />
</div>

I need [] because of php array, but if user is entering one server and there is [] in name it doesn't work.

Upvotes: 0

Views: 298

Answers (2)

Jon
Jon

Reputation: 437336

I think that you should simply have name="servername[]" no matter what.

Since you can get it to work when servername contains more than one element, I don't see what stops you from having it work correctly with only one (or even none at all) element as well.

If you are not completely convinced, consider how much trouble you are having right now, trying to fight against what I suggest.

Upvotes: 1

German Rumm
German Rumm

Reputation: 5812

Add a check

if ($(this).attr('name').substr(-2) != '[]') {
    return $(this).attr('name') + "[]";
}

Upvotes: 1

Related Questions