How to get ID dynamic in Jquery? - javascript

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>

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>

why does my script wont append the ul in my class?

i have this script to append new message from client but it wont append to my ul list, don't know why but when i check in console it print 2 object from class chat-message one there is the ul and one not, but from this script it only append to .chat-message class one time and in the html i only have the container class and in the new .chat-message i empty my .message-user class and only add the ul tag to used it later when append new data
here is the html script
<div class="chat-message">
</div>
here is my js script.
function get_message_data(){
$(".client-message").on("click",function(){
$.ajax({
url:"msg",
method:"get",
data:{"data":this.id},
success:function(response){
data_response = JSON.parse(response)
add_data = add_data +
'<div class="header-message" value='+data_response[0].line_name+'>'+
'<div class="image-profile">'+
'<img src='+data_response[0].line_image+' alt="image-message">'+
'</div>'+
'<div class="username-profile">'+
'<label>'+data_response[0].line_name+'</label>'+
'</div>'+
'<button id="btn-exit" onclick="exit_app()">X</button>'+
'</div>'+
'<div class="message-user">'+
'<ul>'+
'</ul>'+
'</div>'+
'<div class="footer-message-send">'+
'<div class="file-send">'+
'<label for="btn-file-input"><i class="fas fa-archive"></i></label>'+
'<button id="btn-file-input" style="display:none;"></button>'+
'<input type="file" id="file-input" style="display: none;">'+
'</div>'+
'<div class="send-message">'+
'<input type="text" name="yellow" class="textinput">'+
'</div>'+
'<div class="button-send">'+
'<label for="send-message-admini"><i class="fa fa-paper-plane" aria-hidden="true"></i></label>'+
'<button id="send-message-admini" style="display:none;" type="button" value="submit"></button>'+
'</div>'+
'</div>'
$(".chat-message").empty();
$(".chat-message").append(add_data);
for(var i = 0; i < data_response.length; i++){
var add_template =
'<li class="message-send-client">'+
'<div class="client-message-send">'+
'<div class="message-header-send">'+
'<img src='+data_response[i].line_image+'>'+
'</div>'+
'<div class="user-message">'+
'<label>'+data_response[i].line_name+'</label>'+
'<p>'+data_response[i].message+'</p>'+
'</div>'+
'</div>'+
'</li>'+
$('.message-user').find('ul').append(add_template)
}
send_admin_message();
var interval = setInterval(function(){
update_message();
},3000)
}
})
id_user = this.id
})
}
here make it like this
see in ul i have added the templatedata
success:function(response){
data_response = JSON.parse(response)
var add_template = '';
for(var i = 0; i < data_response.length; i++){
// here this is creating list
add_template +=
'<li class="message-send-client">'+
'<div class="client-message-send">'+
'<div class="message-header-send">'+
'<img src='+data_response[i].line_image+'>'+
'</div>'+
'<div class="user-message">'+
'<label>'+data_response[i].line_name+'</label>'+
'<p>'+data_response[i].message+'</p>'+
'</div>'+
'</div>'+
'</li>'+
}
add_data = add_data +
'<div class="header-message" value='+data_response[0].line_name+'>'+
'<div class="image-profile">'+
'<img src='+data_response[0].line_image+' alt="image-message">'+
'</div>'+
'<div class="username-profile">'+
'<label>'+data_response[0].line_name+'</label>'+
'</div>'+
'<button id="btn-exit" onclick="exit_app()">X</button>'+
'</div>'+
'<div class="message-user">'+
'<ul>'+add_template+
'</ul>'+
'</div>'+
'<div class="footer-message-send">'+
'<div class="file-send">'+
'<label for="btn-file-input"><i class="fas fa-archive"></i></label>'+
'<button id="btn-file-input" style="display:none;"></button>'+
'<input type="file" id="file-input" style="display: none;">'+
'</div>'+
'<div class="send-message">'+
'<input type="text" name="yellow" class="textinput">'+
'</div>'+
'<div class="button-send">'+
'<label for="send-message-admini"><i class="fa fa-paper-plane" aria-hidden="true"></i></label>'+
'<button id="send-message-admini" style="display:none;" type="button" value="submit"></button>'+
'</div>'+
'</div>'
$(".chat-message").empty();
$(".chat-message").append(add_data);
}

dynamically generate a list dropdown in javascript from JSON data

I have generated a form and storing it into a JS variable but the problem is I want to generate a dropdown list. Data for that dropdown is present in an array into JSON. I tried to concat values using a for loop but that didn't work
function(resp){
resp = JSON.parse(resp);
console.log(resp);
let dispData = '<form>'+
'<div class="form-group">'+
'<label>Item</label>'+
'<input type="text" class="form-control reas-item" id="'+resp["item_details"].master_id+'" value="'+resp["item_details"].item_name+'" disabled>'+
'</div>'+
'<div class="form-group">'+
'<label>Date</label>'+
'<input type="date" class="form-control reas-date">'+
'</div>'+
'<div class="form-group">'+
'<label>Quantity</label>'+
'<input type="number" class="form-control reas-quantity" min="1" max="'+resp["item_details"].quantity+'" value="'+resp["item_details"].quantity+'" >'+
'</div>'+
'<div class="form-group">'+
'<label>Reassign To:</label>'+
'<select class="form-control reas-staff">'
for (var i = 0; i < resp['trachers_list'].length; i++) {
var staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name
+'<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>'
}
'</select>'+
'</div>'+
'</form>';
/*for (var i = 0; i < resp['trachers_list'].length; i++) {
let staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name
$(".reas-staff").html('<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>');
}*/
}
See Commented for loop I've tried that as well but that is also not working.
This is how my json looks like
Please do code like below:
function(resp){
resp = JSON.parse(resp);
console.log(resp);
let dispData = '<form>'+
'<div class="form-group">'+
'<label>Item</label>'+
'<input type="text" class="form-control reas-item" id="'+resp["item_details"].master_id+'" value="'+resp["item_details"].item_name+'" disabled>'+
'</div>'+
'<div class="form-group">'+
'<label>Date</label>'+
'<input type="date" class="form-control reas-date">'+
'</div>'+
'<div class="form-group">'+
'<label>Quantity</label>'+
'<input type="number" class="form-control reas-quantity" min="1" max="'+resp["item_details"].quantity+'" value="'+resp["item_details"].quantity+'" >'+
'</div>'+
'<div class="form-group">'+
'<label>Reassign To:</label>'+
'<select class="form-control reas-staff">';
for (var i = 0; i < resp['trachers_list'].length; i++) {
var staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name;
dispData += '<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>';
}
dispData += '</select>'+
'</div>'+
'</form>';
/*for (var i = 0; i < resp['trachers_list'].length; i++) {
let staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name
$(".reas-staff").html('<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>');
}*/
}

Remove DIV dynamically with JQuery

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>

Escaping Quotes does not work in JavaScript innerHTML

I have got a quite bad "quoting situation" at the moment.
I am working inside an innerHTML and inside this i want to call a function on the onClick-Event, which leaves me with the following:
modalEl.innerHTML = '<form>'+
'<legend>Gruppe bearbeiten</legend>'+
'<div class="mui-textfield">'+
'<input id="groupName" type="text" value="'+name+'">'+
'<label>Gruppenname</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<textarea id="groupDesc" placeholder="">'+desc+'</textarea>'+
'<label>Beschreibung</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<label>Geräte hinzufügen</label>'+
'<select id="devicetable" data-placeholder="ID und/oder Namen eingeben" class="chosen-select" multiple style="width:350px;" tabindex="4">'+
'<option value="0"></option>'+
'</select>'+
'</div>'+
'<br>'+
'<div class="outterformbuttons">'+
'<div class="formbuttons">'+
'<button type="button" class="mui-btn mui-btn--raised" onclick="sendUpdatedGroup(id, document.getElementById("groupName").value, document.getElementById("groupDesc").value)">Speichern</button>'+
'<button type="button" class="mui-btn mui-btn--raised" onclick="deactivateOverlay()">Abbrechen</button>'+
'</div>'+
'</div>'+
'</form>';
I already tried escaping the quotes and using HTML-Quotes, but neither worked.
Instead of HTML encoding the single quotes, just JavaString escape your single quotes.
'<button type="button" class="mui-btn mui-btn--raised"
onclick="sendUpdatedGroup(id, document.getElementById(\'groupName\').value,
document.getElementById(\'groupDesc\').value)">Speichern</button>'+
If you don't want to get into escaping hell , don't use event handlers as HTML attributes (which we stopped doing about 10 years ago).
modalEl.innerHTML = '<form>'+
'<legend>Gruppe bearbeiten</legend>'+
'<div class="mui-textfield">'+
'<input id="groupName" type="text" value="'+name+'">'+
'<label>Gruppenname</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<textarea id="groupDesc" placeholder="">'+desc+'</textarea>'+
'<label>Beschreibung</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<label>Geräte hinzufügen</label>'+
'<select id="devicetable" data-placeholder="ID und/oder Namen eingeben" class="chosen-select" multiple style="width:350px;" tabindex="4">'+
'<option value="0"></option>'+
'</select>'+
'</div>'+
'<br>'+
'<div class="outterformbuttons">'+
'<div class="formbuttons">'+
'<button type="button" class="mui-btn mui-btn--raised" >Speichern</button>'+
'<button type="button" class="mui-btn mui-btn--raised">Abbrechen</button>'+
'</div>'+
'</div>'+
'</form>';
var buttons = modalEl.querySelectorAll('.formbuttons button');
buttons[0].addEventListener('click', function() {
sendUpdatedGroup(id,
document.getElementById('groupName').value,
document.getElementById('groupDesc').value))
});
buttons[i].addEventListener('click', deactivateOverlay);
You forgot to declare desc and name look at this fiddle totally works https://jsfiddle.net/L3Lfweh9/
HTML
<div id="message">
</div>
<button id="bttn">
click here
</button>
JS
var name = "one";
var desc = "two";
var text = '<form>'+
'<legend>Gruppe bearbeiten</legend>'+
'<div class="mui-textfield">'+
'<input id="groupName" type="text" value="'+name+'">'+
'<label>Gruppenname</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<textarea id="groupDesc" placeholder="">'+desc+'</textarea>'+
'<label>Beschreibung</label>'+
'</div>'+
'<br/>'+
'<div class="mui-textfield">'+
'<label>Geräte hinzufügen</label>'+
'<select id="devicetable" data-placeholder="ID und/oder Namen eingeben" class="chosen-select" multiple style="width:350px;" tabindex="4">'+
'<option value="0"></option>'+
'</select>'+
'</div>'+
'<br>'+
'<div class="outterformbuttons">'+
'<div class="formbuttons">'+
'<button type="button" class="mui-btn mui-btn--raised" onclick="sendUpdatedGroup(id, document.getElementById("groupName").value, document.getElementById("groupDesc").value)">Speichern</button>'+
'<button type="button" class="mui-btn mui-btn--raised" onclick="deactivateOverlay()">Abbrechen</button>'+
'</div>'+
'</div>'+
'</form>';
document.getElementById("bttn").addEventListener("click", function(){
document.getElementById("message").innerHTML = text;
}, false);

Categories