jQuery dynamic added class gets not applied - javascript

I've got a quite strange behaviour. I append a class at runtime but the class doesn't get applied (although it is there as I can see by debugging via firebug). Here is a fully (un-)functional example:
<html>
<head>
<link rel='stylesheet' href='./jQuery/css/superfish/superfish.css' type='text/css' />
<link rel='Stylesheet' href='./jQuery/css/smoothness/jquery-ui-1.8.16.custom.css' type='text/css' />
<script type='text/javascript' src='./jQuery/js/jquery-1.6.2.min.js'></script>
<script type='text/javascript' src='./jQuery/js/jquery-ui-1.8.16.custom.min.js'></script>
<script type='text/javascript' src='./jQuery/js/jquery.ui.datepicker-de.js'></script>
<script type='text/javascript' src='./jQuery/js/jquery-ui-timepicker.js'></script>
<script type='text/javascript' src='./jQuery/js/jquery-ui-timepicker-de.js'></script>
<script type='text/javascript'>
$(function () {
$('.DateTimePicker').datetimepicker({
stepMinute: 15
});
});
</script>
</head>
<body>
<script type='text/javascript'>
function testMe() {
$("[id$=Working]").addClass('DateTimePicker');
}
</script>
<input id="notWorking" type="text">
<input id="clickToTest" type="button" onclick="testMe()">
<input id="static" type="text" class="DateTimePicker">
</body>
</html>

I think the issue you're having is that the datetimepicker() is initialised to all elements with a class .dateTimePicker, but when you are dynamically adding a class to other elements the datetimepicker does not get initialised again for these elements. Here is a piece of code that i've seen used before to get around this problem.
$(document).ready(function(){
$('.DateTimePicker').on('click', function(){
$(this).datetimepicker({
stepMinute : 15
}).datetimepicker('show');
});
});
This means the datetimepicker is invoked straight after it is attached using .on(). more info here. This way the datetimepicker will be initialised on all elements which have the class .DateTimePicker even if they are added dynamically. Hope this helps.
UPDATE:
There's a few other ways i've seen this done if you do not like this method. One neat way of doing it is here.
Another way is to remove the class the datetimepicker adds to the element (so it knows which elements have datetimepickers initialised on them) and then rebinding the datetimepicker to your class again.
function testMe() {
$("[id$=Working]").addClass('DateTimePicker');
$('.DateTimePicker').removeClass('hasDatepicker').datetimepicker({ stepMinute: 15 });
}

When you click your <input type="submit" /> the class is being added and then a POST is being performed which reloads the page and the class should not be there on the fresh load.
Try changing it to <input type="button" /> and it should probably work.

Related

jQuery.validationEngine reference error?

Everything seems to be referenced correctly however I can't get it to work properly. Strangely it worked once but took 10 seconds before the validation message popped up, didn't change anything and tried again but stop working. The only warning i have is event.returnValue is deprecated. Please use the standard event.preventDefault() instead. in the jQuery library.
<html>
<head>
<link rel="stylesheet" href="jQuery-Validation-Engine-master/css/validationEngine.jquery.css" type="text/css"/>
</head>
<body>
<form id="formID">
<input class="validate[required]" type="text" id="agree" name="agree"/>
</form>
<script src='js/jquery-1.10.2.min.js'></script>
<script src="jQuery-Validation-Engine-master/js/languages/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script src="jQuery-Validation-Engine-master/js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$("#formID").validationEngine();
});
</script>
</body>
If there is nothing wrong with the above then it may be something else in my project interfering, but any help would be appreciated.
What is happening, probably, is at the time jQuery is loaded your plugin(s) aren't yet loaded so when you call the validationEngine() method, it's not yet defined. I recommend loading your scripts synchronously with Modernizr and call that method once both scripts have loaded.
If you stick with the Modernizr way all you need to do is include your minimized version of Modernizr in the head and call your scripts like below.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Your Document</title>
<!--
following script loads first. nevermind the version, I copied it from a script of mine
-->
<script type="text/javascript" src="js/modernizr.2.6.2.min.js"></script>
</head>
<body>
<form id="formID">
<!-- etc -->
</form>
<script type="text/javascript">
Modernizr.load([
{
// following loads next
load: 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',
complete: function() {
if (!window.jQuery) Modernizr.load('js/jquery-1.10.2.min.js');
// this is your local copy of jQuery, in case you might need a fallback
}
},{
// finally the remaining scripts load
load:[
'jQuery-Validation-Engine-master/js/languages/jquery.validationEngine-en.js',
'jQuery-Validation-Engine-master/js/jquery.validationEngine.js'
],
complete: function() {
// all is loaded. do what you want here.
$("#formID").validationEngine();
}
}]);
</script>
</body>
</html>
In my case as I mentioned above updating to jQuery lib 1.11.0 rid the warning for me. (latest chrome)
Here is how I ended up using the validationEngine if interested:
<form id="formID" />
<button type="submit" value="Save" id="Save" onclick="clicked(event);">Submit Survey</button>
function clicked (e)
{
if (confirm('Are you sure you want to submit?'))
{
if ($("#formID").validationEngine('validate'))
{
my.LocalStorage.save();
}
}
e.preventDefault();
}

Can't replace submit button with JQuery

I'm trying to do my first tests usign JQuery and it seems to be more difficult than what I expected.
I have a simple form calling some long operations. What I want is to display a progress bar during the loading. What I try to do in the following code is to replace the submit button with a progress bar when the user submits the form. The next page taking time to load, he will see a nice animation making him wait.
<html>
<head>
<title>Test form</title>
</head>
<body>
<form id="myCuteLittleForm"><input type="submit" id="submit"/></form>
<br />
<script src="http://code.jquery.com/jquery-1.9.1.js">
$(document).ready(function() {
$('#myCuteLittleForm').submit(function() {
$("#submit").replaceWith('<progress value="" max="">Import en cours.</progress>');
});
});
</script>
</body>
</html>
However, to my great distress, it doesn't work. Am I just doing bad jquery or is there a fundamental incomprehension ?
Do it in other script tag:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myCuteLittleForm').submit(function() {
$("#submit").replaceWith('<progress value="" max="">Import en cours.</progress>');
});
};
</script>

jQuery click function doesnt work

So I have a very simple code with form and one button
with jQuery I want to bind some actions when user clicks on that button, but some reason it's not working
Here is the code
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<script>
$('#jallerysubmit').bind('click', function() {
alert('asd');
})
</script>
<form>
<input type="checkbox" name="box1">box1<br>
<input type="checkbox" name="box1">box2<br>
<input type="button" id="jallerysubmit" value="Proved">
</form>
</body>
</html>
please suggest what's wrong with this code as it does not work, even it does not produce any error
You need to wrap it in a document ready handler.
<script>
$(function() {
$('#jallerysubmit').bind('click', function() {
alert('asd');
});
});
</script>
Docs: http://api.jquery.com/ready/
The JavaScript code will be executed before the DOM is loaded, so the element with ID jallerysubmit cannot be found (it does not exists yet).
#sje397 described a very common way (at least when using jQuery) how to solve this. Another way is to put the script at the end of the document:
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<form>
<input type="checkbox" name="box1">box1<br>
<input type="checkbox" name="box1">box2<br>
<input type="button" id="jallerysubmit" value="Proved">
</form>
<script>
$('#jallerysubmit').bind('click', function() {
alert('asd');
});
</script>
</body>
</html>
Your code attaching the handler is being executed before the element exists in the DOM, therefore the selector returns nothing and the handler is not applied. Put the code inside a document ready handler and it should work. You could also simplify by using the click shortcut.
<script>
$(function() {
$('#jallerysubmit').click(function() {
alert('asd');
});
});
</script>
Include an alert("hello"); right after to make sure the jQuery is working right. Then add a return false to the end of your submit handle to make sure your page doesnt reload when the button is clicked, also use document.ready. See code below
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
alert("hello");
$('#jallerysubmit').bind('click', function() {
alert('asd');
return false;
});
});
</script>
<form>
<input type="checkbox" name="box1">box1<br>
<input type="checkbox" name="box1">box2<br>
<input type="button" id="jallerysubmit" value="Proved">
</form>
</body>
</html>
Best practice is using an external .js file, example script.js:
$(document).ready(function() {
yourFunction();
});
function yourFunction() {
$('#jallerysubmit').click(function() {
alert('asd');
});
}
and import it in your html file in the tag head:
<script type="text/javascript" src="script.js"></script>
Always use jquery function within
(document).ready(function(){//ur jquery codes});
or
$().ready(function(){//ur jquery codes});
or
$.noConflict();
jQuery(document).ready(function($){//ur codes});
Once DOM of page is loaded above ready function is initiated. so i recommend jquery lovers to write their magic codes always within this code

Apply jQuery datepicker to multiple instances

I've got a jQuery date picker control that works fine for once instance, but I'm not sure how to get it to work for multiple instances.
<script type="text/javascript">
$(function() {
$('#my_date').datepicker();
});
</script>
<% Using Html.BeginForm()%>
<% For Each item In Model.MyRecords%>
<%=Html.TextBox("my_date")%> <br/>
<% Next%>
<% End Using%>
Without the For Each loop, it works fine, but if there's more than one item in the "MyRecords" collection, then only the first text box gets a date picker (which makes sense since it's tied to the ID). I tried assigning a class to the text box and specifying:
$('.my_class').datepicker();
but while that shows a date picker everywhere, they all update the first text box.
What is the right way to make this work?
html:
<input type="text" class="datepick" id="date_1" />
<input type="text" class="datepick" id="date_2" />
<input type="text" class="datepick" id="date_3" />
script:
$('.datepick').each(function(){
$(this).datepicker();
});
(pseudo coded up a bit to keep it simpler)
I just had the same problem.
The correct way to use date pick is $('.my_class').datepicker(); but you need to make sure you don't assign the same ID to multiple datepickers.
The obvious answer would be to generate different ids, a separate id for each text box, something like
[int i=0]
<% Using Html.BeginForm()%>
<% For Each item In Model.MyRecords%>
[i++]
<%=Html.TextBox("my_date[i]")%> <br/>
<% Next%>
<% End Using%>
I don't know ASP.net so I just added some general C-like syntax code within square brackets. Translating it to actual ASP.net code shouldn't be a problem.
Then, you have to find a way to generate as many
$('#my_date[i]').datepicker();
as items in your Model.MyRecords. Again, within square brackets is your counter, so your jQuery function would be something like:
<script type="text/javascript">
$(function() {
$('#my_date1').datepicker();
$('#my_date2').datepicker();
$('#my_date3').datepicker();
...
});
</script>
<html>
<head>
<!-- jQuery JS Includes -->
<script type="text/javascript" src="jquery/jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery/ui/ui.core.js"></script>
<script type="text/javascript" src="jquery/ui/ui.datepicker.js"></script>
<!-- jQuery CSS Includes -->
<link type="text/css" href="jquery/themes/base/ui.core.css" rel="stylesheet" />
<link type="text/css" href="jquery/themes/base/ui.datepicker.css" rel="stylesheet" />
<link type="text/css" href="jquery/themes/base/ui.theme.css" rel="stylesheet" />
<!-- Setup Datepicker -->
<script type="text/javascript"><!--
$(function() {
$('input').filter('.datepicker').datepicker({
changeMonth: true,
changeYear: true,
showOn: 'button',
buttonImage: 'jquery/images/calendar.gif',
buttonImageOnly: true
});
});
--></script>
</head>
<body>
<!-- Each input field needs a unique id, but all need to be datepicker -->
<p>Date 1: <input id="one" class="datepicker" type="text" readonly="true"></p>
<p>Date 2: <input id="two" class="datepicker" type="text" readonly="true"></p>
<p>Date 3: <input id="three" class="datepicker" type="text" readonly="true"></p>
</body>
</html>
There is a simple solution.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="../js/flexcroll.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.8.18.custom.min.js"></script>
<script type="text/javascript" src="../js/JScript.js"></script>
<title>calendar</title>
<script type="text/javascript">
$(function(){$('.dateTxt').datepicker(); });
</script>
</head>
<body>
<p>Date 1: <input id="one" class="dateTxt" type="text" ></p>
<p>Date 2: <input id="two" class="dateTxt" type="text" ></p>
<p>Date 3: <input id="three" class="dateTxt" type="text" ></p>
</body>
</html>
When adding datepicker at runtime generated input textboxes you have to check if it already contains datepicker then first remove class hasDatepicker then apply datePicker to it.
function convertTxtToDate() {
$('.dateTxt').each(function () {
if ($(this).hasClass('hasDatepicker')) {
$(this).removeClass('hasDatepicker');
}
$(this).datepicker();
});
}
A little note to the SeanJA answer.
Interestingly, if you use KnockoutJS and jQuery together
the following inputs with different IDs, but with the same data-bind observable:
<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: first_dt" id="date_2" class="datepick" />
will bind one (the same) datepicker to both of the inputs (even though they have different ids or names).
Use separate observables in your ViewModel to bind a separate datepicker to each input:
<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: second_dt" id="date_2" class="datepick" />
Initialization:
$('.datepick').each(function(){
$(this).datepicker();
});
The solution here is to have different IDs as many of you have stated. The problem still lies deeper in datepicker. Please correct me, but doesn't the datepicker have one wrapper ID - "ui-datepicker-div." This is seen on http://jqueryui.com/demos/datepicker/#option-showOptions in the theming.
Is there an option that can change this ID to be a class? I don't want to have to fork this script just for this one obvious fix!!
To change use of class instead of ID
<script type="text/javascript">
$(function() {
$('.my_date1').datepicker();
$('.my_date2').datepicker();
$('.my_date3').datepicker();
...
});
</script>
I had the same problem, but finally discovered that it was an issue with the way I was invoking the script from an ASP web user control. I was using ClientScript.RegisterStartupScript(), but forgot to give the script a unique key (the second argument). With both scripts being assigned the same key, only the first box was actually being converted into a datepicker. So I decided to append the textbox's ID to the key to make it unique:
Page.ClientScript.RegisterStartupScript(this.GetType(), "DPSetup" + DPTextbox.ClientID, dpScript);
I had a similar problem with dynamically adding datepicker classes. The solution I found was to comment out line 46 of datepicker.js
// this.element.on('click', $.proxy(this.show, this));
In my case, I had not given my <input> elements any ID, and was using a class to apply the datepicker as in SeanJA's answer, but the datepicker was only being applied to the first one. I discovered that JQuery was automatically adding an ID and it was the same one in all of the elements, which explained why only the first was getting datepickered.

JQuery UI datepicker not working when bound to a class

I've got this code:
<html>
<head>
<link type="text/css" href="css/blitzer/jquery-ui-1.7.2.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript">
$(function() {
$('.hasDatepicker').datepicker();
});
</script>
</head>
<body>
<p>date: <input type="text" name="data" class="hasDatepicker" /></p>
<input type="submit" value="send" />
</div>
</body>
</html>
When I click the input field, nothing happens. The datepicker is initialized though, when I inspect the DOM in Firebug, I get the id="dp1260260566059" added to my <input> element.
After changing the html and js to use id attribute instead of class, so having this in my code:
$(function() {
$('#hasDatepicker').datepicker();
});
and
<p>date: <input type="text" name="data" id="hasDatepicker" /></p>
Everything works OK.
Can't datepicker from JQuery UI work for all elements of some class?
Please check if the datepicker works if you change the class name of the input fields from 'hasDatePicker' to something else. The reason is, when add the datepicker to the input field using the below code:
$(function() {
$('#date').datepicker();
});
it adds the class name "hasDatePicker" to the input field. (which is the one u r using)
Don't use hasDatepicker as your date picker's class name. Use a different name, like date_picker.
JQuery adds the class hasDatepicker to the element that datepicker() is called on. If the element already has the class hasDatepicker, then the datepicker() function does nothing. So, just use a different class name.

Categories

Resources