JQUERY: Add more item when insert new data

2.7k Views Asked by At

I am developing the app using CakePHP 1.3 Now I want to make the "Insert function" to add new user into database. I have 2 fields user & pass to insert. But I not only insert 1 user, I want insert one or multiple user (optional). If I want to add more user I will click to "add more" to add new field in view.

In cakephp, it required when we want to insert a array with multiple data. The field name will be define as:

<?php
   echo $this->Form->input('Modelname.0.fieldname');
   echo $this->Form->input('Modelname.1.fieldname');
?>

and in view will be:

<input type="text" id="Modelname0Fieldname" name="**data[Modelname][0][fieldname]**">
<input type="text" id="Modelname1Fieldname" name="**data[Modelname][1][fieldname]**">

My question is: Does JQuery have some function to add new element and how can I increase the index number follow the pattern above data[Modelname][0][fieldname]

Thank for your view and suggestion.

3

There are 3 best solutions below

0
On BEST ANSWER

I've created this code, here it is, I've tested it and it works

http://codepen.io/anon/pen/xbxVQG

var $insertBefore = $('#insertBefore');
var $i = 0;
$('#plusButton').click(function(){
  $i = $i+1;
  $('<br><div class="Index">User N. ' + $i + '</div><br>Username:<br><input type="text" id="Modelname' + $i + 'Fieldname" name="**data[Modelname][' + $i + '][fieldname]**"><br>Password:<br><input type="text" id="Modelname' + $i + 'Password" name="**data[Modelname][' + $i + '][Password]**"><br>').insertBefore($insertBefore);
});
#Userlist{
  border-style:solid;
  width: 300px;
  margin: 0 auto;
  text-align:center;
  padding: 0.5em;
}
.Index{
  background-color:grey;
  text-align:left;
}
#plusButton {
  background-color:green;
  color: white;
  font-size:1.9em;
  width: 300px;
  margin: 0 auto;
  text-align:center;
  cursor: pointer;
}
<html>
<head>
  <title>Add New Users</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>  
<body>  
  <form action="your-script.php" method="post" id="Userlist">
    <div class="Index">User N. 0</div>
     Username:<br>
      <input type="text" id="Modelname0Fieldname" name="**data[Modelname][0][fieldname]**"">
      <br>Password:<br>
      <input type="text" id="Modelname0Password" name="**data[Modelname][0][Password]**">
    <br>
    <div id="insertBefore"></div>
    <br><br><input type="submit" value="Add User">
  </form>
  <div id="plusButton">+</div>
  
</body>
</html>

some important notes:

1- The div who's id="insertBefore" is just to tell jQuery where to put the new duplicated fields.

2- The jQuery code works with an index variable ($i) that starts in 0 and gets incremented by 1 on each new click on the "+" button (so the first time you click, it should get to 1)

3- The original Form's code (where value is 0 by default) is printed everytime the + button is clicked, but replacing each 0 in the html code by '+$i+'

3.2 - If you make some changes to the code of your form, by this method, you should change the javascript code as well. I know it's not an elegant solution to do this, but it shouldn't be so difficult either, just remember to copy the exact html code, delete all intro's and replace all 0's with '+$i+'

4- The "Index N." div is just keeping track of the user's number, you could put your own text there, like "User Nº 0" and in the jQuery code replace the 0 with the value of $i

5- You could put a limit to the number of users (example:10) that can be added by creating an if($i<10){} variable inside the .click() function

0
On

Just write a jQuery code to append a user field. and also send data-id to the javascript.

Let say for example. in your form.

<div id="segment">
    $this->Form->input('User.1.name',array('class'=>'user','data-id'=>1));
</div>

in jquery.you can have a function like this on click of add user,

var lastid = parseInt($('.user:last').attr('data-id');
var newid = lastid+1;

var input = "<input name='data[User][" + newid + "][name]' class='user' id='user-" + newid + "' data-id='" + newid + "' type='text'><br/>";
$('#segement').append(input);

Note that double check the input string, I might miss a quote or anything.

0
On

Thanks for all answers about this, I was not test your code but I found the way to append and increase the index number too. When I have time, I will research about your code.

My code is follow this thread http://www.sanwebe.com/2013/03/addremove-input-fields-dynamically-with-jquery. He made it easily to understand.

The JS:

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

and the HTML:

<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>

The demo you can see in that link above.

More thank for everybody again.