.click() not working when using jQuery - javascript

I have a normal js script which has been working since the start of my project. But now for some reason when I click on buttons nothing works at all, no response from the clicking event(note this used to work) and nothing displays in the console log stating if there is an error of some sort... the script just doesn't respond...
Here is the HTML:
<script type="text/javascript" src="js/myscript.js"></script>
<form>
<input type="text" name="signinemail" id="signinemail" placeholder="Enter Email">
<input type="password" name="signinpassword" id="signinpassword" placeholder="Enter Password">
<input type="submit" id ="siginsubmit" name="siginsubmit" value="Sign In">
</form>
Here is my javascript:
$(document).on('pageinit',"#sellbookpage",
function()
{
$("#siginsubmit").click
(
function()
{
alert("hello");
}
);
}
);
Note I am making use of jQuery Mobile

The pageinit event is only available if you use jQuery Mobile. Are you still using that? Otherwise you should use $(document).ready( ... ).

The winning answer to my problem was nothing to do with any of the above posts mentioned above! What was causing the problem was I was using the jQuery mobile, jQuery and Twitter Bootstrap. As soon as I commented out the link to the bootstrap css everything started to work as it used to. Thus there must be a conflict between Twitters Bootstrap and either jQuery or jQuery Mobile.

have u tried using live()
$("#sellbookpage").live('pageinit', function() {
$("#siginsubmit").click(function(){
alert("hello");
});
});

From http://api.jquery.com/on/#on-events-selector-data-handlereventObject:
When a selector is provided, the event handler is referred to as
delegated. The handler is not called when the event occurs directly on
the bound element, but only for descendants (inner elements) that
match the selector. jQuery bubbles the event from the event target up
to the element where the handler is attached (i.e., innermost to
outermost element) and runs the handler for any elements along that
path matching the selector.
siginsubmit is an input (which cannot contain descendant elements let alone descendant elements with id="sellbookpage") so the selector string is not matching anything and the click event is never reaching the siginsubmit input.
Change it to this:
$(document).on('pageinit', function () {
$('#siginsubmit').click(function (e) {
alert('hello');
e.preventDefault();
return false;
});
});
Working fiddle: http://jsfiddle.net/VG3Eg/

Related

Why is jQuery select event listener triggering multiple times?

Please run this sample in Google Chrome browser.
Stack Snippet
$(function() {
$(":input").select(function() {
$("div").text("Something was selected").show().fadeOut(1000);
alert("Selected");
});
$("button").click(function() {
$(":input").select();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button>Click To Select</button>
<input type="text" value="Some text">
<div></div>
Here why jQuery select event listener is triggering multiple times? Does anyone know the reason behind this? And is there any workaround solution for this without using timeout?
The $(":input") selector is selecting the button too, so it causes recursion. Either use just $("input"), or $(":input:not(button)").
I noticed when the three events are fired, the first doesn't have originalEvent property, so we definitely can dismiss it, and the second two has very similar (however not identical) timestamp. You can store the last timestamp in some variable and in event listener compare it with the event's timestamp. If the rounded values of these two are the same, you can dismiss this event.
$(function() {
var lastTimeStamp;
$("input").select(function(event) {
if (!event.originalEvent ||
lastTimeStamp === Math.round(event.timeStamp)) return;
lastTimeStamp = Math.round(event.timeStamp);
$("div").text("Something was selected").show().fadeOut(1000);
alert("Selected");
});
$("button").click(function() {
$("input").select();
});
});
See updated JS Fiddle.
It appears the issue is a combination of:
the :input selector gets the input and the button, hence multiple events triggered.
even when using just input as the selector there is some odd event propagation being triggered on related elements which is raising the select event handler multiple times.
To avoid both of the above, use input as the selector and also use preventDefault() in the event handler. stopPropagation() may also be required, depending on your HTML stucture.
$(function() {
$('input').select(function(e) {
// e.stopPropagation(); // optional
e.preventDefault();
$('#message').text("Something was selected").show().fadeOut(1000);
console.log('Selected');
});
$('button').click(function() {
$('input').select();
});
});
Working example
UPDATE: We were all fooled. The select() function needs a prevent default.
Rory McCrossan figured it out. Well done mate.
Incidentally, I'm not sure what the benefit of select() actually is! Something like focus() or on('focus',) might make more sense. Not Sure what the context is however. The below still follows:
Why waste time using generalised tag/type selectors which may change? Use an ID, and pick out only the one you want.
If you want to detect multiple, use a class. If you want to use multiple, but figure out which one you clicked, use a class and an ID. Bind with the class, and identify using $this.attr('id').
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button>Click To Select</button>
<input type="text" value="Some text" id="pick-me">
<div></div>
$(function() {
$("#pick-me").select(function(event) {
event.preventDefault();
$("div").text("Something was selected").show().fadeOut(1000);
alert("Selected");
});
$("button").click(function() {
$("#pick-me").select();
});
});

Toggle state of textbox with javascript using a button

I have a form as follows:
<form>
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock" onMouseDown="toggleInput()"></button>
</form>
And javascript code:
function toggleInput(){
if ($("#input").disabled){
$("#input").disabled = false;
}
else {
$("#input").disabled = true;
};
}
What I basically want to do is to check what state (enabled/disabled) the textbox is in, and then toggle the state accordingly. I don't know if the javascript portion even uses the correct syntax to check if the textbox is disabled, but it's what I could think of.
Thanks in advance!
EDIT: Reason as to why I've chosen to use onmousedown instead of onclick to execute the event with the button:
I have chosen to use onmousedown instead of onclick as it makes the app I'm building feel less clunky due to the presence of this feature with onclick: When you click on a button and then drag the cursor away from the button while holding the mouse button down, and subsequently lift your finger off the mouse button when the cursor is in an area away from the button on the webpage, the event will not be executed. Hence, I've chosen to use onmousedown as this is overcome.
Use .prop(), Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element
$("#input").prop('disabled',!$("#input").prop('disabled'))
DEMO
I am not sure why you are using onMouseDown. Use click instead
$("#lock").on("click", function() {
$("#input").prop('disabled',!$("#input").prop('disabled'))
});
DEMO with click
To do it with jQuery try this:
$("#input").prop("disabled", function(i, v) { return !v; });
Your existing code doesn't work because DOM elements have a .disabled property, but jQuery objects do not.
I'm not sure why you're using onmousedown instead of onclick for the button, but either way if you're going to use jQuery I'd recommend removing the inline event attribute in favour of binding the handler with jQuery:
$("#lock").on("click", function() {
$("#input").prop("disabled", function(i, v) { return !v; });
});
(You'd need to include that code either in a script block at the end of the body or in a document ready handler.)
Demo: http://jsfiddle.net/a7f8v/
You should append the event handler with jQuery instead of an onMouseDown event. The syntax could look like this:
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock"></button>
JavaScript:
$(document).ready(function() {
$("#lock").click(function() {
var input = $("#input");
input.prop('disabled',!input.is(':disabled'))
});
});
Example

Jquery unable to find form inputs to given form id

I'm attempting to run a function on sumbit of a reply form on my website.
These forms are created by Javascript after the page load, so the Jquery is using a live function to react to the click of the ".replyformsubmit" class of button.
I need the script to record the input values of the form, but it seems unable to do so.
Currently the ID of the form which houses the button is found, but using it to try and find the input values seems fruitless, it's probably a school boy error but I can't seem to suss it.
Any help would be great.
The Jquery:
$(".replyformsubmit").live("click", function(){
var curform = $(this).closest('form').attr('id');//what form is the current one?
var comment = $('#' + curform + ' > input[name=comment]"').val(); //comes out as undefined
var replyingSerial = $('#' + curform + ' > input[name=replyingSerial]"').val(); //comes out as undefined
...
The script seems unable to find what comment and the replyingSerial are.
The HTML for a standard example form is:
<form action="com.php" method="post" id="replyform_quickreply_1345291318.6107" class="replyform">
<textarea name="comment" type="text" id="commenttextquickreply_1345291318.6107">
</textarea>
<br>
<input type="submit" value="send!" class="replyformsubmit">
<input type="hidden" style="visibilty: hidden;" name="replyingSerial" value="1345291318.6107"></form>
A couple of things. Comment is a textarea, not an input, so if you want to find it you need to use textarea[name=comment].
Second, you can use parent() and find to make your code a little cleaner:
$(".replyformsubmit").on("click", function(){
var parent = $(this).parent();
var comment= parent.find("textarea[name=comment]");
alert(comment.val());
});​
That's because the button is a submit, it prevents the rest of the code to be executed.
Use type='button' instead.
Or use:
$('#formname').submit(function() {
alert('Handler for .submit() called.');
return false;
});
change input type="submit" to input type="button" as it wont allow other code to get executed afer the submit, and instead of .live() use .on()
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
This method provides a means to attach delegated event handlers to the document element of a page, which simplifies the use of event handlers when content is dynamically added to a page. See the discussion of direct versus delegated events in the .on() method for more information.

jQuery show not working after added a new element in document

I am loading elements into a div container using Ajax / Request. By default I'm hiding an input box. If a user clicks an edit icon on that div, I want to show the input box. Here is my code:
HTML CODE
<div class='container'>
<input type = 'text' onkeydown='saveFn(event,this)' name = 'editemail' class = 'editemail' style='display:none; height:20px;' />
</div>
JS CODE
$(".container").click(function(){
console.log($(this).find(".editemail").show()); //Note it works fine If i didn't load any new elements into the div.
});
Console Log Output before loading new element into the container.
<input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; " value="hyther#zohocorp.com" title="press enter to save">
Console Log Output after loading an element into the container.
<input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; display: none; " value="saravanan#zohocorp.com" title="press enter to save">
Even though I am also tried to remove the "style" attribute from this element and adding a new style element, it still doesn't work.
First you should read the jQuery Docs FAQ section: Why_do_my_events_stop_working_after_an_AJAX_request
Use on() to delegate the handler for future elements
$(document).on('click', ".container", function(){
/* your code*/
})
Try this instead:
$(document).on('click','.container',function(){
http://api.jquery.com/on/
Try this one instead:
$('.container').live('click', function(){
/* Your Code Here */
});
The problem is that the click() bound is getting lost after an ajax request. In JQuery you can use .live() function to get this working however this function is now deprecated and they encourage you to use .on() or .delegate(). Personally i've have tons of headecks using .on() and .delegate() and rather use the plugin livequery. With livequery plugin is as simple as:
$(function(){
$('#elementId').livequery('click',function(){
//do something on click
})
});
For more information go to:
.livequery()
.on()
.delegate()

jQuery - add functionality to element after load()

I have some code which loads some html from another file, which works as it should. But I am struggling to access elements from this newly loaded data.
I have this code:
var widgetSettings = $("<div>").addClass("widgetsettings").load('dashboard/chart-settings-form.php #editChartForm');
widgetSettings.appendTo(widget.element);
//so far so good...
widget.element.find('.date').each(function(i){
$(this).datetimepicker(); //this doesn't work
console.log('testing... '+$(this).attr('id')); //this doesn't even work...
});
I'd expect it to find these text boxes in the '#editChartForm' form loaded from the above url (they're within a table):
<input type="text" name="datefrom" id="datefrom" class="date" /> To: <input type="text" name="dateto" id="dateto" class="date" />
The html is definitely being loaded. Just really confused as to why I can't access any elements from the load() event.
I also wanted to apply a click function to a cancel button on the same form, and I found the only way to make it work was to put it within a 'live' function before the load:
$('.cancel').live('click', function() {
//actions here...
});
Any ideas what is going on?
Simple! Because the load() method is asynchronous, and your line widget.element.find('.date') is firing BEFORE there's actually any elements in the DOM that match it! Just use a callback in your load(), like this:
$("<div>").addClass("widgetsettings").load('dashboard/chart-settings-form.php #editChartForm', function() {
$('div.widgetsettings').find('.date').each(function(i){
$(this).datetimepicker();
console.log('testing... '+$(this).attr('id'));
});
});
$("div").load("url here",function(){
callbacks();
});
function callbacks(){
//put everything that you want to run after the load in here.
//also if the click function is in here it wont need the .live call
}
Edit: Also with the latest version of jQuery you can now use .on instead of .live (its much more efficient) ie.
$(".widgetsettings").on("click",".cancel",function(){
//actions here
});
hope this helps :)

Categories

Resources