I have created a server control for a login panel.
On this panel I have a textbox for the username and a textbox for the password.
Below that there is the button for login.
I want the button to be disabled if either or both textboxes are empty.
For that I created a function that checks the length of the contents of the textboxes.
function doCheck()
{
var lngth1 = document.getElementById('pnLogin_txtUserName').value.length;
var lngth2 = document.getElementById('pnLogin_txtPassword').value.length;
if (lngth1 > 0 && lngth2 > 0)
{
$('#pnLogin_btLogin').removeAttr('disabled');
} else {
$('#pnLogin_btLogin').attr('disabled','disabled');
}
}
I run this function at the start and on every keyup event.
That works great.
The problem is when the browser starts with the page. It fills in the username and password if they are stored.
When the function is then run, it still disables the button even though there is information in the textboxes.
I tried this:
setTimeout( function()
{
doCheck();
}, 2000);
But after 2 seconds I see the button disabling while seeing my credentials filled in.
If I inspect the element in Chrome, I don't see my credentials in the html code.
So where is it stored? How can I detect this?
You will not see the values in the html as they are not actually in the DOM.
You may access their values using $("#pnLogin_txtUserName").val() and
$("#pnLogin_txtPassword").val().
I would simplify your function and use jQuery specific syntax rather than native javascript.
function doCheck() {
var lngth1 = $("#pnLogin_txtUserName").val().length;
var lngth2 = $("#pnLogin_txtPassword").val().length;
if (lngth1 > 0 && lngth2 > 0) {
$('#pnLogin_btLogin').prop('disabled', false);
} else {
$('#pnLogin_btLogin').prop('disabled', true);
}
}
I also changed your code from .attr to .prop for disabling the input. Find more information with this stackoverflow question
The problem is when the browser starts with the page. It fills in the username and password if they are stored. When the function is then run, it still disables the button even though there is information in the textboxes.
Your code is being executed the moment it is loaded and parsed by the browser. The proper jQuery method is to use whats called .ready() which will execute after jQuery detects the page has finished loading.
$(document).ready( function() {
doCheck();
});
Or more simplified to:
$(function() {
doCheck();
});
detecting change
We can detect when the values get changed by bind an event listener:
$("pnLogin_txtUserName").change(function() {
console.log( 'pnLogin_txtUserName has changed', $(this).val() );
});
If we add a class to your inputs, say .loginElements, then we do things a bit easier and detect several different events:
$(".loginElements").on( 'change keypress', function() {
doCheck();
});
Related
I have a problem with my inputs, i had a custom floating label once there is text inside my input. My problem is chrome autofill add the text after my javascript onDocumentReady check for text. I want my javascript function to be called after chrome as loaded the text or any time of autocompletion. Is it possible?
I have tried launching the javascript function upon documentGetReady.
$( document ).ready(function() {
toggleInputsFloatingLabelCustomClass();
});
Use a change function instead to see if any of your inputs change
jQuery('input').change(function(){
toggleInputsFloatingLabelCustomClass();
}
this will solve your problem of chrome autofilling after your script has run
You can add onkeyup definition for your inputs eq.
<input onkeyup='toggleInputsFloatingLabelCustomClassWithWait();'/>
than you can check if user is stil writing eq. Every one seocond and execute your method if user is writing like this:
var timeout = null;
function toggleInputsFloatingLabelCustomClassWithWait() {
clearTimeout(timeout);
timeout = setTimeout(function () {
toggleInputsFloatingLabelCustomClass();
}, 1000);
}
I have a function that is triggered by "Calculate" button
I need this line to only run once per session (session could be 1 day or until browser is reloaded).
$('.popup-with-form').magnificPopup('open');
This opens a Magnific Popup. Once this function is executed (popup opens), if "calculate" button is pressed again, I don't want popup to open again.
JS / JQuery code:
function StateChanged() {
if (XmlHttp.readyState == 4 || XmlHttp.readyState == "complete") {
$('.popup-with-form').magnificPopup('open');
document.getElementById("CalcSum").innerHTML = XmlHttp.responseText;
document.getElementById("CalcSumPopup").innerHTML = XmlHttp.responseText;
}
}
PS I know many of these questions pop up, and I tried different ways of doing thing, but since I'm "code-challanged" and do not know JQuery or JS I can't figure it out. I know there is a .one "thing" in JQuery, but don't understand how to make it work.
If you want to execute this line only once per browser session you can use sessionStorage. When you set a variable on sessionStorage it keeps its value until the browser closes (e.g. until you close Google Chrome).
So you can do something like:
if (!sessionStorage.alreadyClicked) {
$('.popup-with-form').magnificPopup('open');
sessionStorage.alreadyClicked = 1;
}
Be careful with sessionStorage because it can only store string values.
If you want the line to be executed only once per page session (which means once every page refresh) then you can use any variable and set it to true to remember you already executed the line:
if (!window.alreadyClicked) {
$('.popup-with-form').magnificPopup('open');
alreadyClicked = true;
}
Try
Edit, v2
I read about .one but could not figure it out :( ... I actually need
it to run once ONLY when CALCULATE button is pressed. – Roofing
Calculator
html
<!-- removed `action="javascript:GetInfo();"
, accept-charset="UNKNOWN"
, enctype="application/x-www-form-urlencoded"
, method="post"`
from `form` attributes -->
<form id="formcalc" style="text-align: left;">
<!-- changed `input` `type` to `button` -->
<input name="calculate" type="button" value="Calculate" />
</form>
js
$("#formcalc > input[name='calculate']")
.one("click", function(e) {
e.stopPropagation();
GetInfo();
});
v1
$("a.popup-with-form").one("click", function(e) {
// do stuff, once
// i.e.g.,
// `XmlHttp.onreadystatechange = StateChanged;` at `ShowSum()`
$(e.target).remove(); // remove element when `click`ed once
});
jsfiddle http://jsfiddle.net/guest271314/7K3tn/
See http://api.jquery.com/one/
Please use below.
disableOn
null
If window width is less then number in this option - lightbox will not be opened and default behavior of element will be triggered. Set to 0 to disable behavior. Option works only when you initialize Magnific Popup from DOM element.
Can also accept Function as a parameter, which should return true if lightbox can be opened andfalse otherwise. For example:
disableOn: function() { if( $(condition) { return false; } return true; }
Is there a way I can trace what the user does on the page. Mainly I want to do the following thing: User opens a page, if he does not click anywhere on that page to show a tooltip (i'm using tipsy) guiding him which parts are clickable.
So far I've tried several stuffs:
I have set tipsy to show manually: trigger:manual;
I made a variable that equals false until the user clicks those
clickable items (divs and images)
If the variable is false, show the tooltip (tipsy).
But I'm missing something because this doesn't work. Here is my code.
$(document).ready(function() {
var userClick = false;
function showTooltips() {
$(document).ready(function()) {
if(userClick === false)
$('.nickname .pseudo-white').tipsy('show');
}
setTimeout(showTooltips(), 5000);
});
Try getting rid of the extra call to $(document).ready, and pass the function name to setTimeout rather than calling it with ()
$(document).ready(function() {
var userClick = false;
function showTooltips() {
if(userClick === false)
$('.nickname .pseudo-white').tipsy('show');
}
setTimeout(showTooltips, 5000);
});
I've 3 divs (#Mask #Intro #Container) so if you click on Mask, Intro gets hidden and Container appears.
The problem is that I just want to load this only one time, not every time I refresh the page or anytime I click on the menu or a link, etc.
How can I do this?
This is the script I'm using for now:
$(document).ready(function(){
$("div#mask").click(function() {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
});
});
Thank you!
You can try using a simple counter.
// count how many times click event is triggered
var eventsFired = 0;
$(document).ready(function(){
$("div#mask").click(function() {
if (eventsFired == 0) {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
eventsFired++; // <-- now equals 1, won't fire again until reload
}
});
});
To persist this you will need to set a cookie. (e.g. $.cookie() if you use that plugin).
// example using $.cookie plugin
var eventsFired = ($.cookie('eventsFired') != null)
? $.cookie('eventsFired')
: 0;
$(document).ready(function(){
$("div#mask").click(function() {
if (eventsFired == 0) {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
eventsFired++; // <-- now equals 1, won't fire again until reload
$.cookie('eventsFired', eventsFired);
}
});
});
To delete the cookie later on:
$.cookie('eventsFired', null);
Just point to an empty function once it has been called.
var myFunc = function(){
myFunc = function(){}; // kill it
console.log('Done once!'); // your stuff here
};
Web pages are stateless in that they don't hold states between page refreshes. When you reload the page it has no clue what has happened in the past.
Cookies to the rescue! You can use Javascript (and jQuery has some nice plugins to make it easier) to store variables on the client's browser. Store a cookie when the mask is clicked, so that when the page is next loaded it never shows.
this code with will work perfect for you and it is the standard way provided by jquery to bind events that you want to execute only once
$(document).ready(function(){
$("div#mask").one('click', function() {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
});
});
I have the following JQuery code which does similar functionality like Stackoverflow where the user clicks on the comment link and it displays the comments or in this case replies to a member's status update, generally it works great except when a member posts a new status update which updates the list of status updates using an ajax async postback in ASP.net MVC.
What happens is if you click on the new item in the list it brings them to a new page instead of doing what the JQuery is suppose to do.
<script type="text/javascript">
$(function() {
$("a[id ^='commentLink-']").click(function() {
match = this.id.match(/commentLink-(\d+)/);
container = $("div#commentContainer-" + match[1])
container.toggle();
if (container.is(":visible")) {
container.load($(this).attr("href"));
} else {
container.html("Loading...");
}
return false; //Prevent default action
});
});
</script>
Note: I think what is causing it is the fact that the new item in the list isn't actually on the page as the list was updated through the ajax so the new html isn't there until the page is refreshed.
Update Okay how would I use this live/event functionality that Paolo Bergantino spoke of in his answer to trigger an ASP.net MVC ActionResult?
Check out the new Events/live feature in jQuery 1.3
Binds a handler to an event (like click) for all current - and future - matched element.
So as you add new items, jQuery should add the click event to them with this.
If for some odd reason you do not want to upgrade to jQuery 1.3, you can check out the livequery plugin.
EDIT in response to update:
The actual code to use .live would be something like this:
$(function() {
$("a[id ^='commentLink-']").live('click', function(event) {
match = this.id.match(/commentLink-(\d+)/);
container = $("div#commentContainer-" + match[1])
container.toggle();
if (container.is(":visible")) {
container.load($(this).attr("href"));
} else {
container.html("Loading...");
}
event.preventDefault();
});
});
The changes that were made are mostly in the 2nd line, where
$("a[id ^='commentLink-']").click(function() {
was replaced by
$("a[id ^='commentLink-']").live('click', function(event) {
I am now also receiving the argument event to use for event.preventDefault(); which is the way you are recommended to stop events by jQuery. If return false; does the trick, though, you can keep that.
I haven't used .live yet, but I think that should do the trick. Make sure that you get jQuery 1.3 in your server before trying this, though. :)