Remove DIV dynamically with JQuery - javascript

i have a problem to reference an identifier of a DIV. I allow to add a div with a text field and a button to delete the text field, and i set a id to the DIV like an array with this code:
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso['+$count+']>' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
'<a class="btn btn-default" id="eliminacorso['+$count+']" aria-label="Elimina">' +
'<i class="fa fa-times" aria-hidden="true"></i>' +
'</a>' +
'</div>' +
'</div>' +
'');
});
So.. if i press on the botton at the at the side of the text area, i'll call a function that will remove it.
The skeleton of the function is the follow:
$('#eliminacorso[]').on('click', function() {
$count --;
$('#corso[]').remove();
});
So my ask is: How can i insert between the square brackets the right identifier of the div?

A better choice is:-
1.Instead of using id use button class
2.And then use event delegation concept like below:-
$(document).on('click','.btn-default',function(){
$(this).closest('.form-group').remove();
});
Reference:- https://api.jquery.com/closest/

Use as below the script that add DIV. Remove '[' from id attribute from div tag and anchor tag as below
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso'+$count+'>' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
'<a class="btn btn-default" id="corso'+$count+'" aria-label="Elimina">' +
'<i class="fa fa-times" aria-hidden="true"></i>' +
'</a>' +
'</div>' +
'</div>' +
'');
});
And then script to get the clicked id and remove the matched div on click of button as below
$('.btn').on('click', function() {
var selectedId = $(this).attr('id');
$('#'+selectedId).remove();
});

Try below code.It may help you
var $count =0
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso_'+$count+'">' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso_'+ $count + '"/>' +
'<a class="btn btn-default" id="eliminacorso_'+$count+'" aria-label="Elimina" onclick="remove(this);">' +
'Test' +
'</a>' +
'</div>' +
'</div>' +
'');
});
function remove(aRemove){
console.log(aRemove);
var divid = aRemove.id.replace("eliminacorso_","corso_");
$("#" + divid).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="aggiungi"> Click ME </button>
<div id="corsi">
</div>

https://codepen.io/vino4all/pen/vZrQEX
Try this code.
<button id="aggiungi">Click</button>
<div id="corsi"></div>
Add a class attribute to the <a> tag.
var $count = 0;
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso['+$count+']>' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
'<a class="btn btn-default delBtn" id="eliminacorso['+$count+']" aria-label="Elimina"><span>X</span>' +
'<i class="fa fa-times" aria-hidden="false"></i>' +
'</a>' +
'</div>' +
'</div>' +
'');
});
$('#corsi').on('click', '.delBtn', function() {
console.log('this :'+$(this));
$count --;
$(this).parent().parent().remove();
});
Notice the usage of on function.
It should be like below
$('#corsi').on('click', '.delBtn', fun);

You can use something like this
var count = 3;
$('button').click(function(){
count--;
$($('.corso')[count]).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="corso">1. <input type="text" /></div><br />
<div class="corso">2. <input type="text" /></div><br />
<div class="corso">3. <input type="text" /></div><br />
<br />
<button>Remove</button>

Try this:
var $count = 0
$('#aggiungi').on('click', function () {
$count++;
let divId = `input_div_${$count}`;
let html = `<div class="form-group row" id="${divId}">
<label class="col-sm-2 col-form-label" for="corsi">Input ${$count}</label>
<div class="col-sm-10 form-inline">
<input type="text" class="form-control" id="input" name="${divId}"/>
<button type="button" id="remove_btn_${$count}" aria-label="Elimina" onclick="remove('${divId}');">
remove
</a>
</div>
</div>`;
$('#main-div').append(html);
});
function remove(removeDivId) {
console.log(removeDivId);
$("#" + removeDivId).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="aggiungi"> Click ME </button>
<div id="main-div">
</div>

Related

How to dynamically add form elements in jquery?

I'm trying to created a dynamic form in rails with a little bit of javascript I have a problem I only get one row in the output when using pry apparently it's because I have the same params for every field input since I use jQuery .clone, maybe someone has struggled with something similar can share some knowledge, how to dynamically add index to params in this form with javascript ?
#extends('Admin.master')
#section('content')
<div class="p-5">
<h3><i class="fas fa-cog ml-2"></i>Setting</h3><hr>
<form action="{{ route('settings.update', $setting->id) }}" method="POST" >
#csrf
#method('PUT')
<div id="showDynamic">
</div>
</form>
</div>
#endsection
#section('script')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
let count = 1;
$('.add').click(function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary" id="add">Add</a>\n' +
'<a class="btn btn-danger" id="delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
</script>
#endsection
1st id must be unique .. So change id="add" and id="delete" to classes class="btn btn-primary add"
2nd event-binding-on-dynamically-created-elements After changing the id to class use $(document).on('click' , '.add' , function(){ //code here })
Your code should be
<script>
$(document).ready(function(){
let count = 1;
$(document).on('click' , '.add' , function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary add">Add</a>\n' +
'<a class="btn btn-danger delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
</script>
$(document).ready(function(){
let count = 1;
$(document).on('click' , '.add' , function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary add">Add</a>\n' +
'<a class="btn btn-danger delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showDynamic"></div>

How to get ID dynamic in Jquery?

I am making dynamic input, when the user clicks "Add From Checklist" there will be an input form, and if clicked again "Add From Checklist" then the input form becomes two and so on, for the actual select code there is already data such as
'1-022020-001', now for inputting stations and equipment, the data is where the value '1-022020-001' is in the database, now I'm still confused about how to get results from value '1-022020-001' can be sent to the controller and returned to js to display the input Station and Equipment.
DEMO:
var html = '';
$('.btnSend').attr('disabled', true);
$("#inputCode, #inputStasiun, #inputPeralatan").select2({
placeholder: "Choose one",
allowClear: true
});
var runNumberAdd = 1;
$("#add-more").click(function() {
html =
'<div class="col-sm-6 control-group">'+
'<div class="panel panel-default" style="padding: 10px;">'+
'<div class="form-horizontal">'+
'<div class="form-group">'+
'<label class="col-sm-2 control-label">Tanggal</label>'+
'<div class="col-sm-10">'+
'<input name="inputTgl[]" type="date" id="inputTglClone'+ runNumberAdd +'" class="form-control inputTglClone">'+
'</div>'+
'</div>'+
'<div class="form-group">'+
'<label class="col-sm-2 control-label">Code</label>'+
'<div class="col-sm-10">'+
'<select name="inputCode[]" id="inputCodeClone'+ runNumberAdd +'" class="form-control select2 inputCodeClone">'+
'</select>'+
'</div>'+
'</div>'+
'<div class="form-group">'+
'<label class="col-sm-2 control-label">Stasiun</label>'+
'<div class="col-sm-10">'+
'<select name="inputStasiun[]" id="inputStasiunClone'+ runNumberAdd +'" class="form-control select2 inputStasiunClone">'+
'</select>'+
'<input name="inputStasiunHidden[]" type="text" id="inputStasiunHiddenClone'+ runNumberAdd +'" class="form-control inputStasiunHiddenClone">'+
'</div>'+
'</div>'+
'<div class="form-group">'+
'<label class="col-sm-2 control-label">Peralatan</label>'+
'<div class="col-sm-10">'+
'<select name="inputPeralatan[]" id="inputPeralatanClone'+ runNumberAdd +'" class="form-control select2 inputPeralatanClone">'+
'</select>'+
'</div>'+
'</div>'+
'<div class="form-group">'+
'<label class="col-sm-2 control-label">Deskripsi</label>'+
'<div class="col-sm-10">'+
'<textarea name="inputDeskripsi[]" id="inputDeskripsiClone'+ runNumberAdd +'" class="form-control inputDeskripsiClone"></textarea>'+
'</div>'+
'</div>'+
'<div class="form-group">'+
'<label class="col-sm-2 control-label">Resume</label>'+
'<div class="col-sm-10">'+
'<label class="radio-inline">'+
'<input type="radio" name="inputChecklist[]" id="inputChecklist1Clone'+ runNumberAdd +'" class="inputChecklist1Clone'+ runNumberAdd +'" value="1"> OK'+
'</label>'+
'<label class="radio-inline">'+
'<input type="radio" name="inputChecklist[]" id="inputChecklist2Clone'+ runNumberAdd +'" class="inputChecklist2Clone'+ runNumberAdd +'" value="0"> NOK'+
'</label>'+
'<div class="pull-right">'+
'<button type="button" class="btn btn-danger btn-sm remove_list"> Hapus From Checklist</button>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>';
$('.clone-form').append(html);
$(".inputCodeClone, .inputStasiunClone, .inputPeralatanClone").select2({
placeholder: "Choose one",
allowClear: true
});
$.ajax({
url : 'showDataCode',
dataType : 'JSON',
async : true,
success : function(data) {
var minrunNumberAdd = runNumberAdd - 1;
var attrCode = '#inputCodeClone' + minrunNumberAdd;
$(attrCode).append($("<option selected disabled></option>").attr("value", '').text(''));
$.each(data, function(key, value) {
$(attrCode).append($("<option></option>").attr("value", value.id).text(value.code));
});
}
});
$('.btnSend').attr('disabled', false);
$('.inputStasiunClone').attr("disabled", true);
$('.inputPeralatanClone').attr("disabled", true);
runNumberAdd++;
});
$("body").on("click", ".remove_list",function() {
var numItems = $('.control-group').length;
$(this).parents(".control-group").remove();
if (numItems == 1) {
$('.btnSend').attr('disabled', true);
} else {
$('.btnSend').attr('disabled', false);
}
});
// How to get attribut ID
// My Xample
$('input[id^="inputCodeClone"]').on('click', function() {
alert('A');
});
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<div class="box-header">
<div class="pull-right">
<button type="button" id="add-more" class="btn btn-success btn-sm"> Tambah From Checklist</button>
</div>
</div>
<form action="<?= base_url('GeneralFormChecklist/submitChecklist'); ?>" method="post" id="formInput">
<div class="box-body">
<div class="clone-form">
</div>
</div>
<div class="box-footer">
<div class="pull-right">
<button type="submit" class="btn btn-primary btn-sm btnSend">Kirim Checklist</button>
</div>
</div>
</form>
Sample data in a database
The question is:
how to be able to display id_location in the input station and id_equipment_name in the input equipment by selecting code as where in the database later?
NOTE: the code that I have stuck when looking for a dynamic ID
if you want to get the value of current input that you clicked or all the nearest inputs then you can use $(this).
it helps you to point on the currently focused or clicked element.
I just try to add some fields .You modify
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="box-header">
<div class="pull-right">
<button type="button" id="add-more" class="btn btn-success btn-sm"> Tambah From Checklist</button>
</div>
</div>
<form action="<?= base_url('GeneralFormChecklist/submitChecklist'); ?>" method="post" id="formInput">
<div class="box-body">
<div class="clone-form">
</div>
</div>
<div class="box-footer">
<div class="pull-right">
<button type="submit" class="btn btn-primary btn-sm btnSend">Kirim Checklist</button>
</div>
</div>
</form>
<script>
$(document).ready(function(){
var html = '';
$('.btnSend').attr('disabled', true);
$("#inputCode, #inputStasiun, #inputPeralatan").select2({
placeholder: "Choose one",
allowClear: true
});
var runNumberAdd = 1;
$("#add-more").click(function() {
html = $('<div/>', {
'class': 'col-sm-6 control-group'
});
var firstchild = $('<div/>', {
'class': 'form-group'
});
var lable1 = $('<label/>', {
'class': 'col-sm-2 control-label',
text: 'Tanggal',
id: 'lbl1'
}).on('click',function(){
alert("First lable");
});
var innerchild = $('<div/>', {
'class': 'col-sm-10'
});
var firstinput = $('<input/>', {
'class': 'form-control inputTglClone',
id: 'inputTglClone'+ runNumberAdd,
type: 'date'
});
innerchild.append(firstinput);
firstchild.append(lable1);
firstchild.append(innerchild);
html.append(firstchild);
var lable2 = $('<label/>', {
'class': 'col-sm-2 control-label',
text: 'Code',
id: 'lbl2'
}).on('click',function(){
alert("First lable");
});
runNumberAdd = 2;
var firstselectinput = $('<select/>', {
'class': 'form-control select2 inputCodeClone',
id: 'inputTglClone_select',
});
var innerchild1 = $('<div/>', {
'class': 'col-sm-10'
});
var secondchild = $('<div/>', {
'class': 'form-group'
});
innerchild1.append(firstselectinput);
secondchild.append(lable2);
secondchild.append(innerchild1);
html.append(secondchild);
$('.clone-form').html(html);
$(".inputCodeClone, .inputStasiunClone, .inputPeralatanClone").select2({
placeholder: "Choose two",
allowClear: true,
data:[{id:'1',text:'one'},{id:'2',text:'two'}],
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {id: term,text: term}
}
}).on("change", function (e) {
var selectedvalue = e.currentTarget.selectedOptions[0].value;
alert(selectedvalue);
});
$('.btnSend').attr('disabled', false);
$('.inputStasiunClone').attr("disabled", true);
$('.inputPeralatanClone').attr("disabled", true);
runNumberAdd++;
});
$("body").on("click", ".remove_list",function() {
var numItems = $('.control-group').length;
$(this).parents(".control-group").remove();
if (numItems == 1) {
$('.btnSend').attr('disabled', true);
} else {
$('.btnSend').attr('disabled', false);
}
});
});
</script
</body>

Remove dynamically generated textboxes

I have the following javascript that dynamically add textboxes together with a remove button to a div. How can I using the remove button delete the content of the row being selected to delete?
<script type="text/javascript">
function GetDynamicTextBox(value) {
return('' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Key" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.StartDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.EndDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.Description" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(this)"><i class="fa fa-angle-right"></i> Remove</button>' +
'</div>');
}
function AddTextBox() {
var div = document.createElement('DIV');
div.className = "form-group";
div.innerHTML = GetDynamicTextBox("");
document.getElementById("divcontent").appendChild(div);
}
function RemoveTextBox(div) {
//document.getElementById("divcontent").removeChild(div.parentNode); // this does not work
iterateBoxesAndSetUniqueIds();
}
function iterateBoxesAndSetUniqueIds() {
// Set unique names of each textbox
var children = document.getElementById("divcontent").children;
for (i = 0; i < children.length; i++)
{
var el = children[i];
el.name = 'events[' + i + '].Key'; //
el.id = 'events[' + i + '].Key';
el.name = 'events[' + i + '].Value.StartDate';
el.id = 'events[' + i + '].Value.StartDate';
el.name = 'events[' + i + '].Value.EndDate';
el.id = 'events[' + i + '].Value.EndDate';
el.name = 'events[' + i + '].Value.Description';
el.id = 'events[' + i + '].Value.Description';
}
}
</script>
<button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button>
<div id="divcontent">
</div>
UPDATE
I added a snippet for updating the id for each textbox, but obviously I am doing something wrong here. Can anyone help with this too?
I assume you want to remove the entire row, so heres how to do that.
You almost had it, since you pass (this) in the onclick, it means we have a direct reference to the button that was clicked. From there, we can get its grandparent by using .parentNode twice (since the first parent is .col-md-2) and then use the remove() function.
div.parentNode.parentNode.remove()
function GetDynamicTextBox(value) {
return('' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Key" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.StartDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.EndDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.Description" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(this)"><i class="fa fa-angle-right"></i> Remove</button>' +
'</div>');
}
function AddTextBox() {
var div = document.createElement('DIV');
div.className = "form-group";
div.innerHTML = GetDynamicTextBox("");
document.getElementById("divcontent").appendChild(div);
}
function RemoveTextBox(div) {
div.parentNode.parentNode.remove()
}
<button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button>
<div id="divcontent">
</div>
function GetDynamicTextBox(value, uniquedId) {
return('' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Key" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.StartDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.EndDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.Description" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(\'' + uniquedId +'\')"><i class="fa fa-angle-right"></i> Remove</button>' +
'</div>');
}
function AddTextBox() {
var uniquedId = Math.floor(Math.random() * 100) + '_unique';
var div = document.createElement('DIV');
div.setAttribute("id", uniquedId);
div.className = "form-group";
div.innerHTML = GetDynamicTextBox("", uniquedId);
document.getElementById("divcontent").appendChild(div);
}
function RemoveTextBox(uniquedId) {
var elem = document.getElementById(uniquedId);
return elem.parentNode.removeChild(elem);
}
<button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button>
<div id="divcontent">
</div>
<script type="text/javascript">
function GetDynamicTextBox(value, uniquedId) {
return('' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Key" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.StartDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.EndDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.Description" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(\'' + uniquedId +'\')"><i class="fa fa-angle-right"></i> Remove</button>' +
'</div>');
}
function AddTextBox() {
var uniquedId = Math.floor(Math.random() * 100) + '_unique';
var div = document.createElement('DIV');
div.setAttribute("id", uniquedId);
div.className = "form-group";
div.innerHTML = GetDynamicTextBox("", uniquedId);
document.getElementById("divcontent").appendChild(div);
}
function RemoveTextBox(uniquedId) {
var elem = document.getElementById(uniquedId);
return elem.parentNode.removeChild(elem);
}
</script>
<button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button>
<div id="divcontent">
</div>

INSERT data from append script

I have a problem.
here is my php & HTML:
<?php
if ($_POST['btn_tambah'] == 'tambah') {
$sub_lapangan = $_POST['sub_lapangan'];
$SQL = "SELECT AUTO_INCREMENT as IDLapangan FROM information_schema.tables WHERE TABLE_SCHEMA = 'ta' AND TABLE_NAME = 'lapangan';";
$res = mysql_query($SQL, $link);
$row = mysql_fetch_object($res);
$tambah1 = mysql_query("INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES('".$sub_lapangan."',1,$row->IDLapangan);");
}
?>
<HTML><BODY>
<div class="row">
<div class="form-group" id="sub_lapangan">
<div class="col-lg-3"><label>Nama Sub-Lapangan :</label></div>
<div class="col-lg-2">
<input type="text" name="sub_lapangan" class="form-control" required>
</div>
<div class="col-lg-1">
<a onclick="tambahSubBaru()" class ="btn btn-info"> <i class="fa fa-plus"></i></a>
</div>
</div>
</div>
<div id="sembunyisub">
</div>
</BODY></HTML>
Here is my script:
var count = 0;
function tambahSubBaru() {
count += 1;
if (count > 15) {
alert("Maksimal Untuk Tambah Sub Lapangan adalah 15 Sub Lapangan");
}
else {
$('#sembunyisub').append(
'<div class="row" id="barisbarusub' + count + '">'
+ '<div class="form-group">'
+ '<div class="col-lg-3">'
+ '</div>'
+ '<div class="col-lg-2">'
+ '<input id="subku' + count + '" type="text" class="form-control" name="sub_lapangan" required>'
+ '</div>'
+ '<div class="col-lg-1">'
+ '<a class ="btn btn-warning" onclick="hapusSub(' + count + ')"> <i class="fa fa-trash"></i></a>'
+ '</div>'
+ '</div>'
+ '</div>'
);
}
}
function hapusSub(row) {
$('#barisbarusub' + row).remove();
}
Here is the pic:
So the scenario is, when i click the "plus" button, it will show up the second textbox. I want to insert them into database. but when i try to insert, the SECOND textbox is succedded to insert in database. but the FIRST textbox doesn't insert to database.
How can i insert the FIRST textbox?
to show up the second textbox, i use .append in javascript.
help me please. I aprreciated the answer. many thank you. :)
You have to loop through your fields in PHP. Therefore you have to create an Array-input-element with [] after the name.
HTML:
<input type="text" name="sub_lapangan[]" class="form-control" required> <!-- Add [] to your field name for creating an Array-->
JS:
+ '<input id="subku' + count + '" type="text" class="form-control" name="sub_lapangan[]" required>' //The same in you dynamic input field
PHP: Loop through you fields (Array)
if ($_POST['btn_tambah'] == 'tambah') {
$sub_lapangan = $_POST['sub_lapangan'];
$SQL = "SELECT AUTO_INCREMENT as IDLapangan FROM information_schema.tables WHERE TABLE_SCHEMA = 'ta' AND TABLE_NAME = 'lapangan';";
$res = mysql_query($SQL, $link);
$row = mysql_fetch_object($res);
$fields = $_POST['sub_lapangan']; //Your Array
foreach($fields as $field => $value) {
$tambah1 = mysql_query("INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES('".$value."',1,$row->IDLapangan);");
}
}
Try this:
'INSERT INTO sub_lapangan(nama,status,id_lapangan) VALUES("'.$sub_lapangan.'","1","'.$row->IDLapangan.'")'

Can't get textarea value in PHP

I have a submit form for writing a caption in an image. I'm using plupload for this. When file is uploaded it will append a div and inside it is a textarea where you can write your caption of that image. But I always getting an error of Undefined Index when submitting a form.
This is my code when file was uploaded:
uploader.bind('FileUploaded', function(up, file) {
var filename = file.id + '.' + file.name.split(".").pop()
var uploaded_files = $('#uploaded_files').attr('value');
var appended_files = uploaded_files + file.id + ',';
$('#uploaded_files').attr('value', appended_files);
var prev = '<div class="col-sm-12" style="margin-bottom:5px;" id="upload-' + file.id + '">' +
'<div class="col-sm-3">' +
'<img class="img-thumbnail" width="100%" height="auto" src="./assets/images/gallery/resorts_gallery/' + filename + '">' +
'</div>' +
'<div class="col-sm-6">' +
'<textarea name="' + file.id + '_Caption" class="form-control" style="font-size:12px;height:70px" placeholder="Put a caption"></textarea>' +
'</div>' +
'<div class="col-sm-3"><span class="btn btn-danger btn-xs"><span class="fa fa-times"></span></span></div>' +
'</div>';
$("#prevCap").append(prev);
});
In my html:
<form role="form" method="POST" id="submit-review" enctype="multipart/form-data">
<div class="form-group">
<label for="uploadphoto">Share your Experiences by uploading Photos</label> <span class="small-text">(optional)</span><br/>
<div class="well" id="caption-thumb"> <!-- preview and caption -->
<div id="prevCap" class="col-sm-12" style="margin-bottom:10px"></div>
<input type="hidden" name="uploaded_files" id="uploaded_files" value="" />
<hr>
<button class="btn btn-default navbar-btn" type="button" data-toggle="modal" data-target="#upload-modal">Add Photos</button>
<hr id="hr-line" style="display:none">
</div>
</div>
<input type="submit" class="btn btn-embossed btn-default" id="btnsubmit" name="submit" disabled value="SUBMIT"/>
</form>
in my php i do something like this:
$last_id = insert_getID("reviews", $fields, $val);
$uploaded_files = $_POST['uploaded_files'];
$uploaded_files = explode(',', $uploaded_files);
$uploaded_files = array_filter($uploaded_files);
foreach ($uploaded_files as $file) {
$wherefields = array('img_name', 'users_id');
$upload_value = $file;
$wherevalues = array($upload_value, $_SESSION['uid']);
$where_file = where($wherefields, $wherevalues, "", "");
$caption = $file . "_Caption";
$file_caption = $_POST['\'' . $caption . '\''];
$file_field = array('review_id', 'caption');
$file_value = array($last_id, $file_caption);
update('gallery', $file_field, $file_value, $where_file);
echo "<pre>" + $file_caption + "</pre>";
}
WHen the files where successfully uploaded, textarea will append inside the div #prevCap and that div was also inside the form. I'm getting an error because the form can't get the value of textarea. How can i fix this problem, how can i get textarea value that was appended?

Categories