JqueryUI DateTimePicker buttons stop working after appending html from dialog - javascript

I'm having this issue with my datetimepicker that stops working after appending an html table.
I have a button that opens a dialog. This contains fields to enter and when clicking Save it adds the values as a record to an html table.
That works fine, however, when opening the dialog again, the datetimepicker buttons don't work anymore.
The dialog form has multiple datetimepickers, however, I simplified an example of the issue.
Please see my jsfiddle below for an example.
$(".datepicker").datepicker({
dateFormat: "yy-mm-dd", timeFormat: "HH:mm", hourMin: 0, hourMax: 24, stepMinute: 10
});
var dialog;
dialog = $("#addnewDialog").dialog({
autoOpen: false,
height: 250,
width: 350,
modal: true,
buttons: {
"Save": addnewrec,
Cancel: function () {
dialog.dialog("close");
}
},
open : function() {
},
close: function () {
}
});
$("#AddNew").button().on("click", function () {
dialog.dialog("open");
});
function addnewrec() {
var valid = true;
var dealerref = $('#tblInput').find('#DealerRef').val();
var dtCreated = $('#tblInput').find('#DTCreated').val();
if (valid) {
var td1 = '<td id=DealerRef>' + dealerref + '</td>';
var td2 = '<td id=DTCreated>' + dtCreated + '</td>';
$("#tblStyle tbody").append("<tr><td></td>" +
td1 + td2 + "</tr>");
dialog.dialog("close");
}
return valid;
}
JSFiddle

This is beacause you're genrating in the table td's with the same id as your datepicker id , so it works first time then after appending td into the table , the select on timepicker will throw an error due to duplicate id items
Also know that in an HTML page you should always use ID for one and only one element otherwise use classes .
You can fix this last by generating changine timepicker id or genrate other id's for td's by incrementation for example :
See this Fiddle
Snippet :
$(function () {
$(".datepicker").datepicker({
dateFormat: "yy-mm-dd", timeFormat: "HH:mm", hourMin: 0, hourMax: 24, stepMinute: 10
});
var increment = 0;
var dialog;
dialog = $("#addnewDialog").dialog({
autoOpen: false,
height: 250,
width: 350,
modal: true,
buttons: {
"Save": addnewrec,
Cancel: function () {
dialog.dialog("close");
}
},
open : function() {
},
close: function () {
}
});
$("#AddNew").button().on("click", function () {
dialog.dialog("open");
});
function addnewrec() {
var valid = true;
var dealerref = $('#tblInput').find('#DealerRef').val();
var dtCreated = $('#tblInput').find('#DTCreated').val();
if (valid) {
increment++;
var td1 = '<td id=DealerRef'+increment+'>' + dealerref + '</td>';
var td2 = '<td id=DTCreated'+increment+'>' + dtCreated + '</td>';
$("#tblStyle tbody").append("<tr><td></td>" +
td1 + td2 + "</tr>");
dialog.dialog("close");
}
return valid;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<input id="AddNew" type="button" value="Add New Activity" class="btn btn-default" />
<br /><br />
<div id="addnewDialog" title="Add New Activity">
<table id="tblInput">
<tbody>
<tr>
<td>
DealerRef
</td>
<td>
<input id="DealerRef" name="DealerRef" type="text" value="">
</td>
</tr>
<tr>
<td>
DTCreated
</td>
<td>
<input class="datepicker" id="DTCreated" name="DTCreated" type="text" value="">
</td>
</tr>
</tbody>
</table>
</div>
<table id="tblStyle">
<thead>
<tr>
<th>DealerRef</th>
<th>DTCreated</th>
</tr>
</thead>
<tbody></tbody>
</table>

Related

Get selected drop-down value of a row in html table using JavaScript/jQuery

I have a html table with 4 columns and multiple rows
column1 : simple text
column2 : simple text
column3 : select list with 2 values
column4 : Button that performs some operation
At run time, I want to get the selected / entered values for all the columns of that row against which column4 button is clicked. I know a little of JavaScript/jQuery.
Here is the static table code
<table id="invoiceTbl" border="1">
<thead>
<tr>
<th>Broker info</th>
<th>Receivable Amount</th>
<<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
And I am populating table i.e. inserting data on AJAX call like this:
$.ajax({
type: "POST",
data: $('#searchDetails').serialize(),
async: false,
cache: false,
url: "/opsadmin/search.json",
dataType: 'json',
success: function (result) {
var i = 1;
$.each(result, function (index, value) {
alert(index + ": " + value.brokerInfo);
$('table#invoiceTbl TBODY').append('<tr> <td>' + i + '</td><td>' + value.brokerInfo + '</td><td>' + value.receivableAmount + '</td><td><select name="act" id="s"><option>PENDING</option><option>CLEARED</option></select></td><td><input type="button" value="Process" onclick="updateStatus(\'' + index + '\')"</input></td></tr>');
i++;
});
}
});
return false;
First set the unique ID to each of your "select" with help of index like:
'<select name="act" id="s'+ index +'">'
and pass the index with "updateStatus(index)" function call.
function updateStatus(index) {
$('#s'+index).val(); // value of selected box.
}
$("#invoiceTbl input[type=button]").click(function(e){
$(e.target).closest("tr").find("td").slice(0,2).each(function(){
console.log($(this).text());
});
});
On #button click you will get an array (arr) that holds the values of the clicked row cells:
$('#button').on('click', function() {
var arr = [];
$(this).closest('tr').find('td').each(function() {
var that = $(this);
if (that.find('input[type="text"]').length > 0) {
arr.push(that.find('input[type="text"]').val());
} else if (that.find('select').length > 0) {
arr.push(that.find('select').val());
} else {
arr.push(that.text());
}
});
alert(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>text</td>
<td>text2</td>
<td>
<select>
<option value="opt1">opt1</option>
<option value="opt2">opt2</option>
<option value="opt3">opt3</option>
</select>
</td>
<td><button id="button">Click</button></td>
</tr>
</tbody>
</table>
There's already a few good answers, but my solution is a bit different:
$("#invoiceTbl tr").each(function(){
var select = $(this).find("select");
var button = $(this).find("button");
button.click(function(){
alert(select.val());
});
});
If you also want the content of the other columns, that's a bit more difficult:
$("#invoiceTbl tr").each(function(){
var tr = $(this);
var button = $(this).find("button");
button.click(function(){
tr.find("td").each(function(){
var select = $(this).find("select");
var td_button = $(this).find("button");
if(!td_button.length)
{
if(select.length)
console.log(select.val());
else
console.log($(this).text());
}
});
});
});
Check out https://jsfiddle.net/cgfjewoe/ to see it run.

Running external javascript function from a button clicked that was created dynamically using jquery in Wordpress

I am trying to execute the function that was created separately called uploads.js . This javascript file is a custom image uploader function to be used in Wordpress. I was able to run that javascript file whenever i create a new button just by the of the HTML by sending the needed parameters.
There is a part where i created a dynamic button creation function using jquery, where whenever a 'PLUS' sign button is pressed, that function will trigger and a new button is added. The id of that button is automatically incremented by one.
The problem here is, whenever i click on the button that was created not by using the dynamic button function, it was able to execute the uploads.js function. But the dynamic created buttons are not able to. It seems like the id of the dynamic button was not detected. I even inspect the element of that page, the id that was sent is exactly the same from what I have sent as a parameter to the uploads.js function.
Is there something that i have missed or I have done wrong? Below are the codes:
HTML
<tr class="form-field">
<th scope="row">
<label for="component1"> Component 1</label>
<br></br>
<input type='button' class="button button-large" value='+' id='addButton'>
<input type='button' class="button button-large" value='-' id='removeButton'>
<input type='button' class="button button-large" value='Get TextBox Value' id='getButtonValue'>
</th>
<td>
<div id='TextBoxesGroup'>
<div id="ImageDiv1">
<input id="section2_1" class="button" type="button" value="Upload Image" name="upload_s2_1"/>
</div>
<div id="TextBoxDiv1">
<label>Title #1 : </label>
<input type='text' id='title1' />
</div>
<div id="DescDiv1">
<label>Description #1 : </label>
<input type='text' id='description1' /><br></br>
</div>
</div>
</td>
</tr>
uploads.js
jQuery(document).ready(function($){
function dynamic_image( button , textbox )
{
var custom_uploader;
$(button).click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$(textbox).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
}
dynamic_image('#upload_image_button' , '#upload_image');
dynamic_image('#section2_1' , '#section2_text1');
dynamic_image('#section2_2' , '#section2_text2');
dynamic_image('#section2_3' , '#section2_text3');
dynamic_image('#section2_4' , '#section2_text4');
dynamic_image('#section2_5' , '#section2_text5');
});
script
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 components are allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var newDescDiv = $(document.createElement('div'))
.attr("id", 'DescDiv' + counter);
var newImageDiv = $(document.createElement('div'))
.attr("id", 'ImageDiv' + counter);
newTextBoxDiv.after().html('<label>Title #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="title' + counter + '" value="" >');
newDescDiv.after().html('<label>Description #'+ counter + ' : </label>' +
'<input type="text" name="descbox' + counter +
'" id="desc' + counter + '" value="" ><br></br>');
newImageDiv.after().html('<input class="button" type="button" name="upload_s2_' + counter +
'" value="Upload Image" id="section2_' + counter + '" >');
newImageDiv.appendTo("#TextBoxesGroup");
newTextBoxDiv.appendTo("#TextBoxesGroup");
newDescDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more component to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
$("#DescDiv" + counter).remove();
$("#ImageDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
Other button(like #section2_2, #section2_3 ...) maybe not exist, When function dynamic_image run.
Then below code cannot have meaning.
dynamic_image('#section2_2' , '#section2_text2');
// cannot find #section2_2 , because not yet added
Try this.
// function is called when input.button(like #section2_1, #section2_2 ...) on #TextBoxesGroup clicked
$('#TextBoxesGroup').on('click','input.button',function(e){
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$(textbox).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
})
See example
indicate actually like following
$('#TextBoxesGroup').on('click','input.button',function(e){
var $clickedInput = $(this);// JQuery Object of section2_2
var clickedInputId = $clickedInput.attr('id'); // section2_2
var indicateKey = clickedInputId.substring(10,clickedInputId.length);// 2
var neededTextId = 'section2_text'+indicateKey ; //section2_text2
var $neededText = $("#" +neededTextId ); // JQuery Object of section2_text2
// run logic what you want to do
})

Why can't I make the bootstrap popover work at the table where I want it to work?

I am trying to following the example here and create a popover table row. When I just copy the code it works like a charm. But in the table where I want the popup to work it fails.
I have the following JavaScript code (same as Fiddle):
// Popover
var options = { placement: 'bottom', trigger: 'manual', html: true, title: 'This row' };
function createPopover(element, args) {
var href = $(element).data('popover-url'), txt = $(element).data('popover-content');
var html = '<p>Challenge: Can you click the link in a popover?</p><p><a href="' + href
+ '">' + txt + '</a></p>';
$(element).data('content', html).popover(args);
}
function popoverPlacementBottom() {
createPopover($(this), options);
}
$('.row').each(popoverPlacementBottom);
var insidePopover = false;
function attachEvents(tr) {
$('.popover').on('mouseenter', function () {
insidePopover = true;
});
$('.popover').on('mouseleave', function () {
insidePopover = false;
$(tr).popover('hide');
});
}
$('table').on('mouseenter', 'tr', function () {
var tr = $(this);
setTimeout(function () {
if (!insidePopover) {
$(tr).popover('show');
attachEvents(tr);
}
}, 200);
});
$('table').on('mouseleave', 'tr', function () {
var tr = $(this);
setTimeout(function () {
if (!insidePopover) $(tr).popover('hide');
}, 200);
});
and try to have popovers on this table:
<table class="table table-condensed scrollable popup">
<thead>
<tbody id="logEvents">
<tr class="row" data-popover-url="#url_for_row_1" data-popover-content="line 1" data-
original-title="" title="">
<td class="col-md-1">18:27</td>
<td class="col-md-5">InfoService</td>
<td>Blabla...</td>
</tr>
</tbody>
</table>
This however, does not work. While it does work at the table underneath which looks like this:
<table class="popup">
<tbody>
<tr class="row" data-popover-url="#url_for_row_1" data-popover-content="line 1" data-original- title="" title="">
<td>the first line</td>
</tr>
</tbody>
</table>
Why does it not work at the table where it should work? I hope someone can help me out.
/EDIT Okay I made my own Fiddle HERE.
Strangely enough the code works in the Fiddle. But on my webpage it does not. The only difference with the Fiddle is that the tr rows are dynamically generated everytime an event happens by the function:
return "<tr " + trClass + " data-popover-content='line 1' data-popover-url='#url_for_row_1'>"
+ "<td class='col-md-1'>" + time + "</td>"
+ "<td class='col-md-5'>" + item.Source + "</td>"
+ "<td>" + item.DescriptionShort + "</td>"
// + "<td class='col-md-6'>" + "<a id='pop' data-content='test' data-
toggle='popover'>" + item.DescriptionShort + "</a></td>"
+ "</tr>";
Could this have anything to do with it? (e.g., that the id's and classes come after the document-ready? And that I need to reassign the classes every time a new event happens? And if so, how?
Okay the problem was in the generated code! The <tr>'s were generated everytime an event happened and so I should not assign the popover event only at document ready, but also everytime a new row was created.
I put the popover() function in his own pop namespace, and added the pop.popOver() after the new event made a new row. Looked as follows:
this.addData = function (item) {
var container = $(this.cId);
container.append(this.getEventHtml(item));
pop.popOver();
}
Now the popups show! YEAH! Thanks to Suman Bogati for his help.

generating textbox inside a table using jquery

Suppose this is the prepare table below. and each of 3 row there was a textbox and beside them there where 2 buttons the + or add and - for delete. when i click + in a row, a new textbox will be generated and when i click - the textbox will delete. like the sample below:
Could anyone suggest the snippet for this step or procedure?
Thank you
you could write something on these lines:
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes are allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
</script>
If you do not want to create the div on the fly, you can find the id of your last table row, add 1 to it, create the table row, and then append the textbox creation html to it.
Assuming the html structure is as follows
<table border = "1">
<thead>
<tr><td> Text Boxes </td></tr>
</thead>
<tbody>
<tr><td><button class="add-text-box">+</button><button class="remove-text-box">-</button></td></tr>
<tr><td><button class="add-text-box">+</button><button class="remove-text-box">-</button></td></tr>
<tr><td><button class="add-text-box">+</button><button class="remove-text-box">-</button></td></tr>
</tbody>
​
the following jquery snippet should work
$(".add-text-box").click(function(){
$(this).parent().prepend(" <input class='text-box' /> <br>");
});
$(".remove-text-box").click(function(){
textboxes = $(this).parent().find('.text-box');
$(textboxes).last().remove();
if (textboxes.length === 0) {
$(this).siblings().remove();
$(this).remove();
}
});
​
You can see it in action here

How to include array content in HTML?

I have this code
var users = result.users; // array
$("#dialog:ui-dialog").dialog("destroy");
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
open: function() {
$(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
},
buttons: {
"Okay": function() {
$(this).dialog("close");
},
Cancel: function() {
is_okay = 0;
$(this).dialog("close");
}
}
});
where the array contain data in the form of
{"ss":"Sandra Schlichting","fn":"Full name"}
What I am trying to accomplish is to get the content of the arrays in the form of (white space inserted for readability)
<table>
<tr> <td>Initials</td> <td>Full Name </td> </tr>
<tr> <td>ss </td> <td>Sandra Schlichting</td> </tr>
<tr> <td>fn </td> <td>Full name </td> </tr>
</table>
and have that replaced with <b>New text goes here</b> in
$(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
From what I can tell $.each() should be used for this.
But still I can't quite figure out how to get started.
Can anyone help me out?
You can use a JS for-in to loop through it.
<table id='nameTable'>
<tr> <td>Initials</td> <td>Full Name </td> </tr>
</table>
var names = {
"ss": "Sandra Schlichting",
"fn": "Full name"
};
var $table = $('#nameTable');
var row = '';
for (name in names) {
row += '<tr><td>' + name + '</td><td>' + names[name] + '</td></tr>';
}
$table.append(row)
Here's a fiddle : http://jsfiddle.net/exP2b/4/
function makeTable(users) {
var result = '<table><tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
alert(makeTable({"ss":"Sandra Schlichting","fn":"Full name"}));
Working here
$.each documentation

Categories

Resources