Calling .mouseenter( ) is working even though .click( ) won't trigger animation - javascript

In HTML, I have a button with the id of "submit1"
<div id="first">
<form>
<input type="radio" name="school" value="pitt">Pitt<br>
<input type="radio" name="school" value="memphis">Memphis<br>
<button id="submit1">Submit</button>
</form>
</div>
Now in Jquery, I try to use a .click() to trigger the div "first" to fadeOut, like so:
$(document).ready(function() {
$('#submit1').click(function(){
$('#first').fadeOut('slow');
});
});
Weirdly enough, nothing happens when I click submit. I thought maybe it wasn't calling my .js file, but alas, when I change it to a .mouseenter( ), it works perfectly to trigger a fadeOut of the div.
$(document).ready(function() {
$('#submit1').mouseenter(function(){
$('#first').fadeOut('slow');
});
});
I saw an old Stack Overflow post where they used alert instead of an animation, so I tried that too during debugging and it still worked. It is literally just animations that seem to break things (tried .slideToggle, .slideDown, etc. just to check). Thanks!

Since the submit button is inside a form element, the default click behavior is to submit the form to the server. Internally, the JS is being called but this also causes the whole page to refresh so you don't see the animation happening. In order to prevent this, change your code to prevent the default submit behavior:
$('#submit1').click(function (e) {
e.preventDefault();
$('#first').fadeOut('slow');
});

Related

How do I check when an input is changed?

I tried using the "input" event on the text box but it doesn't work. I've read a few posts on Stack Overflow but none of them worked.
Here's my most recent HTML and Javascript code using onchange:
function updateResults(){
document.write("Wroks");
}
<input id="search-box" onchange="updateResults();"> </input>
I tried changing HTML to onchange="updateResults;" but didn't work.
I also tried changing HTML to onchange="updateResults(event);" and then Javascript to function updateResults(event){...}
Nothing that I tried worked.
Looks fine to me. If you make any changes then you'll see the function get called as soon as you lose focus (onchange only happens when you blur). If you want more immediate results you can use oninput instead, like so:
function updateResults(){
document.write("Wroks");
}
<input id="search-box" oninput="updateResults();" />
Another way is to use event listeners, if you want to keep javascript out of the markup:
function updateResults() {
document.write("Wroks");
}
document.getElementById("search-box").addEventListener("input", updateResults);
<input id="search-box" />
The above however will only work if the DOM has already been loaded when the javascript is run. You could put it in an onload event, or include the javascript after the DOM markup.
Alternatively you could attach the event listener to the document and check for the ID whenever the event is triggered. There are pros and cons to this method. Since the function doesn't attach to the element directly, the DOM will not need to be loaded yet. If the element is removed and a new one with the same ID is added, it will still work. Also, if you add your content dynamically after the page loads, you will not need to worry about attaching the listener later. However, this function will be called every time any input on the page is registered, which theoretically could slow the page down (e.g. if you have a lot of these types of listeners), although probably minimally.
function updateResults() {
document.write("Wroks");
}
document.addEventListener("input", function(e) {
if (e.target.id === "search-box") {
updateResults();
}
});
<input id="search-box" />
document.write("Wroks"); will replace everything in your window with "Wroks".
try this:
<input id="search-box" onchange="updateResults();"> </input>
<script>
function updateResults(){
console.log('Works');
}
</script>
You also may want to consider using jQuery because then you could do a lot more out of the box with this. for example:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<input id="search-box">
<script>
$('#search-box').on('change',function(){
console.log($(this).val());
})
</script>
The above code will give you the value of the input on change.
try:
<input id="search-box" onchange="javascript:updateResults();"> </input>
or:
<input id="search-box" onchange="javascript:document.updateResults();"> </input>
It is a bit unclear whether you want the JavaScript to fire when the user finishes updating the textbox, or after every character is input.
This will fire after the user "commits" to their input, often by clicking something else.
HTML
<input id="search-box" />
JavaScript
function updateResults(){
alert("Works");
}
document.getElementById("search-box").addEventListener("change", updateResults, false);
This will fire after every key is pressed (and so forth).
HTML
<input id="search-box" />
JavaScript
function updateResults(){
alert("Works");
}
document.getElementById("search-box").addEventListener("input", updateResults, false);
As far as I understand the question, you want to know when a user types in one letter/number and then call your function.
This would be "onkeyup":
<input type="text" onkeyup="myFunction()">
You could also use onkeydown. See also http://www.w3schools.com/jsref/dom_obj_event.asp
When you use onchange, this works too, but only after the input is finished. Either when the user presses enter or after leaving the textbox.
If all of this doesn't work, turn on Javascript in your Browser.

Unable to submit a form on the first click event

Well, I spent hours on this problem and scanned the whole stackoverflow, but still do not know what to do. But what really gets me nuts is that such a trivial and the simplest in the world thing is not working. So, what I have now is a form with inputs and a button:
<form id="frm" action="/accent/login/enter/">
{% csrf_token %}
<div draggable="true" id="panel" class="panel" title="">
<input id="login" name="login" type="text" placeholder="" class="required" /> <br/>
<input id="pswd" name="pswd" type="password" placeholder="" class="required" /> <br/>
<button id="btn" value="">ENTER</button>
</div>
</form>
And I have this code which is supposed to send the form:
$('#btn').one("click",function(){ // prevent from multiple submits
$('#frm').validate({ // validate the form before submission
...general stuff: rules, messages, etc
submitHandler:function(form){
$('#frm').submit(function(e){ //submitted on the second click. why???
...prepare parameters for ajax call
$.ajax({
type:'POST',
...general stuff
});
e.preventDefault();
})
}
});
});
The problem is, when a user clicks on submit button for the first time, then the form is not submitted, if, however, he or she clicks it for the second time, then it is submitted ok. I can't understand the logic behind such behaviour implemented in jquery. Besides, I should say, that I have tried many other tricks, like:
form.submit(...
$('#frm')[0].submit(...
But they work not as expected, as if there is no callback function - I'm redirected to the url, but do not stay on the same page - just what I expect from e.preventDefault. I guess there is some sacred method or magic properties in jquery that I should use to make it work (like method one which prevents terrible multiple submits). But at this moment I do not know them.
EDIT
I also tried this trick:
jQuery('#frm').submit(...
but it works exactly like the first method - $('#frm').submit(...
EDIT
I found the third method which works like the previous one:
$('form').submit(...
To sum up, I have three different methods, but all of them work only when a user clicks on the button for the second time. And I have two methods that work in a standard manner and do not make it possible to use a callback function.
The problem is, you are registering for form submit after the form validation.
so,
1) On first click of button validation, the submit event is registered to a handler.
2) On second click of the button, the registered handler will be called. that is why it get submitted on second click. But note that you are registering again for the submit event. which means, on third click the form will be submitted twice, on fourth click the form will be submitted thrice..... and so on...
Solution
1) remove the $("#frm").submit() code from the submitHandler and put it outside.
2) use e.preventDefault(); in $("#frm").submit() so the default action is prevented and page doesn't get reloaded.
3) put the AJAX code directly in submitHandler
$('#btn').one("click",function(){ // prevent from multiple submits
$('#frm').validate({ // validate the form before submission
...general stuff: rules, messages, etc
submitHandler:function(form){
...prepare parameters for ajax call
$.ajax({
type:'POST',
...general stuff
});
}
});
});
$('#frm').submit(function (e) {
e.preventDefault();
});
I guess you are using the jqueryvalidation plugin. If it's true, then your using of $().validate() may be wrong.
The $().validate() function is to initialize the validation, it tells the script how to validate the form value and what to do if the validation is passed(the submitHandler property).
So maybe you should edit your code like this:
<form id='frm'>
...
</form>
$('#frm').validate({
//...general stuff: rules, messages, etc
submitHandler: function (form) {
//blahblah before doing the submitting...
form.submit();
}
});
$('#btn').one('click', function (){
$('#frm').submit();
});
But, actually there's still a problem with your $btn.one() event handler: if you click the button while the form values doesn't meet your validation rules, the one chance to fire the handler is consumed and even if you re-input the right value, the button will never response your clicking unless refreshing the page.
So maybe you should check your business logic again and redesign the form submitting flow, but that's not what this question is discussing, good luck ;)

jquery click not getting triggered on IE

I've seen a lot of posts on this issue but none of the solutions worked. The following..
<script type="text/javascript">
$(document).ready(function() {
$("a.login_linkedinbutton").click(function(){
$("#signup-form").submit();
return false;
});
});
</script>
is what I have in the body tag of a page. Also in the body is the form, the html of which in IE shows up like this..
<form accept-charset="UTF-8" action="/auth/linkedin" class="well form-inline" id="signup-form" method="post">
<a class="login_linkedinbutton" href="#">Login using Linkedin</a>
</form>
in IE8, when the link within the form is clicked, the jquery is not getting triggered. It's working in Chrome and Firefox. I've tried:
1) Using the live event to bind the click action
2) Moved the jquery out of the page and into rails assets
Any ideas what else to try?
Use <input type="submit" value="Login using Linkedin">
Why create problems by using a non-standard element and then trying to recover from it?
If you want it to LOOK like a link, just style the button. But why do it? It's poor user experience to suggest the user to go to another page while they're submitting a form. Most users avoid clicking links when they have a form filled because they're afraid of loosing what they just typed.
If you insist using the link, you could try this:
var onLinkedInLogin = function(e){
e.preventDefault(); // stops the link processing
$("#signup-form").submit();
// add return false; if you want to stop event propagation also
// equivalent to calling both, e.preventDefault() and e.stopPropagation().
};
$(document).on('click', 'a.login_linkedinbutton', onLinkedInLogin);
The reason I'm suggesting using .on() instead on .click() is that I guess that on IE, the a.login_linkedinbutton is not present in the DOM when you call the .click().

jQuery Tools Overlay - Two buttons with different close conditions

I have the following jQuery Tools overlay:
<div id='editDescriptiontOverlay' class='overlay'>
<input type='text' class='description'/>
<button class='save'>Save</button>
<button class='close'>Cancel</button>
</div>
Background info: The HTML for this overlay is static. I have a list of items each having their own Edit link. When a given Edit link is clicked, the overlay is generated by calling: $('a[rel=#editDescriptionOverlay]').overlay( { ... } ); and the input is populated with the respective text.
The Save button needs to validate the text in the input element and close the overlay if and only if the validation is successful. Otherwise, the overlay must remain open. The Cancel button simply closes the overlay without validation.
The validation logic has been independently verified to work.
I've tried setting the onBeforeClose event during overlay generation as a means of validation. Taking this approach, both the Save and Cancel buttons needed the same class .close. Unfortunately, the condition applies to all .close elements in the overlay so even the Cancel button was validating.
I've also tried binding a click event to the Save button immediately after generating the overlay, like so:
$('.save', $('#editDescriptionOverlay'))
.unbind('click')
.bind('click', function() {
if (validateText) {
console.log("Validation passed.");
$('a[rel=#editDescriptionOverlay]').overlay().close();
}
else {
console.log("Validation failed.");
}
});
The console.log's confirm that the validation is working, but the overlay doesn't close.
Any insight is appreciated, thanks.
For jquery widgets, public methods should be called as follows:
$('a[rel=#editDescriptionOverlay]').overlay("close");
wherein close is the method name that you wish to call.
If a method accepts parameters, then, these should be added as parameters right after the method name.
Updated:
I am sorry. I just had time to check what jQuery Overlay Tools is and I am mistaken. This is not similar to any jQuery widget, hence, my comment above will also not work for this case. I tried your code above and it worked. The overlay was closed. But, when I tried it with multiple <a rel="#editDescriptionOverlay">, which I think is what you did. It did not work. My suggestion would be to use just one <a rel="#editDescriptionOverlay"> and use a dummy anchor element for the Edit link, which when clicked would trigger a click to <a rel="#editDescriptionOverlay">. You can do something like this:
<script type="text/javascript">
$(document).bind("ready", function(e){
$("a[rel]").overlay();
$('.save', $('#editDescriptionOverlay')).unbind("click").bind("click", function(){
if (validationValue){
$("a[rel=#editDescriptionOverlay]").overlay().close();
}
});
});
function clickThis(){
$("a[rel=#editDescriptionOverlay]").trigger('click');
return false;
}
</script>
Edit1
Edit2
<a rel="#editDescriptionOverlay">Dummy</a>
<div id='editDescriptionOverlay' class='overlay'>
<input type='text' class='description'/>
<button class='save'>Save</button>
<button class='close'>Cancel</button>
</div>
I'd prefer binding an event to the save button (the second one you mentioned). Actually your code looks fine, except that you probably don't need to bind the event to $('#editDescriptionOverlay') and you have typo in your html markup above (<div id='editDescriptiontOverlay' should be <div id='editDescriptionOverlay').
See here for an example.

Javascript function not being called at all

I made the following small Javascript script to enable some form elements on my page:
function unHide()
{
if($('#UserName').val() == "")
{
alert('Please Enter a User Name first');
}
else
{
$('#radio-choice-1').checkboxradio('enable');
$('#radio-choice-2').checkboxradio('enable');
$('#radio-choice-1-board').checkboxradio('enable');
$('#radio-choice-2-board').checkboxradio('enable');
$('#TransNum').textinput('enable');
$('#UserContinue').remove();
$('#nextButton').show();
}
}
The problem is, this isn't being called when the correct button is clicked. Even the alert doesn't show up. Here is the HTML:
<label for="UserName" style="vertical-align: top;">User Name:</label>
<input type="text" name="UserName" id="UserName" placeholder="Ex: LesniakBjEVS101" />
...
<a data-role="button" data-icon="check" data-mini="true" id="UserContinue"
style="float:right;" onclick="javascript:unHide(); return false;">Continue...</a>
...
<section id="nextButton" hidden>
<a href="salamanderSelect.html" data-role="button" data-icon="forward"
data-mini="true" style="float:right;">Next</a>
</section>
The problem I am encountering is when I click on the submit button, absolutely nothing happens. I am not getting any feeback from the Javascript, nor anything.
Any help would be greatly appreciated!
Thanks!
Edit:
After trying out suggestions, I still am unable to get the javascript to do anything. I have tried multiple browsers, but still nothing.
And I just had this working yesterday too...without any changes to the code too
Edit 2:
Apparently it works if my script is the last thing in the HTML file, even outside of the tags.
While onclick doesn't need javascript:, it should still work in many browsers. Here is a jsfiddle of your example: http://jsfiddle.net/ukWcp/2/
Only use javascript: in an href.
While i suggest debugging using the javascript console and debugger in firebug or chrome, others have mentioned using an all javascript solution for your bindings. That is preferrable.
As you're using jQuery already, why not use it to attach your events, rather than using the clunky onclick attribute.
<a data-role="button" data-icon="check" data-mini="true" id="UserContinue"
style="float:right;">Continue...</a>
$("#UserContinue").click(function(e) {
if($('#UserName').val() == "") {
alert('Please Enter a User Name first');
}
else {
$('#radio-choice-1').checkboxradio('enable');
$('#radio-choice-2').checkboxradio('enable');
$('#radio-choice-1-board').checkboxradio('enable');
$('#radio-choice-2-board').checkboxradio('enable');
$('#TransNum').textinput('enable');
$('#UserContinue').remove();
$('#nextButton').show();
}
e.preventDefault();
});
$(document).ready(function() {
$("#UserContinue").click(function() {
if($('#UserName').val() == "")
{
alert('Please Enter a User Name first');
}
else
{
$('#radio-choice-1').checkboxradio('enable');
$('#radio-choice-2').checkboxradio('enable');
$('#radio-choice-1-board').checkboxradio('enable');
$('#radio-choice-2-board').checkboxradio('enable');
$('#TransNum').textinput('enable');
$('#UserContinue').remove();
$('#nextButton').show();
}
return false;
);
});
If you're using jQuery, why not fully use it? The return false at the end stops the click event from continuing if that was what you desired.
Edit:
You say in your original post "The problem I am encountering is when I click on the submit button, absolutely nothing happens. I am not getting any feeback from the Javascript, nor anything."
Yet you have attached a click event to your incomplete anchor tag (it's missing the href). So are you expecting the behavior to trigger on clicking the submit button or clicking the anchor tag? If you are expecting the trigger to fire on clicking the submit button, then you need to change $("#UserContinue") to reference the submit button and not the anchor tag. Or use the .submit() event handler instead of .click(), http://api.jquery.com/submit/.
If this is not the issue, then I suggest editing your post to include all of your code and saying what behavior you expect after clicking which elements.
Edit 2:
I believe you are not wrapping your jQuery around the .ready() function, please see the revised code snippet that now includes .ready(). .ready() ensures the DOM is fully loaded before working with your jQuery.
Keep your function and add the event handler to your javacript and NOT in markup:
$(document).ready(function() {
$('#UserContinue').click(function() {
unHide();
});
});
short version:
$(document).ready(function() {
$('#UserContinue').click(unHide);
});

Categories

Resources