Ok, I have this HTML:
<td class="text-left"><button type="button" onclick="addImage('<?php echo $language['language_id']; ?>');" data-toggle="tooltip" title="<?php echo $button_banner_add; ?>" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button></td>
On click I call JS function addImage.
<script type="text/javascript">
function addImage(language_id) {
html = '<td class="text-left"><div class="row"><div class="col-sm-6"><div class="form-group"><label class="col-sm-2 control-label" for="date-ended"><?php echo 'Date Started' ?></label><div class="input-group date" id="datetimepicker1"><input name="background_images_date_ended" type="text" id="date-ended" class="form-control" /><span class="input-group-addon"><i class="fa fa-calendar"></i></span></div></div></div></div></td>';
$('#images' + language_id + ' tbody').append(html);
</script>
After that I want to call function on this div <div class="input-group date" id="datetimepicker1">
This function:
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker();
});
</script>
But this div is dynamically added and I don't know, but the function is not running.
Why you just dont init the datetimepicker at the bottom of the addImage function, or call another function from there?
function addImage(language_id) {
html = ' <td class="text-left"><div class="row"><div class="col-sm-6"><div class="form-group"><label class="col-sm-2 control-label" for="date-ended"><?php echo 'Date Started' ?></label><div class="input-group date" id="datetimepicker1"><input name="background_images_date_ended" type="text" id="date-ended" class="form-control" /><span class="input-group-addon"><i class="fa fa-calendar"></i></span></div></div></div></div></td>';
$('#images' + language_id + ' tbody').append(html);
$('#datetimepicker1').datetimepicker();
}
or
function addImage(language_id) {
....
initDatepicker();
}
function initDatepicker () {
$('#datetimepicker1').datetimepicker();
}
For elements dynamically added, you must use event handlers like this:
someElement.addEventListener( "click", function() {
//some code to run on click
});
This should work for you then
Related
So I'm developing a website for a medical clinic and they asked me to add a button beneath every doctor to make an appointment.
this is what i have for the doctors section
for (var i = 0; i < 3; i++) {
$('#get_medicos').append(
'<div class="col-md-3 dummy">' +
'<div class="text-box">' +
'<img src="assets/images/corpo-clinico/' + medico[i].ficheiro + '" alt="" class="img-responsive"/>' +
'<div class="clearfix"></div>' +
'<div class="text-box white padding-3">' +
'<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
'<p>' + medico[i].especialidade + '</p>' +
'<a id="marcar" type="button" class="btn btn-primary">Marcar consulta</a>' +
'</div>' +
'</div>' +
'</div>'
);
}
The then code for the click function (that doesn't work):
$('#marcar').click(function() {
var offset = $('#marcacao').offset();
$('html, body').animate({
scrollTop: offset.top-100,
scrollLeft: offset.left
}, 1000);
$('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(medico[i].especialidade);
$('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(medico[i].nome);
console.log('test');
});
This is all inside a $(document).ready(function() {}); and what should do is when i click that button beneath the doctor, should go up to the form and fill the doctor's name and specialty... but it seems it's not working for some reason... this is a copy of other click functions in the code, but they seem to work fine.
HTML form:
<div id="marcacao-consulta" data-target="#marcacao-consulta">
<div class="row">
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="section">
<label class="field select prepend-icon">
<select id="especialidade-marcacao" class="gui-input">
<option id="especialiade-default" value="default">Escolha a especialidade</option>
<?
$query = $dbHandle->prepare("
SELECT `especialidade`
FROM `especialidade`
ORDER BY `especialidade` ASC
");
$query->execute();
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?=$row["especialidade"]; ?>"><?=$row["especialidade"]; ?></option>
<? }
} else { ?>
<option value="">Nenhum resultado</option>
<? }
?>
</select>
<span class="field-icon"><i class="fas fa-heartbeat"></i></span>
</label>
</div>
</div>
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="section">
<label class="field select prepend-icon">
<select id="corpo-clinico-marcacao" class="gui-input">
<option id="corpo-clinico-default" value="default">Escolha o médico</option>
<?
$query = $dbHandle->prepare("
SELECT `nome`
FROM `medico`
ORDER BY `nome` ASC
");
$query->execute();
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?=$row["nome"]; ?>"><?=$row["nome"]; ?></option>
<? }
} else { ?>
<option value="">Nenhum resultado</option>
<? }
?>
</select>
<span class="field-icon"><i class="fas fa-user-md"></i></span>
</label>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12">
<div class="section">
<label class="field prepend-icon">
<input id="nome" class="gui-input" type="text" placeholder="Nome Completo">
<span class="field-icon"><i class="fas fa-user"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="email" class="gui-input" type="text" placeholder="Endereço de correio eletrónico">
<span class="field-icon"><i class="fas fa-envelope"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="telefone" class="gui-input" type="text" placeholder="Telefone/Télemovel">
<span class="field-icon"><i class="fas fa-phone-square"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="tipo" class="gui-input" type="text" value="consulta" disabled>
</label>
</div>
</div>
</div>
</div>
You have to add the element and register the event for the element. Here is the fiddle which works for you
https://jsfiddle.net/0q3kpyfv/
Your sample HTML
<div id="get_medicos">
</div>
Sample jquery code
Notice I have added the data-val attribute to the added anchor tag which will help you to get the information and perform the logic based on which button is clicked. you can pass dynamic data to data-val attribute and use it in click event.
$(document).ready(function() {
var sampleString = "";
var medico = [{'especialidade':'speciality 0','nome':'Doctor 0'},{'especialidade':'speciality 1','nome':'Doctor 1'},{'especialidade':'speciality 2','nome':'Doctor 2'}]
for (var i = 0; i < 3; i++) {
var doctorData = medico[i];
$('#get_medicos').append(
'<div class="col-md-3 dummy">' +
'<div class="text-box">' +
'<img src="assets/images/corpo-clinico/' + medico[i].especialidade + '" alt="" class="img-responsive"/>' +
'<div class="clearfix"></div>' +
'<div class="text-box white padding-3">' +
'<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
'<p>' + medico[i].especialidade + '</p>' +
'<a id="marcar" data-doctor-especialiadade="'+medico[i].especialidade+'" data-doctor-nome="'+medico[i].nome+'" type="button" class="btn btn-primary">Marcar consulta'+i+'</a>' +
'</div>' +
'</div>' +
'</div>'
);
};
$('#get_medicos').on('click','a',function(event){
var elementClicked = event.target;
var doctorEspecialiadade = $(elementClicked).data('doctor-especialiadade');
var doctorName = $(elementClicked).data('doctor-nome');
$('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(doctorEspecialiadade);
$('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(doctorName);
})
});
if you create the button after your event, you could have problem so, use the delegate version of click:
$('div').on('click', 'a', (function()....
and better put an id on the ancestor div:
'<div class="text-box white padding-3" id="mydiv"'
:
$('#mydiv').on('click', 'a', (function()....
another thing, with the loop you will have same id more time in your html??its no good.
so you'll have to rebuild your program logic...and bind the event with the right button (use a common class) it will be better than an id
If you bind the event to the parent element, and filter by the children, you can listen to any new elements that are added, doesn't matter how many.
<div class="container"></div>
<button class="js-add-new">Add new</button>
const $addNew = $('.js-add-new')
const $container = $('.container')
let count = 0
$addNew.on("click", () => {
count += 1
$container.append(`
<div>
<button>log me ${count}</button>
</div>
`)
})
$container.on("click", "button", (event) => {
console.log(event.currentTarget)
})
A working example: https://codepen.io/alexmccabe/pen/jOrXZxj?editors=1111
The button click is working. Here is a fiddle showing it does:
https://jsfiddle.net/bradberkobien/qL4m10y6/3/
There must be an issue with the code that comes before the console.log("test") line within the click. I would use the debugger to help you with that.
i have a form with two buttons, two datepickers and one hidden input. if the oneway button is clicked the return datepicker becomes hidden and the value of the input is changed to oneway. clicking the return button reverts the process and and the value of the input is changed to return.
<script>
$(document).ready(function() {
$("label[name='oneway']").on("click", function(){
sessionStorage.setItem("btnActive", "oneway");
$(".returnpicker").hide();
$("label[name='return']").removeClass('active');
$(this).addClass('active');
document.getElementById('hiddeninput').value = "oneway";
});
$("label[name='return']").on("click", function(){
sessionStorage.setItem("btnActive", "return");
$(".returnpicker").show();
$("label[name='oneway']").removeClass('active');
$(this).addClass('active');
document.getElementById('hiddeninput').value = "return";
});
let sessionState = sessionStorage.getItem("btnActive");
if( sessionState == "oneway") {
$(".returnpicker").hide();
$("label[name='return']").removeClass('active');
$(this).addClass('active');
document.getElementById('hiddeninput').value = "oneway";
} else {
sessionStorage.setItem("btnActive", "return");
$(".returnpicker").show();
$("label[name='oneway']").removeClass('active');
$(this).addClass('active');
document.getElementById('hiddeninput').value = "return";
}
});
</script>
My html looks like this
<form method="post" action="">
<input type="hidden" id="hiddeninput" name="hiddeninput">
<div class="form-row">
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label for="oneway" class="btn btn-default " name="oneway">One way</label>
<label for="return" class="btn btn-default " name="return">Return</label>
</div>
<div class="form-group col-lg-3 departure">
<label for="OnewayDatepicker">Departure Date</label>
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input id="date_added" type="text" name="OnewayDatepicker"class="form-control" value="<?php echo isset($_POST['OnewayDatepicker']) ? $_POST['OnewayDatepicker'] : '' ?>">
</div>
<div class="mb-3">
<?php if (isset($OnewayDatepicker_err )) echo '<p class="text-danger"><small>' . $OnewayDatepicker_err . ' </small></p>'; ?>
</div>
</div>
<div class="form-group col-lg-3 arrival">
<label for="ReturnDatepicker">Arrival Date</label>
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input id="date_modified" type="text" name="RetunDatepicker"class="form-control" value="<?php echo isset($_POST['RetunDatepicker']) ? $_POST['RetunDatepicker'] : '' ?>">
</div>
<div class="mb-3">
<?php if (isset($ReturnDatepicker_err )) echo '<p class="text-danger"><small>' . $ReturnDatepicker_err . ' </small></p>'; ?>
</div>
</div>
</div>
<div>
<button type="submit" name="confirm" class="btn btn-primary btn-lg " id="confirm">Confirm</button>
</div>
</form>
And my php
<?php
$OnewayDatepicker_err = "";
$RetunDatepicker_err = "";
$OnewayDatepicker = $_POST['OnewayDatepicker'];
$RetunDatepicker = $_POST['RetunDatepicker'];
$hiddeninput = $_POST['hiddeninput'];
if (isset($_POST["confirm"])) {
if (empty($OnewayDatepicker)) {
$OnewayDatepicker_err = " * Choose Departure Date";
} else {
$OnewayDatepicker_err = "";
}
if ((empty($RetunDatepicker)) && ($hiddeninput == "return")) {
$RetunDatepicker_err = " * Choose Return Date";
} else {
$RetunDatepicker_err = "";
}
}
?>
Everything works fine except this part of the code "&& ($hiddeninput = "return")".
it seems php doesn't recognize the value the JS has passed into the hidden input or am i doing something wrong?
I am trying to get .sortable from jQuery UI to work but it is only working for my first item, when I dynamically add new ones, it stops working.
I found this: http://api.jqueryui.com/sortable/#method-refresh which should refresh everything and recognize new items, but when I use that I get the error:
Uncaught Error: cannot call methods on sortable prior to initialization; attempted to call method 'refresh'
What can I do?
My code:
// HTML template for new fields
const template = `<div class="row sortwrap">
<div class="col-md-8">
<input type="text" name="category[]" placeholder="" class="form-control name_list catinput" />
<i class="mdi mdi-sort dragndrop"></i>
<div class="questionlist">
<div class="row">
<div class="col-md-8">
<input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
<button class="btn btn-success questionbutton">Extra vraag</button>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<button id="addcategory" class="btn btn-danger btn_remove">X</button>
</div>
</div>`;
const vraagTemplate = `<div class="row">
<div class="col-md-8">
<input type="text" name="question[]" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
<button class="btn btn-danger btn_remove">X</button>
</div>
</div>`;
$('.sortwrap').sortable();
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
// Sortable code
$('.sortwrap').sortable("refresh");
$('#dynamic_field input[name^=cat]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
});
$('#dynamic_field .sortwrap').each(function(i) {
$(this).attr("id", i + 1);
});
$('#dynamic_field .questionlist').each(function() {
$(this).find('input[name^=qu]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
});
});
}
// Append category template
$('#addcategory').click(function() {
$('#dynamic_field').append($(template));
updatePlaceholders();
});
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
$ql = $(this).closest('.questionlist');
$ql.append($(vraagTemplate));
updatePlaceholders();
});
// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
$(this).closest('.row').remove();
updatePlaceholders();
});
If I remove the line that says refresh in my function and only have the one .sortable in my code then I can drag all items even new ones but nothing is dropping. So I can drag but not sort/drop.
I think this is on where you attach your sort. I used a wrapper here to do so.
Note I turned off the refresh due to where I attached it as it seems to not need that given that attachment point.
// HTML template for new fields
const template = '<div class="row sortwrap"> <div class="col-md-8"> <input type="text" name="category[]" placeholder="" class="form-control name_list catinput" /> <i class="mdi mdi-sort dragndrop"></i> <div class="questionlist"> <div class="row"> <div class="col-md-8"> <input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" /> </div> <div class="col-md-4"> <button class="btn btn-success questionbutton">Extra vraag</button> </div> </div> </div> </div> <div class="col-md-4"> <button id="addcategory" class="btn btn-danger btn_remove">X</button> </div> </div>';
const vraagTemplate = '<div class="row"> <div class="col-md-8"> <input type="text" name="question[]" class="form-control name_list questioninput" /> </div> <div class="col-md-4"> <button class="btn btn-danger btn_remove">X</button> </div> </div>';
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
// Sortable code
// $('#dynamic_field').sortable( "refresh" );
let df = $('#dynamic_field');
df.find('input[name^=cat]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
});
df.find('.sortwrap').each(function(i) {
$(this).attr("id", i + 1);
});
df.find('.questionlist').each(function() {
$(this).find('input[name^=qu]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
});
});
}
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
let $ql = $(this).closest('.questionlist');
$ql.append($(vraagTemplate));
updatePlaceholders();
});
// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
$(this).closest('.row').remove();
updatePlaceholders();
});
$('#addcategory').on('click', function() {
let t = $(template)
$('#dynamic_field').append(t);
updatePlaceholders();
});
$(function() {
$('#addcategory').trigger('click');
$('#dynamic_field').sortable();
});
.sortwrap{border: solid green 1px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div>
<button id="addcategory">add</button>
</div>
<div id="dynamic_field"></div>
As mentioned above this will work fine
This looks promising:
http://api.jqueryui.com/sortable/#method-refresh
it seems to imply that you can just add an item to a sortable, then call
$('#mysortable').sortable('refresh')
to recognize it.
var counter = 1;
function appendThing() {
$("<li id='Text" + counter + "' class='ui-state-default'>Text" + counter + "</li>").appendTo($("#mySortable"));
$("#mySortable").sortable({ refresh: mySortable })
counter++;
};
please take a look into this
https://jsfiddle.net/6ztrdg9n/
I've been coding for years, but only in recent months I started looking into JavaScript/jQuery/Ajax. I have searched for days, but none of the answers I see match what I'm trying to do (as far as I can see).
I have a select that gets a list of agendas from the controller. After an agenda is selected, an Ajax call is triggered to get related subjects from the database, and add it as radio inputs to a predefined div. There is already a radio button group for "time assignment per group", where, depending on your selected option, the right set of input fields is displayed.
This works fine for adding the info, but now I want to edit existing records on this same page. So now I want to select an agenda, get the subjects, have the system check if there are already time assignments for the subject I select. If there are, display the correct fields with the data preloaded. If not, treat it like an Add form.
My select works as expected, the Ajax call also creates the needed radio buttons, but how do I access those newly created radio buttons, to start a new Ajax call on that element, to check if there are already assignments?
SELECT
<form accept-charset="UTF-8" class="form-horizontal">
{{ csrf_field() }}
<div class="form-group">
<label for="agenda" class="col-sm-3 control-label">Agenda</label>
<div class="col-sm-6">
<select class="form-control" id="agenda" name="agenda">
<option value="">Selecteer een agenda</option>
#foreach($agendas as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
</div>
</form>
<form method="POST" action="{{ action('TimeController#store') }}" accept-charset="UTF-8" class="form-horizontal">
{{ csrf_field() }}
<div class="form-group"><div id="insertSubjects"></div></div>
<div class="form-group">
<label for="all_type" class="col-sm-3 control-label">Allocatie type</label>
<div class="col-sm-6">
<input type="radio" name="type" id="user" value="1"> User<br>
<input type="radio" name="type" id="fraction" value="2"> Fractie<br>
<input type="radio" name="type" id="oppcoa" value="3"> Oppositie/Coalitie
</div>
</div>
<div id="insertFields"></div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<input class="btn btn-default" type="submit" value="Voeg toe">
</div>
</div>
</form>
JAVASCRIPT
<script type="text/javascript">
$(document).ready(function() {
$('#agenda').on('change', function() {
var agenda = $('#agenda option:selected').attr('value');
var my_url = window.location.pathname + '/agenda/' + agenda;
$.ajax({
type: "post",
url: my_url,
headers: {'X-CSRF-TOKEN': $('input[name=_token]').val()},
dataType: 'json',
context: this,
success: function (data) {
var fields = '<label for="subject" class="col-sm-3 control-label">Selecteer onderwerp</label>' +
'<div class="col-sm-6">';
jQuery.each(data, function (k, v) {
fields += '<input type="radio" name="subject" value="' + v.id + '" class="subject_radio"> ' + v.subject + '<br>';
});
fields += '</div>';
$('#insertSubjects').html(fields);
$('input:radio[name=subject]:first').attr('checked', true);
}
})
});
$('input[type=radio][name=type]').change(function() {
var fields;
if (this.id == 'user') {
fields = '<div class="form-group"><label for="per_user" class="col-sm-3 control-label">Per lid</label><div class="col-sm-6"><input type="text" name="per_user" id="per_user" /></div></div>';
}
else if (this.id == 'fraction') {
fields = '<div class="form-group"><label for="NDP" class="col-sm-3 control-label">NDP</label><div class="col-sm-6"><input type="text" name="NDP" id="NDP" /></div></div>' +
'<div class="form-group"><label for="VHP" class="col-sm-3 control-label">VHP</label><div class="col-sm-6"><input type="text" name="VHP" id="VHP" /></div></div>' +
'<div class="form-group"><label for="ABOP" class="col-sm-3 control-label">ABOP</label><div class="col-sm-6"><input type="text" name="ABOP" id="ABOP" /></div></div>' +
'<div class="form-group"><label for="PL" class="col-sm-3 control-label">PL</label><div class="col-sm-6"><input type="text" name="PL" id="PL" /></div></div>' +
'<div class="form-group"><label for="BEP" class="col-sm-3 control-label">BEP</label><div class="col-sm-6"><input type="text" name="BEP" id="BEP" /></div></div>' +
'<div class="form-group"><label for="NPS" class="col-sm-3 control-label">NPS</label><div class="col-sm-6"><input type="text" name="NPS" id="NPS" /></div></div>' +
'<div class="form-group"><label for="PALU" class="col-sm-3 control-label">PALU</label><div class="col-sm-6"><input type="text" name="PALU" id="PALU" /></div></div>' +
'<div class="form-group"><label for="DOE" class="col-sm-3 control-label">DOE</label><div class="col-sm-6"><input type="text" name="DOE" id="DOE" /></div></div>' +
'<div class="form-group"><label for="Onbekend" class="col-sm-3 control-label">Onbekend</label><div class="col-sm-6"><input type="text" name="Onbekend" id="Onbekend" /></div></div>';
}
else if (this.id == 'oppcoa') {
fields = '<div class="form-group"><label for="Coalitie" class="col-sm-3 control-label">Coalitie</label><div class="col-sm-6"><input type="text" name="Coalitie" id="Coalitie" /></div></div>' +
'<div class="form-group"><label for="Oppositie" class="col-sm-3 control-label">Oppositie</label><div class="col-sm-6"><input type="text" name="Oppositie" id="Oppositie" /></div></div>' +
'<div class="form-group"><label for="Neutraal" class="col-sm-3 control-label">Neutraal</label><div class="col-sm-6"><input type="text" name="Neutraal" id="Neutraal" /></div></div>';
}
$('#insertFields').html(fields);
});
});
</script>
All the Ajax requests just return JSON encoded data from the database, but if you guys need to see those calls too, let me know. Please guide me in the right direction...
You can create array which will hold the newly created radios buttons.
var newRdoBtnsArr = []; // Array to hold the newly created new radio buttons
$.ajax({
.
.
.
.
success: function (data) {
var newRdoBtn = '<input type="radio" name="subject" value="' + v.id + '" class="subject_radio"> ';
newRdoBtnsArr.push( $( newRdoBtn ) ); // Push the radio button as jQuery object
fields += newRdoBtn + v.subject + '<br>';
.
.
.
.
});
Update after the comment:
I guess you need to execute a AJAX call when there is a change in newly created radio buttons. In that case you can add below lines and try. Like you did for $('input[type=radio][name=type]').change(function() {
$( 'body' ).on( 'change', 'input:radio[name=subject]', function() {
console.log("It works");
} );
I wanted to write a code that would allow me to create the inputs such as subject, date of purchase and asset value, the input box has the attribute 'class = "datepicker"' and at first everything works properly read, but when I call the works to append to add other input (same as above) within the pages, "datepicker" no longer gives any sign of life.
I show you the code:
<div class="well bs-component" ><fieldset><div id="elencoBeni">
<div class="input-group">
<span class="input-group-addon">Oggetto</span>
<g:textField class="form-control" placeholder="Oggetto" name="oggetto" id="oggetto" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar" ></span></span>
<g:textField class="form-control datepicker" placeholder="Data acquisto" name="dataAcquisto" id="dataAcquisto" />
<span class="input-group-addon">Valore</span>
<g:textField class="form-control" placeholder="Valore" name="valoreBene" id="valoreBene"/><br/>
</div><br/>
</div>
<label class="btn btn-success" id="aggiungiOggetto" name="aggiungiOggetto" >+</label>
</fieldset></div>
jquery Function:
<g:javascript>
$(document).ready(function(){
$('.datepicker').datepicker({
language: 'it'
}); var i = 0;
$("#aggiungiOggetto").click(function(){
$("#elencoBeni").append('<div class="input-group"><span class="input-group-addon">Oggetto</span><input type="text" class="form-control" placeholder="Oggetto" name="oggetto'+i+'" id="oggetto'+i+'"/><span class="input-group-addon"><span class="glyphicon glyphicon-calendar" ></span></span><input type="text" class="datepicker form-control" placeholder="Data acquisto" name="dataAcquisto'+i+'" id="dataAcquisto'+i+'"/><span class="input-group-addon">Valore</span><input type="text" class="form-control" placeholder="Valore" name="valoreBene'+i+'" id="valoreBene'+i+'"/><br/></div><br/>');
i++
}); </g:javascript>
Since the input is dynamically added to dom, you need to initialize datepicker for the element after added to dom.
$(document).ready(function() {
$('.datepicker').datepicker({
language: 'it'
});
var i = 0;
$("#aggiungiOggetto").click(function() {
$("#elencoBeni").append('<div class="input-group"><span class="input-group-addon">Oggetto</span><input type="text" class="form-control" placeholder="Oggetto" name="oggetto' + i + '" id="oggetto' + i + '"/><span class="input-group-addon"><span class="glyphicon glyphicon-calendar" ></span></span><input type="text" class="datepicker form-control" placeholder="Data acquisto" name="dataAcquisto' + i + '" id="dataAcquisto' + i + '"/><span class="input-group-addon">Valore</span><input type="text" class="form-control" placeholder="Valore" name="valoreBene' + i + '" id="valoreBene' + i + '"/><br/></div><br/>');
// initialize datepicker again, which includes the dynamically added element
$('.datepicker').datepicker({
language: 'it'
});
i++
});
});
Because new elements don't have .datepicker() binded.
instead of:
$('.datepicker').datepicker({
language: 'it'
});
use:
$('body').on('focus',".datepicker", function(){
$(this).datepicker({
language: 'it'
});
});