Autocomplete for text area using entered values - html

I want to do autocomplete for textarea using entered values from browser. It is working for Textbox but not working Text area.

Normal textbox indeed get autocomplete behaviour for free.
As far as i know, you can get similar behaviour for textarea (even better, with all history) with installing lazarus plugin in your web browser.
Once installed, you will get a small cross icon on the top right corner. Clicking it will popup previous entries.
I usually don't like to install third party plugin in my web browser but this can save a lot of time and frustration when accidentally loosing all the text we already type.

First you need to include jquery UI then use the example code
HTML
<div class="ui-widget">
<label for="tags">Tags:</label>
<textarea id="tags" size="30"></textarea>
</div>
JS
$(function () {
$("document").ready(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"];
$("#tags").on("keydown", function () {
var newY = $(this).textareaHelper('caretPos').top + (parseInt($(this).css('font-size'), 10) * 1.5);
var newX = $(this).textareaHelper('caretPos').left;
var posString = "left+" + newX + "px top+" + newY + "px";
$(this).autocomplete("option", "position", {
my: "left top",
at: posString
});
});
$("#tags ").autocomplete({
source: availableTags
});
});
});

You Need to use external plugin
Scripts and CSS
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
HTML
<textarea id="demo"></textarea>
Script
<script>
$(function() {
//Get the Data from a JSON or Hidden Feild
var availableTags = ["jQuery.com", "jQueryUI.com", "jQueryMobile.com", "jQueryScript.net", "jQuery", "Free jQuery Plugins"]; // array of autocomplete words
var minWordLength = 2;
function split(val) {
return val.split(' ');
}
function extractLast(term) {
return split(term).pop();
}
$("#demo") // jQuery Selector
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
}).autocomplete({
minLength: minWordLength,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
var term = extractLast(request.term);
if(term.length >= minWordLength){
response($.ui.autocomplete.filter( availableTags, term ));
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(" ");
return false;
}
});
});
</script>
DEMO LINK
ANOTHER PLUGIN TEXTEXTJS

Browsers do not currently support autocompletion for a textarea. The autocomplete attribute is formally allowed for textarea in HTML5 and it has the default value of on, but this value just means that browsers are allowed to use autocompletion. They do not actually use it for textareas, apparently because it would seldom be useful and could actually be confusing. It is much more probably that a user wants to reuse his address information, entered in single-line text input fields, than some longish text he has entered in, say, a feedback form of some site and now some other site happens to have a comments textarea with the same name.
Thus, all you can do is to set up some autocomplete functionality of your own. (This is what other answers suggest in various ways.) This means that you need to store user input somehow (which is what browsers do for their own autocompletion operations too), e.g. in cookies or in localStorage. This generally means that the functionality works inside a site, on pages using the same technique to implement it, but not across sites.

Related

how to toggle appended elements using multiple buttons and pass info to the output JQuery

I have asked kind of a similar question before : how to toggle using multiple buttons and pass info to the output JQuery
It was answered well, but this time I am using a different approach in the code thus a new question.
I am trying to toggle info and append a div using three different buttons.
Here is The code https://jsfiddle.net/YulePale/nruew82j/40/
JavaScript
document.getElementById("brazil").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("brazil").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("draw").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("draw").value
para.innerHTML = 'This two teams have played each other 4 times ' +
`${homeTeam}` + ':' <br> <input type="text" value="${homeTeam}" id="myInput">
<button onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("russia").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("russia").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
PS: I don't know why the javascript code is not working in fiddle yet it is working on my computer.
If you look at the code I am basically trying to toggle a div with info on various teams. If it is Brazil the div comes with info on Brazil if Russia, info on Russia.
The problem with my current code is that it keep on appending the divs instead of
toggling them. How can I toggle them? like this: https://jsfiddle.net/YulePale/7jkuoc93/
Instead of having them append another div each time I click a different button?
............................................................................................
PS: EDIT & UPDATE:
#Twisty, I forked the code from your fiddle and tried to implement it when working with more than one row of buttons. The code works well but I was unable to append a different and separate element for each row each time I click on a button on that row.
I tried putting the appended element as a class:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/34/
Also tried putting it as an id:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/38/
How can I put it in a way that each row appends it's own separate element and I would also like users to be able to copy using the copy button without the element disappearing. How do I make it in such a way that the element only disappears only when I click outside the respective:
<div class="col.buttonCol " id="buttons-div">
and also disappears when I click another row of buttons?
Also in your answer you said you would have used text boxes instead of appending this way. I checked the modals out and they all appear on the browser like alerts can you please point me to a resource that show how you can use a modal that works like an appending element instead of one that acts as an alert? Thank you.
Here is the link to the modals I saw: https://getbootstrap.com/docs/4.0/components/modal/
I converted all your JavaScript to jQuery since you posted this in the jquery-ui, I am assuming you want to work with jQuery.
I will often organize my functions first and then the interactive actions.
JavaScript
$(function() {
function myFunction() {
//Do Stuff
}
function AppendFunction(id) {
var para = $("<p>");
var home = $("#" + id).val();
para.append("This is the national team of " + home + ":", $("<br>"), $("<input>", {
type: "text",
value: home,
id: "myInput"
}), $("<button>").html("Copy Text").click(myFunction));
$("#gugu").html(para);
}
function emptyOnDocumentClick(event) {
var action = $(".triggered").length;
$(".triggered").removeClass("triggered");
return !action;
}
$("#brazil, #russia").on('click', function(e) {
if ($(this).hasClass("triggered")) {
return;
}
$(this).addClass("triggered");
var myId = $(this).attr("id");
AppendFunction(myId);
});
$(document).on("click", function(e) {
if (emptyOnDocumentClick(e)) {
$("#gugu").html("");
}
});
});
Working Example: https://jsfiddle.net/Twisty/nruew82j/91/
The basic concept here is a dialog and if it were me, I would use a dialog box either from BootStrap or jQuery UI. You're not doing that, so we're create the content and append it to a specific <div>. Then, like in your previous question, you just detect a click on the document and decide what that will do. In this case, I emptied the content of the <div> that we'd previously appended content to.
Hope that helps.

How to send a single request through p:commandButton inside p:dialog? [duplicate]

I have following jQuery code to prevent double clicking a button. It works fine. I am using Page_ClientValidate() to ensure that the double click is prevented only if the page is valid. [If there are validation errors the flag should not be set as there is no postback to server started]
Is there a better method to prevent the second click on the button before the page loads back?
Can we set the flag isOperationInProgress = yesIndicator only if the page is causing a postback to server? Is there a suitable event for it that will be called before the user can click on the button for the second time?
Note: I am looking for a solution that won't require any new API
Note: This question is not a duplicate. Here I am trying to avoid the use of Page_ClientValidate(). Also I am looking for an event where I can move the code so that I need not use Page_ClientValidate()
Note: No ajax involved in my scenario. The ASP.Net form will be submitted to server synchronously. The button click event in javascript is only for preventing double click. The form submission is synchronous using ASP.Net.
Present Code
$(document).ready(function () {
var noIndicator = 'No';
var yesIndicator = 'Yes';
var isOperationInProgress = 'No';
$('.applicationButton').click(function (e) {
// Prevent button from double click
var isPageValid = Page_ClientValidate();
if (isPageValid) {
if (isOperationInProgress == noIndicator) {
isOperationInProgress = yesIndicator;
} else {
e.preventDefault();
}
}
});
});
References:
Validator causes improper behavior for double click check
Whether to use Page_IsValid or Page_ClientValidate() (for Client Side Events)
Note by #Peter Ivan in the above references:
calling Page_ClientValidate() repeatedly may cause the page to be too obtrusive (multiple alerts etc.).
I found this solution that is simple and worked for me:
<form ...>
<input ...>
<button ... onclick="this.disabled=true;this.value='Submitting...'; this.form.submit();">
</form>
This solution was found in:
Original solution
JS provides an easy solution by using the event properties:
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){//activate on first click only to avoid hiding again on multiple clicks
// code here. // It will execute only once on multiple clicks
}
});
disable the button on click, enable it after the operation completes
$(document).ready(function () {
$("#btn").on("click", function() {
$(this).attr("disabled", "disabled");
doWork(); //this method contains your logic
});
});
function doWork() {
alert("doing work");
//actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
//I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
setTimeout('$("#btn").removeAttr("disabled")', 1500);
}
working example
I modified the solution by #Kalyani and so far it's been working beautifully!
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){ return true; }
else { return false; }
});
Disable pointer events in the first line of your callback, and then resume them on the last line.
element.on('click', function() {
element.css('pointer-events', 'none');
//do all of your stuff
element.css('pointer-events', 'auto');
};
After hours of searching i fixed it in this way:
old_timestamp = null;
$('#productivity_table').on('click', function(event) {
// code executed at first load
// not working if you press too many clicks, it waits 1 second
if(old_timestamp == null || old_timestamp + 1000 < event.timeStamp)
{
// write the code / slide / fade / whatever
old_timestamp = event.timeStamp;
}
});
you can use jQuery's [one][1] :
.one( events [, data ], handler ) Returns: jQuery
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
see examples:
using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx
// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);
using count,
clickcount++;
if (clickcount == 1) {}
After coming back again clickcount set to zero.
May be this will help and give the desired functionality :
$('#disable').on('click', function(){
$('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>
<p>Hello</p>
We can use on and off click for preventing Multiple clicks. i tried it to my application and it's working as expected.
$(document).ready(function () {
$("#disable").on('click', function () {
$(this).off('click');
// enter code here
});
})
This should work for you:
$(document).ready(function () {
$('.applicationButton').click(function (e) {
var btn = $(this),
isPageValid = Page_ClientValidate(); // cache state of page validation
if (!isPageValid) {
// page isn't valid, block form submission
e.preventDefault();
}
// disable the button only if the page is valid.
// when the postback returns, the button will be re-enabled by default
btn.prop('disabled', isPageValid);
return isPageValid;
});
});
Please note that you should also take steps server-side to prevent double-posts as not every visitor to your site will be polite enough to visit it with a browser (let alone a JavaScript-enabled browser).
The absolute best way I've found is to immediately disable the button when clicked:
$('#myButton').click(function() {
$('#myButton').prop('disabled', true);
});
And re-enable it when needed, for example:
validation failed
error while processing the form data by the server, then after an error response using jQuery
Another way to avoid a quick double-click is to use the native JavaScript function ondblclick, but in this case it doesn't work if the submit form works through jQuery.
One way you do this is set a counter and if number exceeds the certain number return false.
easy as this.
var mybutton_counter=0;
$("#mybutton").on('click', function(e){
if (mybutton_counter>0){return false;} //you can set the number to any
//your call
mybutton_counter++; //incremental
});
make sure, if statement is on top of your call.
If you are doing a full round-trip post-back, you can just make the button disappear. If there are validation errors, the button will be visible again upon reload of the page.
First set add a style to your button:
<h:commandButton id="SaveBtn" value="Save"
styleClass="hideOnClick"
actionListener="#{someBean.saveAction()}"/>
Then make it hide when clicked.
$(document).ready(function() {
$(".hideOnClick").click(function(e) {
$(e.toElement).hide();
});
});
Just copy paste this code in your script and edit #button1 with your button id and it will resolve your issue.
<script type="text/javascript">
$(document).ready(function(){
$("#button1").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
});
</script
Plain JavaScript:
Set an attribute to the element being interacted
Remove the attribute after a timeout
If the element has the attribute, do nothing
const throttleInput = document.querySelector('button');
throttleInput.onclick = function() {
if (!throttleInput.hasAttribute('data-prevent-double-click')) {
throttleInput.setAttribute('data-prevent-double-click', true);
throttleInput.setAttribute('disabled', true);
document.body.append("Foo!");
}
setTimeout(function() {
throttleInput.removeAttribute('disabled');
throttleInput.removeAttribute('data-prevent-double-click');
}, 3000);
}
<button>Click to add "Foo"!</button>
We also set the button to .disabled=true. I added the HTML Command input with type hidden to identify if the transaction has been added by the Computer Server to the Database.
Example HTML and PHP Commands:
<button onclick="myAddFunction(<?php echo $value['patient_id'];?>)" id="addButtonId">ADD</button>
<input type="hidden" id="hasPatientInListParam" value="<?php echo $hasPatientInListParamValue;?>">
Example Javascript Command:
function myAddFunction(patientId) {
document.getElementById("addButtonId").disabled=true;
var hasPatientInList = document.getElementById("hasPatientInListParam").value;
if (hasPatientInList) {
alert("Only one (1) patient in each List.");
return;
}
window.location.href = "webAddress/addTransaction/"+patientId; //reloads page
}
After reloading the page, the computer auto-sets the button to .disabled=false. At present, these actions prevent the multiple clicks problem in our case.
I hope these help you too.
Thank you.
One way I found that works is using bootstrap css to display a modal window with a spinner on it. This way nothing in the background can be clicked. Just need to make sure that you hide the modal window again after your long process completes.
so I found a simple solution, hope this helps.
all I had to do was create a counter = 0, and make the function that runs when clicked only runnable if the counter is = 0, when someone clicks the function the first line in the function sets counter = 1 and this will prevent the user from running the function multiple times when the function is done the last line of the code inside the function sets counter to 0 again
you could use a structure like this, it will execute just once:
document.getElementById('buttonID').addEventListener('click', () => {
...Do things...
},{once:true});

Anchor <a> tags not working in chrome when using #

Here is the code I am using on my page,
<li>Sound</li>
(in a menu which appears on all pages)
<a id="Sound"><a>
(on the page where i want to link to)
I have tried adding content to the tags with an id. But only in chrome the browser will not scroll down to the tag. These anchors work in IE&FF
Any ideas?
Turns out this was a bug in certain versions of chrome, posting workaround for anyone who needs it! :)
$(document).ready(function () {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (window.location.hash && isChrome) {
setTimeout(function () {
var hash = window.location.hash;
window.location.hash = "";
window.location.hash = hash;
}, 300);
}
});
The workaround posted didn't work for me, however after days of searching this finally worked like a charm so I figured it was worth sharing:
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
If you somehow ended up here like me when finding out the anchor link to a SPA site doesn't work from an external site. Yep, the browser is just working too fast to load the skeleton of the page. And it couldn't find your anchor when it loads the page.
To work around this, just add in the lifecycle of your SPA (useEffect in React and mounted in Vue) some lines to check the url hash and do the scrolling yourself.
example using React
useEffect(()=> {
if(document.location.hash === '#some-anchor') {
setTimeout(()=> {
document
.querySelector("#some-anchor")
.scrollIntoView({ behavior: "smooth", block: "start" })
}, 300)
}
}, [])
I was having this problem as well (same page navigation using links) and the solution was very easy (though frustrating to figure out). I hope this helps - also I checked IE, Firefox, and Chrome and it worked across the board (as of 05-22-2019).
Your link should looks like this:
Word as link you want people to click
and your anchor should look like this:
<a name="#anchorname">Spot you want to appear at top of page once link is clicked</a>
Try using :
For menu page
<li>Sound</li>
in a menu which appears on all pages
<a id="#Sound"><a>
This works well in the all versions of Chrome!
I have tested it on my browser.
This answer is for someone who encountered same problem, but scripts didn't work. Try to remove loading='lazy' and decoding='async' from all images on the page or set width and height attributes to them.
It worked like a charm for me.
Here is my version of #Jake_ answer for Chrome / angular not scrolling to a correct anchor on initial page load up using ui-router (the original answer would throw my code into 'Transition superseeded' exceptions):
angular.module('myapp').run(function($transitions, $state, $document, $timeout) {
var finishHook = $transitions.onSuccess({}, function() { // Wait for the complete routing path to settle
$document.ready(function() { // On DOM ready - check whether we have an anchor and Chrome
var hash;
var params;
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
finishHook(); // Deregister the hook; the problem happens only on initial load
if ('#' in $state.params && isChrome) {
hash = $state.params['#']; // Save the anchor
params = _.omit($state.params, ['id', '#']);
$timeout(function() {
// Transition to the no-anchor state
$state.go('.', params, { reload: false, notify: false, location: 'replace' });
$timeout(function() {
// Transition back to anchor again
$state.go('.', _.assign($state.params, { '#': hash }), { reload: false, notify: false, location: 'replace' });
}, 0);
}, 0);
}
});
}, {invokeLimit: 1});
});
Not sure if this helps at all or not, but I realized my anchors in IE were working but not in Firefox or Chrome. I ended up adding ## to my anchors and this solved the issue.
example:
a href="##policy">Purpose and Policy Statement
instead of :
a href="#policy">Purpose and Policy Statement
<html>
<body>
<li>
Sound
</li>
<a id="Sound" href="www.google.com">I AM CALLED</a>
</body>
</html>
use this as your code it will call the anchor tag with id value sound
Simply change the call on your link to external.

Google-like jQuery UI autocomplete

Is it possible to send the server only the last 3 words in the textarea and to autofill the best result, letting the user keep typing in (similar to Google auto complete)?
I want the behavior to be:
N[ew]
New[er]
New(SPACE)[er]
New [York]
New c[ar]
New cat [food]
New cat (TAB) [food]
New cat food [makes]
...
New cat food is good for your cat's [health]
(clarification: the [square brackets] indicates the suggestion that is automatically being typed in, the bold text indicates the part being sent to the server, (TAB) and (SPACE) indicates tab and space key presses)
I already a have function on the server for predicting the next word (using Markov chains) and I have integrated jQuery UI autocomplete, but currently it just sends all the text to the server and creates a list with all the suggestions to choose from, once you choose it changes the whole text.
So it eventually comes to these issues:
How to send only the last part?
How to append + select the suggested word?
How to select on Tab key?
Okay - here is the solution (and here is the result):
1 + 2: Instead of managing a single input box, I use two identical size textarea's, the first (#text-area) is enables and with transparent background and the other (#suggestions) is disabled and with gray text color. I use the source callback to do all the work:
$('#text-area').autocomplete({ ...
source: function( request, response ) {
if (request.term.length < 3) {
return false;
}
$.getJSON( $SCRIPT_ROOT + '/_get_word', {
term: request.term
}, function(data) {
$('#suggestions').val(data.result) //suggestion is the disabled textarea
}
);
return false;
},
...
});
});
3: the tab key selection is done with triggering the autocomplete search event:
$('#text-area').live( "keydown",'textarea', function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB) {
event.preventDefault();
$('#text-area').val($('#suggestions').val());
$("#text-area").autocomplete('search', $('#text-area').val());
}
});

jQuery datepicker won't work on a AJAX added html element

I have a jQuery datepicker function bound to the "birthday" input html element, written in the page header:
<script type="text/javascript">
$(function() {
$( "#birthday" ).datepicker();
});
</script>
Next, I have some AJAX functionality - it adds new input html element to the page. That element is:
<input type="text" id="birthday" value="" class="detail-textbox1" />
Clicking on that birthday element does not pop up the date picker below the text field. I expected this, as the element is added after the page is loaded, thus it isn't in relation with the function provided in the header.
How can I make it work? I tried moving the script from the header to the body, but nothing seems to work. Thanks.
P.S. If I create an input html element with id="birthday" in the page body, everythig works as expected. It appears that only the elements added through AJAX are dysfunctional.
I'm a bit late to the party, but for thoroughness - and with the .live() function being deprecated from jQuery 1.7 onwards - I thought I'd provide an updated solution based on my experiences, and from all the help I got from other answers on StackOverflow!
I had a situation where I needed to add the datepicker functionality to input fields that were being added to the DOM through AJAX calls at random, and I couldn't modify the script making the AJAX calls to attach the datepicker functionality, so I opted for the new shiny .on() function with its delegation features:
// do this once the DOM's available...
$(function(){
// this line will add an event handler to the selected inputs, both
// current and future, whenever they are clicked...
// this is delegation at work, and you can use any containing element
// you like - I just used the "body" tag for convenience...
$("body").on("click", ".my_input_element", function(){
// as an added bonus, if you are afraid of attaching the "datepicker"
// multiple times, you can check for the "hasDatepicker" class...
if (!$(this).hasClass("hasDatepicker"))
{
$(this).datepicker();
$(this).datepicker("show");
}
});
});
I hope this helps someone, and thanks for all the answers so far that led me to this solution that worked for me! :)
You need to use .live() so that any newly added elements have the event handler attached: http://api.jquery.com/live/
$('#birthday').bind('load', function() {
$(this).datepicker();
});
EDIT
.live() documentation states, that it is a bit out of date. With new versions of jquery (1.7+) use .on().
Boris, JK: This was super helpful for me. I have also found that you can use the following for AJAX html if you want to use Datepicker's date range selection:
$('#groundtransporation').live('focus', function() {
var gt = $( "#rentalPickUp, #rentalDropOff" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 2,
onSelect: function( selectedDate ) {
var option = this.id == "rentalPickUp" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
gt.not( this ).datepicker( "option", option, date );
}
});
});
I got another case.
My script is copying last table elements including datepicker.
The jquery will not working because the copied element has mark that it "hasDatepicker".
To activate datepicker in new element, remove that class name and the initiate it, like this.
$("#yournewelementid").attr("class","your-class-name");
$("#yournewelementid").datepicker();
your issue is always happens when elements don't exist when you try to initialize it.
When you use $(function(){/** some code **/}); elements must exsit on the document, it means that has to be on the html so you could can create a function to initialize the component or initialize it on the success event after been add it to the document.
Is important to first add the external html load in the ajax request to the document before you try to initialize it or it won't be initialize at all.
Example:
$.ajax({
url:"ajax_html.html",
dataType:"html"
}).done(function(html){
$("#selector").html(html)
init();
});
function init(){
$(".birthday").datepicker({});
}
You could initialize the date picker for the newly added element within your ajax success callback:
$.ajax({
...
success: function(response) {
if(response.success) {
$(body).append(response.html);
$("#birthday").datepicker();
}
}
});