Jquery/Javascript: How can I get ClientID for dynamically generated controls - javascript

How can I get the client ID for dynamically created controls using javascript/jquery.
I have a datepicker and if value change it should trigger a textchanged event and do some functionality. Below is my script
function BindControlEvents() {
$(".datepicker").datepicker({
format: 'mm/dd/yyyy',
autoclose: true,
todayBtn: 'linked'
}).on('changeDate', function (ev) {
__doPostBack('MainContent_dteFr1002', '');
}).on('clearDate', function (ev) {
//to do
});
}
//Initial bind
$(document).ready(function () {
BindControlEvents();
});
//Re-bind for callbacks
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
BindControlEvents();
});
Code-Behind for Dynamically generated textbox Datepicker
protected void Page_Init(object sender, EventArgs e)
{
LoadControls(reportDefId);
}
protected void LoadControls(int reportDefId)
{
HtmlTableCell cellDate = new HtmlTableCell();
TextBox dte = new TextBox();
dte.ToolTip = "If you need to filter for blank dates, please select date range 1/1/1753-1/1/1753";
dte.Attributes.Add("type", "text");
dte.Attributes.Add("class", "datepicker");
if (rfl.fieldDisplayName.Contains("Start") || rfl.fieldDisplayName.Contains("End"))
dte.ID = "dte" + id.ToString();
else
dte.ID = "dteFr" + id.ToString();
dte.Style["Width"] = "85px";
dte.Style["Height"] = "24px";
dte.TextChanged += new EventHandler(dte_TextChanged);
cellDate.Controls.Add(dte);
}
For testing, I have hard coded of ClientID 'MainContent_dteFr1002' to see if it fires textchnaged event. It does. So I need to pass cliendid value dynamically which ever cliendID contains dte.
I have searched but I didn't find appropriate answer.
Please help!
Thanks

You can store the ClientID for each control for later use somewhere.
List<string> dynamicID = new List<string>();
dynamicID.Add(dte.ClientID);
Or give your controls self made ID and set the ClientID Mode to static so they will not be renamed by aspnet into MainContent_ID_5
dte.ID = "ID_" + index;
dte.ClientIDMode = ClientIDMode.Static;
Or navigate down the control path and find the correct ID, in this example the TextBox is added to PlaceHolder1 as the first control.
<%= PlaceHolder1.Controls[0].ClientID %>

The on change function should automatically have the reference to the dynamic control that triggered it.
alert(ev.target.id);
is one way, you should see the id.
$(this).attr("id");
or
this.id
should also contain the dynamic id's respectively. If your definition of CliendID means something else besides the control that is triggered in the event then you should specify what it is and how it's uniquely tied to this on change event.

lets assume that you have the button in a container.
<div class='ButtonContainer'>
<button value="textChanges" id="MainContent_dteFr1002" />
</div>
<input type="text" class='datepicker' value='2017-05-01' />
then you event could look like this
$(".datepicker").datepicker({
format: 'mm/dd/yyyy',
autoclose: true,
todayBtn: 'linked'
}).on('changeDate', function (ev) {
$(".ButtonContainer").find("button").click();
}).on('clearDate', function (ev) {
//to do
});
//OR text changed on the same controller
$(".datepicker").datepicker({
format: 'mm/dd/yyyy',
autoclose: true,
todayBtn: 'linked'
}).on('changeDate', function (ev) {
// (this) is the changes textbox
var id = $(this).attr("id");
__doPostBack(id, '');
}).on('clearDate', function (ev) {
//to do
});

Related

Materialize CSS on chip delete

I have been trying to get the tag of a deleted chip from the div in the Materialize chips class, but nothing is working.
Here is what I have already tried.
$('.chips').on('chip.delete', function(e, chip){
console.log(chip);
console.log(e);
console.log(chip.tag);
});
None of the above is working.
With just only console.log(chip), I get undefined error in JavaScript console, but the function is firing when I delete the chip. I am just not able to get the value of tag of deleted chip. I want to store the tag in a variable.
I am creating chips dynamically on Materialize date select:
$('#pm_date').change(function () {
var chipvalue = $(this).val();
if (chipvalue !== "") {
// checking if tag already exits
if ($("#date_chip_select:contains(" + chipvalue + ")").length > 0) {
alert('Date already selected');
} else {
var appendstring = "<div class='chip' id='date_chip_child_" + chip_id + "'>" + chipvalue + "<i class='material-icons close'>close</i></div>";
}
}
});
Here is the fiddle: https://jsfiddle.net/hq22mne4/1/
chips.js, which is part of materialize, doesn't seem to expose any methods for adding or removing chips programmatically. It seems to exclusively listen for an enter keydown event and then internally add the chip.
So, I stitched together a workaround that does just that. I set potential chip's value within your onchange event:
$("#datechips").find('input').val($(this).val());
And create the chip when date picker is closed:
$('.datepicker').pickadate({
selectMonths: true,
selectYears: 15,
onClose: function() {
// add chip via filling the input and simulating enter
$("#datechips").find('input').trigger({ type : 'keydown', which : 13 });
},
});
It may not be ideal, but you should be able to tailor this going forward.
https://jsfiddle.net/j3ej8240/
I've also had a lot of trouble working this out. This is how I capture the add and delete chip events without using jQuery:
function chipDeleted(e, data) {
console.log("Chip was deleted with text: " + data.childNodes[0].textContent);
}
function chipAdded(e, data) {
console.log("Chip was added with text: " + data.childNodes[0].textContent);
}
//
document.addEventListener("DOMContentLoaded", function (e) {
console.log("DOM fully loaded and parsed");
var firstTag = "Initial Tag";
var elems = document.querySelectorAll('.chips');
var instances = M.Chips.init(elems, {
data:[{
tag: firstTag
}],
autocompleteOptions: {
limit: Infinity,
minLength: 1
},
placeholder: "No search...",
onChipDelete: function (e, data) { chipDeleted(e, data) },
onChipAdd: function (e, data) { chipAdded(e, data) }
});
});
And my HTML part is like this:
<body>
<div class="chips search-history"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
</body>

jQuery datepicker not working on dynamically inserted html element

This same question has been asked repeatedly, and the only time it has been answered is the one where the fellow was trying to initialise datepicker in the .onReady() function. I am not doing that. In fact, I am actually doing what that solution is doing; implementing datepicker immediately after creating the element.
Here is my template code:
<input type=text name="txt_you_History_From_Date_XXX" id="txt_you_History_From_Date_XXX" class="month-picker inputField" size=16 maxlength=16>
You will notice the month-picker class. Also, you will notice the "XXX" placeholders.
Here is the code that inserts that template code:
//
// find the next available id
//
for (var i = 0; ; i++) {
if (!$("#divEmployer_" + i.toString()).length) {
break;
}
}
//
// get html, and replace the placeholders with id, then append.
//
$.get("content/contentHistoryEmployerTemplate.html", function (data) {
while (data.indexOf("XXX") >= 0) {
data = data.replace("XXX", i.toString());
}
$("#employerDIV").append(data);
});
//
// activate datepicker on all month-picker class elements
//
$('.month-picker').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function (dateText, inst) {
$(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
}
});
//alert("here");
I do see the "here" alert if I uncomment it, so I know the code is being run.
The datepicker() throws no error.
I know the function is available because if I comment out my jquery-ui-min.js in my <HEAD>, a reference to datepicker() does then throw an error.
But the field does not respond when it receives focus. The datepicker does not appear.
Can anyone tell me what's wrong? Thanks!
You are trying to instantiate the datepicker before the element exists. Put that code inside the async callback.
$.get("content/contentHistoryEmployerTemplate.html", function (data) {
while (data.indexOf("XXX") >= 0) {
data = data.replace("XXX", i.toString());
}
$("#employerDIV").append(data);
// PUT DATEPICKER HERE
});

Calling Javascript function from an asp dropdownlist

I have an asp dropdownlist with a few selections and when I select a certain item from the list I want a javascript modal to open up. I have successfully been able to open the modal by using an html button after selecting the specific item from the drop down, but I want one less step.
Here is my code for the index changed event on the Drop down:
protected void ShipTo_Changed(object sender, EventArgs e)
{
foreach (DataListItem dli in cart.Items)
{
DropDownList drpShipto = (DropDownList)dli.FindControl("drpShipto");
if (drpShipto.SelectedItem.Text == "-Add New ShipTo-")
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "function", "showDialog('newShipTo')", true);
}
}
}
and here is what I have for the js :
<script>
$(document).ready(function () {
$('#newShipTo').dialog({
autoOpen: false,
draggable: true,
title: "Add New ShipTo",
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
$('#editShipTo').dialog({
autoOpen: false,
draggable: true,
title: "Edit ShipTo",
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
});
function showDialog(id) {
$('#' + id).dialog("open");
}
function closeDialog(id) {
$('#' + id).dialog("close");
}
</script>
I know the function works, as I can swap out the call to the function to making a button visible that with the onclick set to showDialog('newShipTo')
Am I just not calling it correctly using the RegistarStartupScript
I am going to take a stab at answering.
In your drop down....add an onchange event calling showDialog('newShipTo')
Please refer the below URL
http://dotnetgallery.com/forum/thread127-Calling-Javascript-function-from-an-asp-dropdownlist.aspx
Regards.

Bootstrap Datepicker on change firing 3 times

Hi I have been trying to just get the date of a bootstrap date picker and have been able to but it seems to fires 3 times. NOTE: This is not jquery date picker but bootstrap date picker.
Using this date picker: https://github.com/eternicode/bootstrap-datepicker, not older eyecon.ro one.
$(".date-picker").on("change", function(e) {
contents = $(this).val();
id = $(this).attr('id');
console.log("onchange contents: " + contents);
console.log("onchange id: " + id);
});
HTML:
<input id="start_date" type="text" data-date-format="yyyy-mm-dd" class="date-picker form-control" />
I have used a few other options other than change, like
$('.date-picker').datepicker().change(function(){};
But this does not close date picker, hoping there is an easy solution to this. thx
You should be using the "changeDate" event. For example:
var datePicker = $('.date-picker').datePicker().on('changeDate', function(ev) {
//Functionality to be called whenever the date is changed
});
Please view the documentation here for more info on this event.
it does not fix the problem, but i was using the datepicker to send through an ajax post, so the 3 change events was causing me problems - the 3rd event always failed. even if the documentation says to use a changeDate event, it doesn't seem right to me to fire the input tag's change event 3 times. the value isn't changing 3 times!
I wrote a simple 'debounce' function to get around the problem. doesn't fix the issue - which is due to multiple change events being fired from the methods: setValue (line 508) _setDate:(line 1048) and setValue (line 508) (version 1.3.0) of the widget.
var lastJQueryTS = 0 ;// this is a global variable.
....
// in the change event handler...
var send = true;
if (typeof(event) == 'object'){
if (event.timeStamp - lastJQueryTS < 300){
send = false;
}
lastJQueryTS = event.timeStamp;
}
if (send){
post_values(this);
}
it is pretty simple, just finds the jquery 'event', and makes sure that values in a window of 300ms are ignored. in my testing this all happened in 30 msec or so.
As some has mentioned already, use this:
$('#calendar').on("changeDate", function() {
});
The trick is to use changeDate instead of change.
It seems as if when checking the change event, if the change was from actual user interaction, the change event contains a value for originalEvent.
The event does NOT contain this value if the input was changed via JS:
$obj.val('1990-03-07').change() and the same with bootstrap-datepicker
Here's how I set it up:
Generic initial setup
// General selector for date inputs
var $obj = $('input[type="date"]');
$obj.datepicker({
// options here, not important for this example
});
Handle bootstrap-datepicker specific changes
$obj.datepicker().on('changeDate', function (event) {
handleInputDateAndTimeChange(event);
});
Now, deal with user interaction changes
$('input[type="date"], input[type="time"]').change(function (event) {
// This checks if change was initiated by user input and NOT JS
if(event.originalEvent !== undefined) {
handleInputDateAndTimeChange(event);
}
});
And finally, here's the handleInputDateAndTimeChange function
function handleInputDateAndTimeChange(event) {
var $input = $(event.target);
// Do what you want with $input object here...
}
I tried the answer from #pgee70 and it doesn't work for me. So this is my solution, hope its help
var send=true;
$('.input-group.date').datepicker({
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
language: 'es-ES',
weekStart: 1,
format: 'dd/mm/yyyy',
enableOnReadonly:false,
calendarWeeks: true,
autoclose: true,
todayHighlight:true
}).on("changeDate", function(e) {
if(send){
modificarFechaAplicacionCliente($("#input_filtro_fecha_cliente").val());
send=false;
}
setTimeout(function(){send=true;},200);
});
It´s not a beaty solution, but it´s work.
Similar to the above answer, but you should use datepicker unless you've renamed the function:
var datePicker = $('.date-picker').datepicker().on('changeDate', function(ev) {
//Functionality to be called whenever the date is changed
});
This works for me, except in my case, I renamed the function to datepickerBootstrap to avoid the clash with JQuery's. So then it would become:
var datePicker = $('.date-picker').datepickerBootstrap().on('changeDate', function(ev) {
// On change functionality
});
It is fixed find your fixed js datepicker file HERE
Read fixing description HERE
I have faced the same problem with bootstrap-datepicker when it used with the jQuery OnChange event they call function 3 times. Here is my code
#Html.TextBoxFor(x => x.CmpStartDate, "{0:dd-MMM-yyyy}", new { #size = "30", #class = "form-control search-date", #placeholder = "Start date" })
#Html.TextBoxFor(x => x.CmpEndDate, "{0:dd-MMM-yyyy}", new { #size = "30", #class = "form-control search-date", #placeholder = "End date" })
<script>
$('#CmpStartDate,#CmpEndDate').datepicker({
autoclose: true,
todayHighlight: true,
minViewMode: 3,
format: "dd-M-yyyy"
});
$(".search-date").on("change", function () {
cmpStartDate = $("#CmpStartDate").val();
cmpEndDate = $("#CmpEndDate").val();
SearchThisDateRecords(cmpStartDate,cmpEndDate);
});
function SearchThisDateRecords(cmpStartDate,cmpEndDate) {
console.log("Call search method");
}
</script>
We need to call this function only one time, Not multiple time so you can use the below logic to fix this problem
<script>
$('#CmpStartDate,#CmpEndDate').datepicker({
autoclose: true,
todayHighlight: true,
minViewMode: 3,
format: "dd-M-yyyy"
});
var i = 0;
$(".search-date").on("change", function () {
cmpStartDate = $("#CmpStartDate").val();
cmpEndDate = $("#CmpEndDate").val();
SearchThisDateRecords(cmpStartDate,cmpEndDate);
i++;
console.log(i);
if (i == 3) {
SearchThisDateRecords(cmpStartDate,cmpEndDate);
}
});
function SearchThisDateRecords(cmpStartDate,cmpEndDate) {
i =0; //Reset i value
console.log("Call search method");
}
</script>
Get global variable count and check if equal to 0 then execute Your function.
var count=0;
$( "#Id" ).datepicker({ minDate: 0}).on('change',function (){
if(count==0)
validity();//any function
count=1;
});
validity(){ count=0;}
bit annoying..
my code was:
var c=0;var send=false;
$(document).ready(function() {
jQuery( ".ed" ).datepicker({
format: "yyyy-mm-dd",
autoclose:!0
}).on('change',function() {
if(c==2){
c=0;
send=true;
}else{
c++;
send=false;
}
});
});
Please use changeDate function in place of change .
var LastController =['id','value']; //global variable...
function datepeakerchange(e){
if ((LastController[0] != e.target.id && LastController[1] != e.target.value) || (LastController[0] == e.target.id && LastController[1] != e.target.value)) {
LastController[0] = e.target.id;
LastController[1] = e.target.value;
write your code....
}
}
var pickerFireCount = 0;
function checkSelectedDateIsHollyday(rId) {
pickerFireCount++;
if (pickerFireCount == 3) {
if (!selectedDateIsHolyday(rId)) {
showInfoMessage('The date you selected is a holiday.');
pickerFireCount = 0;
}
}
}

jEditable - How to bypass the submit in datepicker onselect event

I am using jeditable with datepicker and i wish to do some validation once user select a date before submit it to the database. I gone through the jeditable-datepicker.js and realized that the submission is triggered once onselect event happened. How can I include conditions in the event so invalid date wont be submitted to the database?
Here is my trial by using the onsubmit event:
$('.expirydatepicker').editable('#(Url.Action("Edit", "Stock"))',
{
type: 'datepicker',
indicator: 'saving...',
event: 'dblclick',
tooltip: 'Double click to edit...',
style: 'inherit',
width: ($('.datepicker').width() - 10) + "px",
onsubmit: function (settings, td) {
var tid = $(td).attr('id');
//alert(tid);
$.ajax({
async: false,
url: '/Stock/CompareDate',
type: 'GET',
data: { id: tid },
success: function (result) {
if (result < 0) {
alert("Expiry dare cannot be earlier than storage date");
return onSelect(false);
}
else {
return true;
}
}
});
}
});
the jEditable-datepicker function :
/* attach jquery.ui.datepicker to the input element */
plugin: function( settings, original ) {
var form = this,
input = form.find( "input" );
// Don't cancel inline editing onblur to allow clicking datepicker
settings.onblur = 'nothing';
datepicker = {
dateFormat: 'D, dd M yy',
onSelect: function() {
// clicking specific day in the calendar should
// submit the form and close the input field
form.submit();
},
I wish to know is there anyway I can either "stop" the onselect event if the input is invalid??
Hope can get some help here... thanks....
try something like this:
plugin : function(settings, original) {
..
$(this).find('input').datepicker().bind('click', function(e) {
//e.preventDefault() // also test this
return false;
})
Can you simply check whether the selected date is valid, and only submit and form if it is?
onSelect: function(dateText, inst) {
if (/* dateText is valid */) {
form.submit();
}
}
i get it done by not stopping the submission, but change the input value back to default value if validation failed. This is the only way I could get it done. Thanks!

Categories