Codeigniter Tutorials
- What is codeigniter?
- Application_Architecture
- MVC Architecture
- HMVC Architecture
- Codeigniter Configuration
- Remove index.php from url in codeigniter
- MVC Concept
- View
- Alternate PHP Syntax for View Files
- Routing
- Codeigniter URL
- Get Current URL
- Previous page URL get
- Seo Friendly URL
- Slug Create in codeigniter
- What is _remap() function
- Remove controller name from url in codeigniter
- Codeigniter Controller Class
- Class Constructor
- GET $ POST method in Codeigniter
- Models
- Basepath, Apppath, FCPATH
- URI Segment
- Page Redirect
- Helper class
- Custom Helper class
- Form Helper
- Common Helper Functions
- Common Function
- Array Problems
- Call controller in Helper
- Add active class to menu using Helper class
- Custom Library
- Custom Library Example
- when to use get_instance()
- Codeigniter Hook
- how to work inline css in codeigniter
- Custom 404 page
- 404 custom error page
- Create custom config file in codeigniter
- How to set and get config item value
- How to Speed Up CodeIgniter App?
- Codeigniter Functions
- Session
- cookies
- How to Set & Get Tempdata in Codeigniter
- flash messages in Codeigniter
- Flashdata
- Encryption and Decryption In CodeIgniter
- Codeigniter security
- csrf token form security
- Password Hashing
- Form Validation
- Custom Validation
- Registration Form with validation
- Server Side Form Validation
- Validate Select Option Field
- Date Format Validation
- Date Format change in codeigniter
- Date Functions
- DOB Validation
- CI CRUD
- User SignUp
- User Login
- User Logout
- Login Account
- Login form with RememberMe
- Login Form with session
- User change password
- Change Password with Callback Validation to Check Old Password
- Forgot password
- Reset password
- Insert data in database
- Fetch data from database
- Update data in database
- Delete data in database
- File Upload
- Image Upload with resize Image
- Upload Multiple file and images
- Upload Multiple images with CRUD
- File and image update
- Upload Image Using Ajax.
- Email Send
- Email Send Using Email library
- Email Send Using SMTP Gmail
- Notification send
- store data in json format in DB
- Json parse
- Fetch data Using Ajax with Json data
- How to Show data Using Ajax with Json parse
- Get JSON Data from PHP Script using jQuery Ajax
- Insert data Using Ajax
- Submit data Using Ajax with form validation
- How to show data Using Ajax in codeigniter
- Insert & Update Using Ajax
- Registration Form With Validation Using Ajax in codeigniter
- Delete data Using Ajax Confirmation
- Delete All data Using checkbox selection
- Ajax CSRF Token
- Ajax Post
- Ajax serverside form validation
- Contact form using AJAX with form validation
- DataTable Using Ajax dynamically
- DataTables pagination using AJAX with Custom filter
- DataTables AJAX Pagination with Search and Sort in codeigniter
- DataTables in Codeigniter using Ajax
- Ajax Custom Serarch
- Ajax Live Data Search using Jquery PHP MySql
- Ajax Custom Serarch and sorting in datatable
- Dynamic Search Using Ajax
- Autocomplete using jquery ajax
- Jquery Ajax Autocomplete Search using Typeahead
- Dynamic Dependent Dropdown Using Ajax
- Dynamic Dependent Dropdown list Using Ajax
- Dynamic Dependent Dropdown in codeigniter using Ajax
- ajax username/email availability check using JQuery
- Check Email Availability Using Ajax
- Data Load on mouse scroll
- Ajax CI Pagination
- Pagination in codeigniter
- Ajax Codeigniter Pagination
- email exists or not using ajax with json
- CRUD using AJAX With Modal popup in CI
- Add / Show Data on modal popup using Ajax
- Modal popup Validation using Ajax
- Data show on Modal popup Using Ajax
- Add / Remove text field dynamically using jquery ajax
- How to Add/Delete Multiple HTML Rows using JavaScript
- Delete Multiple Rows using Checkbox
- Multiple Checkbox value
- Form submit using jquery Example
- REST & SOAP API
- Multi-Language implementation in CodeIgniter
- How to pass multiple array in view
- Captcha
- create zip file and download
- PhpOffice PhpSpreadsheet Library (Export data in excel sheet)
- data export in excel sheet
- Excel File generate in Codeigniter using PHPExcel
- Dompdf library
- tcpdf library
- Html table to Excel & docs download
- CI Database Query
- Database Query
- SQL Injection Prevention
- Auth Model
- Join Mysql
- Tree View in dropdown option list
- OTP Integration in codeigniter
- curl post
- download file using curl
- Sweet Alert
- Sweet alert Delete & Success
- Log Message in Codeigniter
- Menu & Submenu show dynamically
- Set Default value in input box
- Cron Jobs
- Stored Procedure
- Display Loading Image when AJAX call is in Progress
- Send SMS
- IP Address
- Codeigniter Tutorialspoint
- Website Link
- How To Create Dynamic Xml Sitemap In Codeigniter
- Paypal Payment Integration
- Get Latitude and Longitude From Address in Codeigniter Using google map API
- How To Create Simple Bar Chart In Codeigniter Using AmCharts?
- dynamic Highcharts in Codeigniter
- Barcode in Codeigniter
- Codeigniter Interview Questions
- Project
Home » Codeigniter »
Add remove text field dynamically using jquery with ajax in codeigniter.
How to Add dynamically Add more fields?
View
<input type="hidden" id="trow_counter" value="1"/>
<div class="" id="mgmt_details" style="">
<div class="row border border-light mb-2" >
<div class="col-md-3">
<div class="form-group">
<label for="formGroupExampleInput"><b>Organisation Name </b><span class="required" aria-required="true"> * </span></label>
<input type="text" class="form-control" id="organisation_name" name="organisation_name[]" value="<?php echo set_value('organisation_name[]'); ?>" placeholder="Company/Organisation Name" maxlength="255" required />
<span class="required" id="organisation_name_error" aria-required="true"></span>
<span class="error"><?php echo form_error('organisation_name[]'); ?></span>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="formGroupExampleInput"><b>Experience (Years) </b><span class="required" aria-required="true"> * </span></label>
<select name="work_experience_year[]" id="work_experience_year" class="form-control" required >
<option value=""> --- Select Year ---</option>
<!-- <option value="1" <?php //echo set_select('work_experience_year[]','1')?>>1 Years</option> -->
<option value="0">0 Year</option>
<option value="1">1 Year</option>
<option value="2">2 Years</option>
<option value="3">3 Years</option>
<option value="4">4 Years</option>
<option value="5">5 Years</option>
<option value="6">6 Years</option>
<option value="7">7 Years</option>
<option value="8">8 Years</option>
<option value="9">9 Years</option>
<option value="10">10 Years</option>
</select>
<span class="required" id="work_experience_year_error" aria-required="true"></span>
<span class="error"><?php echo form_error('work_experience_year[]'); ?></span>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="formGroupExampleInput"><b>Experience (Months) </b><span class="required" aria-required="true"> * </span></label>
<select name="work_experience_month[]" id="work_experience_month" class="form-control" required >
<option value=""> --- Select Months ---</option>
<!-- <option value="0" <?php // echo set_select('work_experience_month[]','0')?>>0 Month</option> -->
<option value="0">0 Month</option>
<option value="1">1 Month</option>
<option value="2">2 Months</option>
<option value="3">3 Months</option>
<option value="4">4 Months</option>
<option value="5">5 Months</option>
<option value="6">6 Months</option>
<option value="7">7 Months</option>
<option value="8">8 Months</option>
<option value="9">9 Months</option>
<option value="10">10 Months</option>
<option value="11">11 Months</option>
</select>
<span class="required" id="work_experience_month_error" aria-required="true"></span>
<span class="error"><?php echo form_error('work_experience_month[]'); ?></span>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="formGroupExampleInput2"><b>Experience Letter</b><span class="required" aria-required="true"> * </span></label>
<input type="file" id="experience_letter" name="experience_letter[]" class="" onchange="Validatefile_onlypdf(this.id,this.value)" >
<p style="color:green;">File format (pdf)/ Max size:1MB</p>
<span class="required" id="experience_letter_error" aria-required="true"></span>
<span class="help-block" style="color:red;"><?php echo form_error('experience_letter[]'); ?></span>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="formGroupExampleInput2" class=""><b>Add/Remove</b> </label>
<div class="float-right"> <a href="javascript:add_work_experience()" class="btn btn-primary"> <i class="fa fa-plus"></i> Add</a>
</div>
</div>
</div>
</div> <!-- end row -->
<hr>
</div>
Js Function :-
<script>
function add_work_experience(){
var formFiled = true;
$('#mgmt_details input').each(function()
{
if($(this).val() == "") formFiled = false;
});
if (!formFiled) {
swal("error!", "Please fill up all mandatory fields of work experience", "error");
exit;
}
var id=$("#trow_counter").val();
id = eval(parseInt(id)+1);
if(id<=10){
var html = '<div class="row border border-light mb-2" id="trow'+id+'"><div class="col-md-3"><div class="form-group"><input type="text" class="form-control" id="organisation_name_'+id+'" name="organisation_name[]" placeholder="Organisation Name" maxlength="255" required /><span class="required" id="organisation_name_error" aria-required="true"></span><span class="error"><?php echo form_error('organisation_name[]'); ?></span></div></div><div class="col-md-2"><div class="form-group"><select name="work_experience_year[]" id="work_experience_year_'+id+'" class="form-control" required ><option value=""> --- Select Year ---</option><option value="0">0 Year</option> <option value="1">1 Year</option><option value="2">2 Years</option><option value="3">3 Years</option><option value="4">4 Years</option><option value="5">5 Years</option><option value="6">6 Years</option><option value="7">7 Years</option><option value="8">8 Years</option><option value="9">9 Years</option><option value="10">10 Years</option> </select><span class="required" id="work_experience_year_'+id+'_error" aria-required="true"></span><span class="error"><?php echo form_error('work_experience_year[]'); ?></span></div></div><div class="col-md-2"><div class="form-group"><select name="work_experience_month[]" id="work_experience_month_'+id+'" class="form-control" ><option value=""> --- Select Months ---</option><option value="0">0 Month</option><option value="1">1 Month</option><option value="2">2 Months</option><option value="3">3 Months</option><option value="4">4 Months</option><option value="5">5 Months</option><option value="6">6 Months</option><option value="7">7 Months</option><option value="8">8 Months</option><option value="9">9 Months</option><option value="10">10 Months</option><option value="11">11 Months</option></select><span class="required" id="work_experience_month_'+id+'_error" aria-required="true"></span><span class="error"><?php echo form_error('work_experience_month[]'); ?></span></div></div><div class="col-md-3"><div class="form-group"><input type="file" id="experience_letter'+id+'" name="experience_letter[]" class="" onchange="Validatefile_onlypdf(this.id,this.value)" required ><span class="required" id="experience_letter'+id+'_error" aria-required="true"></span><span class="error"><?php echo form_error('experience_letter[]'); ?></span><p style="color:green;">File format (pdf)/ Max size:1MB</p></div></div><div class="col-md-2"><div class="form-group"><div class="float-sm-right"> <a href="javascript:remove_Row(\'trow'+id+'\')" class="btn btn-danger"> <i class="fa fa-minus" aria-hidden="true"></i></a></div></div></div></div>';
$("#mgmt_details").append(html);
$("#trow_counter").val(id.toString());
}
else{
swal("error!", "You can Add Maximum 10 Rows only", "error");
}
}
function remove_Row(row){
var id=$("#trow_counter").val();
$("#"+row).remove();
id--;
$("#trow_counter").val(id);
}
</script>
Controller Class
$this->form_validation->set_rules('organisation_name[]', 'Company/Organisation Name', 'trim|required');
$this->form_validation->set_rules('work_experience_year[]', 'Year', 'trim|required');
$this->form_validation->set_rules('work_experience_month[]', 'month', 'trim|required');
$organisation_name = $this->input->post('organisation_name');
$work_experience_year = $this->input->post('work_experience_year');
$work_experience_month = $this->input->post('work_experience_month');
$conunt_org = count($organisation_name);
$conunt_year = count($work_experience_year);
$conunt_month = count($work_experience_month);
$count_exp_letter = count(array_filter($_FILES['experience_letter']['name']));
if($conunt_org != $count_exp_letter)
{
//$this->form_validation->set_rules("experience_letter", "Experience letter", "callback_file_check_experience_letter");
$this->form_validation->set_rules('experience_letter[]', 'Experience Letter', 'required');
}
/*
$organisation_name = $this->input->post('organisation_name');
$work_experience_year = $this->input->post('work_experience_year');
$work_experience_month = $this->input->post('work_experience_month');
foreach($organisation_name as $key=>$val)
{
$this->form_validation->set_rules("organisation_name[]", "Organization", "trim|required");
$this->form_validation->set_rules("work_experience_year[]", "year", "trim|required");
$this->form_validation->set_rules("work_experience_month[]", "month", "trim|required");
if(empty($_FILES['experience_letter']['name']))
{
$this->form_validation->set_rules('experience_letter[]', 'Experience Letter', 'required');
}
}
*/
if(!empty($organisation_name) && !empty($work_experience_year) && !empty($work_experience_month))
{
if(!empty($_FILES['experience_letter']['name']) && count(array_filter($_FILES['experience_letter']['name']))>0)
{
$upload_path_dir = '/media/bissales/bissalespdf/hrdportal/yp/experience_letter/';
if (!is_dir($upload_path_dir)) {
$oldmask = umask(0);
mkdir($upload_path_dir,0777,TRUE);
umask($oldmask);
}
//$this->load->helper('common');
$docs = multiple_file_uploading($upload_path_dir,array_filter($_FILES['experience_letter']),$_SESSION['UserID']);
if ($docs === FALSE){
$error = array('errors' => $this->upload->display_errors());
} else {
$experience_letter_name = $docs;
}
}
for($k = 0; $k < count($organisation_name); $k++)
{
$work_exp_array[] = array(
'fki_applicant_id' => $user_pk_id,
'application_type' => 'STND',
'organisation_name' => $organisation_name[$k],
'work_experience_year' => $work_experience_year[$k],
'work_experience_month' => $work_experience_month[$k],
// 'work_experience' => $experience_year_total[$k],
'experience_letter' => $experience_letter_name[$k],
'created_on' => date('Y-m-d H:i:s'),
'created_by' => $_SESSION['UserID'],
);
}
// echo "<pre>"; print_r($work_exp_array); echo "</pre>"; die;
$result_data = $this->Yp_model->InsertArray($table='yp_work_experience',$work_exp_array);
}
multiple_file_uploading() Helper function
function multiple_file_uploading($upload_path_directory,$files,$userid) {
$CI = get_instance();
//$CI->load->model('Common');
$CI->load->library('upload');
$date = date('Y_m_d');
$time = time();
$filesCount = count($files['name']);
for($i = 0; $i < $filesCount; $i++){
$info = pathinfo($files['name'][$i]);
$uploadfile_names = $info['filename'];
$uploadfile_name = str_replace(' ', '_', $uploadfile_names);
$extension = $info['extension'];
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$random_strng = substr(str_shuffle($characters), 0, 10);
$filename = $random_strng.'_'.$date.'_'.$time.'_'.$userid.'.'.$extension;
//$filename = $uploadfile_name .'_'.$date.'_'.$time.'.' . $extension;
$_FILES['file']['name'] = $filename;
$_FILES['file']['type'] = $files['type'][$i];
$_FILES['file']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['file']['size'] = $files['size'][$i];
$config['upload_path'] = $upload_path_directory;
$config['allowed_types'] = 'jpg|jpeg|png|pdf|doc|docx';
$config['file_name'] = $filename;
$config['max_size'] = '10000';
$CI->load->library('upload', $config);
$CI->upload->initialize($config);
if(!$CI->upload->do_upload('file',$filename)){
return false;
}else{
$allfiles[] = $filename;
}
}
$total_upload_file = count($allfiles);
if($total_upload_file>1){
return $allfiles;
}else{
$files = $allfiles;
return $files;
}
}
Controller
File Name : Addremove.php
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Addremove extends CI_Controller {
function __construct()
{
parent::__construct();
//$this->load->model('Auth_model');
}
public function index() {
$this->load->view('addremove');
}
public function addmore()
{
if(!empty($this->input->post('name'))){
foreach ($this->input->post('name') as $key => $value) {
//$sql = "INSERT INTO tagslist(name) VALUES ('".$value."')";
//$this->db->query($sql);
//$this->db->set('name',$value);
//$this->db->insert('tagslist');
$this->Auth_model->store_data($value);
}
echo json_encode(['success'=>'Names Inserted successfully.']);
}
exit;
}
}
View
File Name :
<!DOCTYPE html>
<html>
<head>
<title>PHP - Dynamically Add or Remove input fields using JQuery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2 align="center">PHP - Dynamically Add or Remove input fields using JQuery</h2>
<div class="form-group">
<form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" required="" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
//var postURL = "/addmore.php";
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" required /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
//url:postURL,
url:'<?php echo base_url()?>addremove/addmore',
method:"POST",
data:$('#add_name').serialize(),
type:'json',
success:function(data)
{
i=1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
alert('Record Inserted Successfully.');
}
});
});
});
</script>
</body>
</html>
model
public function store_data($value)
{
$sql = "INSERT INTO tagslist(name) VALUES ('".$value."')";
$this->db->query($sql);
//$this->db->insert('tagslist',$sql);
//return;
}
Example : add/remove multiple input fields dynamically with jquery
CREATE TABLE IF NOT EXISTS `tagslist` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=24 ;
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['add-more'] = "AddMoreController";
$route['add-more-post']['post'] = "AddMoreController/storePost";
AddMoreController.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class AddMoreController extends CI_Controller {
/**
* Get All Data from this method.
*
* @return Response
*/
public function __construct() {
parent::__construct();
$this->load->database();
}
/**
* Get All Data from this method.
*
* @return Response
*/
public function index()
{
$this->load->view('addMore');
}
/**
* Get All Data from this method.
*
* @return Response
*/
public function storePost()
{
if(!empty($this->input->post('addmore'))){
foreach ($this->input->post('addmore') as $key => $value) {
$this->db->insert('tagslist',$value);
}
}
print_r('Record Added Successfully.');
}
}
addMore.php
PHP Codeigniter - Dynamically Add or Remove input fields using JQuery
Dynamically Add or Remove input fields using JQuery
<!DOCTYPE html>
<html>
<head>
<title>Dynamically Add or Remove input fields using JQuery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2 align="center">PHP - Dynamically Add or Remove input fields using JQuery</h2>
<div class="form-group">
<form name="add_name" method="POST" action="/add-more-post">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="addmore[][name]" placeholder="Enter your Name" class="form-control name_list" required="" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td><input type="text" name="addmore[][name]" placeholder="Enter your Name" class="form-control name_list" required /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
</body>
</html>