Javascript function only executing one line - javascript

I've got a div that starts out as hidden, and shows up when a button is clicked. There is another button on the div, and the onclick event calls this function:
function popuppage2OK() {
alert("you clicked ok!");
var x = new Object();
x.name = $("#boxforname").val(); //this is a text input
x.option = $("#boxforoption").val();//this is a text input
alert("hiding newfactorpage2");
$("#popupform").hide(); //this is a div containing the text inputs and the button with the onlcick event that calls this function
alert("popupform hidden");
displaystuff(); //another function ive written that needs to be called
alert("this is after the display attempt");
}
My probelm is that the only line that seems to execute is the line to hide the div. None of the alert boxes appear, and the displaystuff() function doesn't get executed, but the div does go back to being hidden. Any thoughts on why lines of code might get skipped like that?

When do you attach the eventhandler to the button inside the div ?
You should do it after the page has done loading, so in Jquery you can do something like:
$(document).ready(function () {
//attach the eventhandler here
})

Usually this kind of behavior happens when you've got an error in your javascript. Check to ensure that all of your selectors are valid and that there aren't any errors elsewhere.

Related

Trigger validation after first submit, then after after every keystroke on input element

I am using jquery validation for everything I'm about to talk below.
so I have an input field, lets call it email. I also have a submit button for this form. Now by default the error message for email field will not kick in until I hit the submit button. Then whenever I type it will show/hide error message dependant on if it is a valid email. This check happens with every key stroke and this is a very important distinction to make so that you would understand my problem I posted below.
Now I have a background colour on the input, it is suppose to be green when validation has passed and red when it has failed. I have this part working, let me show you how I did it:
window.onload = function () {
$(".js-validate-circle").on("input", function () {
UpdateValidationCircle(this);
});
}
function UpdateValidationCircle(e) {
if ($(e).valid()) {
$(e).parent().addClass("active");
} else {
$(e).parent().removeClass("active");
}
}
The active class is what determines if its green or red. There is styling that is irrelevant I think to the question so I wont post it here.
Here is my problem: When the page loads and I start typing, it forces validation to trigger and error messages start coming in before I click the submit button for the first time. I am trying to prevent this. I want the color the start changing on typing only after the submit button was hit. Functionality of my red/green background should match jquery validation messages.
How would I accomplish something like this? I tried using on change but then the validation triggers only when the box loses focus.
jQuery(function($) { // DOM ready and $ alias in scope
// Cache elements
var $circle = $(".js-validate-circle");
var addedInputEvent = false; // Just a flag to know if we already added the evt listener
// On form submit....
$("#form").on("submit", function(event) {
// Prevent default form submit
event.preventDefault();
// Check immediately
$circle.each(UpdateValidationCircle);
// If not already assigned, assign an "input" listener
if(!addedInputEvent) {
addedInputEvent = true;
$circle.on("input", UpdateValidationCircle);
}
});
function UpdateValidationCircle() {
var $el = $(this);
$el.parent().toggleClass("active", $el.valid());
}
});
Use the keyup event instead:
$(".js-validate-circle").on("keyup", function () {
...
Assuming .js-validate-circle is your input... or if it is the form:
$(".js-validate-circle").on("keyup", "#id-of-the-input", function () {
...
If this doesn't work, we are going to need to see validate()s code and some markup.

Simple but strange HTML, jQuery issue. Function loops with no reason

I wrote the code in javascript (jQuery), that allows a user with every click of a button to create a "box" on the web site and to get an alert message after this box was clicked.
It works like this:
1) When the user presses the button "Add (#addBox)" - jQuery appends a new line to the HTML file, that creates the "box" (it looks like a box because of the CSS code).
2) If the user presses the box, it sends out the alert message "Hello".
But if I add multiple boxes and then click on the first one, instead of sending out one alert message, it sends it out as many time as the number of boxes been created.
Example:
1) I have 1 box. By pressing on it, I receive 1 alert message.
2) I have 2 boxes. By pressing on the top one, I receive 2 alert messages.
By pressing on the second one, I receive 1 message.
3) I have 3 boxes. By pressing on the top one, I receive 3 alert messages.
By pressing on the second one, I receive 2 messages.
By pressing on the third one, I receive 1 message.
The function of sending an alert message is looping for some reason.
And so here is the code:
function addBox()
{
$("#addBox").on("click", function () {
$("#addBox").append('<div class="desiredBox">Say Hello</div>');
}
boxCount();
});
}
function boxCount()
{
$(".desiredBox").on("click", function () {
alert("Hello");
});
}
Any ideas, how to make them send only one message each, preventing the function "boxCount()" from looping?
Every time the function boxCount is invoked an event handler is added to existing elements i.e. ".desiredBox". thus you are getting multiple alerts.
As you are creating elements dynamically.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
General Syntax
$(document).on(event, selector, eventHandler);
Ideally you should replace document with closest static container.
Complete code
$("#addBox").on("click", function () {
$("#addBox").append('<div class="desiredBox">Say Hello</div>');
});
$(document).on('click', '.desiredBox', function(){
//Your code
});
Use event delegation so you don't keep adding the click event to .desiredBox over and over again:
$(document).on("click", "#addBox", function () {
$("#addBox").append('<div class="desiredBox">Say Hello</div>');
$(".desiredBox").trigger("click");
});
$(document).on("click", ".desiredBox", function () {
alert("Hello");
});

asp.net & jquery fade effect

I have a page with a button named "projects",a div id="main"> and a label inside it. The main text of the page is written in the label. When I press the button, the text changes, using the label.text = .. inside the button_Click event inside C#. This is the button:
<asp:Button ID="projects" runat="server" OnClick="projects_Click"/>
What I want to do is to add a fading effect when changing the text. I saw that the easiest way was to use jQuery. I added this:
<head>
<script type='text/javascript'>
$(function () {
$("#projects").click(function (e) {
e.preventDefault();
$('#main').fadeOut(1000);
$("#main").fadeIn(1000);
});
});
</script>
</head>
What happens now is that if I press the projects button, the text only fades out and then it fades in, but it's not changed, projects_Click isn't executed. If I remove e.preventDefault(); , the text changes but there is no fading effect. How can I make them work together? Old text fades out, projects_Click is executed and fadeIn comes into action.
If you can move following part(mentioned in your question) to JS , then it will work..
When I press the button, the text changes, using the label.text = .. inside the button_Click event inside C#.
Lets say that text is XYZ, then you can do it like this.
$(function () {
$("#projects").click(function (e) {
e.preventDefault();
$("#main").html("XYZ");
$('#main').fadeOut(1000);
$("#main").fadeIn(1000);
});
});
And if that is calculated on server side, then move those code block to a webmethod and do a ajax call in .click event and in success handler set text and do animations.
Tutorial for above - http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
OR
I have one more suggestion .
Define a javascript function in aspx. Like following.
function animate(){
$('#main').fadeOut(1000);
$("#main").fadeIn(1000);
}
In button click handler, after setting label text, use following line to initiate animation on page load ( after page postback / button click event handler completes).
Page.ClientScript.RegisterStartupScript(this.GetType(), "scr", "<script>animate();</script>");
NOTE - you can not simultaneously use server side code to set some text or do preventDefault to set animation in JS. This will make you in catch 22 situation.
The text is too large to be put inside the script.
Since it was made for one key, I eventually had to make it work for every each key on the page.
I did this:
<head>
<script type='text/javascript'>
$(function () {
$('#main').hide;
$("#main").fadeIn(1000);
});
});
</script>
</head>
This function executes every time the page reloads and since this is a one page site with only the main text changing in the middle, it is executed on every button click.
Aspx changes the text, jQuery immediately hides it and it fades it in slowly. There is no fade out, but this method works great also and thinking about it, I like it better.

Show alert when focusout, only once

I'm having a little problem with my script below. I'm trying to create a script where you can write some text in an input field, and when you have typed some text, you will get an alert when focus-out. The alert should only show, if the input contain text.
But the problem is, that if you're trying to write some text, delete it and then focus-out of the input, the alert do not show next time, when you actually have written something and then focus-out.
Right now, the alert function always will "disappear" when focus out, no matter if you have written any thing or not.
I have tried to add a var already_alert_me_once = true before the alert, and then put everything inside an: if(already_alert_me_once == false), but that didn't do the trick.
I have also tried to change $('#title').focusout(function() with $('#title').one('focusout', function() which almost did the trick.
Here is my current script:
// When focus on title
$('#title').focus(function () {
// Check if empty
if (!$(this).val()) {
$('#title').one('focusout', function () {
if ($(this).val()) {
alert("YEP");
}
});
}
});
..and Here's a Fiddle
So my question is; How to I do so the alert only appears when you have written something, and after that never again (unless you reload the page).
Hope you can understand what I mean.
Thanks - TheYaXxE
You can unbind the focus using:
$('#title').unbind('focus');
Working Fiddle
pretty much the easiest solution, no need for .one or focus events :)
$('#title').blur(function() {
if( $(this).val() ) {
alert('!!');
$(this).unbind('blur');
}
});
http://jsfiddle.net/T7tFd/5/
instead of putting the variable "already_alert_me_once" inside the function, make it a global variable. that way the scope will be maintained. you could also add an attribute to the #title that indicates that it has already been clicked, then check to see if that attribute exists before executing the code.

Button needs to be clicked twice to trigger function

I know this would be difficult to understand but please give a try.
Have a look at the screenshot.
The small input box's name is murl.
add() is used to submit the form. if murl is empty the form has to be submitted directly, if its not empty the murl entry has to be checked against the database if it exists. if it doesn't exist add() is called.
The problem is the button has to be clicked twice to trigger the function.
The code on the button is:
<button type="button" value="My button value" onclick="javascript: niju();" name="microsubmit" id="microsubmit">button</button>
the JavaScript which that button calls is:
function niju()
{
var flag=1;
var micro=document.getElementById('murl').value;
$('#microsubmit').click(function()
{
if(micro=="")
{
add();
}
else
{
//remove all the class add the messagebox classes and start fading
$("#msgbox")
.removeClass()
.addClass('messagebox')
.text('Checking...')
.fadeIn("slow");
//check the username exists or not from ajax
$.post("<?php echo SITE_ROOT;?>inc/user_availability.php",
{ murl: $("input:murl").val() },
function(data)
{
if(data=='no') //if username not avaiable
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this)
.html('This User name Already exists')
.addClass('messageboxerror')
.fadeTo(900,1);
flag=0;
});
}
else
{
$("#msgbox")
//start fading the messagebox
.fadeTo(200,0.1,function()
{
//add message and change the class of the box and start fading
$(this)
.html('Username available to register')
.addClass('messageboxok')
.fadeTo(900,1);
flag=1;
add();
});
}
});
}
});
if(micro=="" && flag==1)
{
add();
}
}
Screenshot:
It has to be clicked twice because you are defining #microsubmit's click event inside the function. So the first time you click you bind the event handler, and the 2nd time the event handler is in place and gets fired. I haven't gone over the logic behind what you're trying to accomplish but my guess is that if you move the event binder outside the function and make sure all your variables are in the right scopes then it'll work.
The first time you load the page, the click handler is not hooked to the button, is only until you click the button the first time that you are calling the niju() and hooking the click event. You need to do something like
$(document).ready() {
niju();
}
and remove the onclick from the button declaration
Move your flag out of the function niju.
var flag=1;
function niju()
{
}

Categories

Resources