jQuery .change() not triggering on select - example from api.jquery.com - javascript

I copied this example from api.jquery.com
$('.target').change(function() {
alert('Handler for .change() called.');
});
I also tried:
$('#target').change(function() {
alert('Handler for .change() called.');
});
I copied it into my .js file, which is included in my html. I have another jQuery function in there (beginning $(window).load(function () { ..."
The other function is working. But the above simple function is not.
The form looks like this:
<form>
<select id="target" class="target">
<option name="pp" value="6">6</option>
<option name="pp" value="12">12</option>
</select>
</form>
I want to just use id, but I added class just for testing. But neither works.
Why doesn't this simple function work? Do I need to do anything else to connect the change event to the function? I am new to jQuery, but I know that in javascript I would have to have the onchange event of the form call the function in order for something to happen.
EDIT: Ok, here is EVERYTHING in my included .js file. As you can see, just one other function. Is it interfering?
Also, I have only 1 form on the page, which you see above. I am going to have it change the number of results shown per page (6 or 12).
$(window).load(function() {
$("img.gall_img").each(function() { // iterate through all img of class gall_img
var imgWidth = $(this).width(); // "$(this)" to access jQuery width() func
var divWidth = $(this).closest('div').width();
//alert(imgWidth + " and " + divWidth); // for debugging
if(imgWidth > divWidth) {
var position = Math.round(-1 * ((imgWidth/2) - (divWidth/2))); //
position = position + "px"; // make position format "123px".
$(this).css("left", position); // "$(this)" to access jQuery css() func
}
});
});
$("#target").change(function() {
alert('Handler for .change() called.');
});

Put the code inside the $(window).load function, like so:
$(window).load(function () {
//whatever code is already here
$('.target').change(function() {
alert('Handler for .change() called.');
});
}); //end of $(window).load function
$(window).load(function () tells the browser to only run that code after the entire page is loaded INCLUDING images. Traditionally with jQuery you will see the $(document).ready(function() {... which tells the browser to not process that code until after the page is loaded (not including images)
IF you don't need to wait for the images to load to run your jQuery then you could replace $(window).load(function () { with $(document).ready(function () {
Cheers!

Try placing your .change(..) inside a .ready(..) function like this:
$(document).ready(function () {
$('#target').change(function() {
alert('Handler for .change() called.');
});
});

I've tried this code in jsFiddle => http://jsfiddle.net/GjScg/
And this code should work, is there any other javascript that is bounded on the Change event? Perhaps there's some other code around, that causes errors?

Are you sure, it doesn't work?
Here is a working link to jsfiddle: http://jsfiddle.net/ayezutov/7pEP4/
UPDATE:
Both versions work: http://jsfiddle.net/ayezutov/7pEP4/1/

Related

Trigger jquery .on() on page load

I am trying to find out if I can trigger some javascript code when page has loaded and not only on keyup
$(document).on('keyup', '.some-class', function (e)
{
// Some code
});
I have tried the following and that didn't work (my research indicate that it shouldn't work either):
$(document).on('keyup load', '.some-class', function (e)
{
// Some code
});
$(window).on('keyup load', '.some-class', function (e)
{
// Some code
});
UPDATE:
My question seems to be unclear in regards to what I want to accomplish. The code works fine when using keyup in an input field.
But I also want the code to run when the page loads.
I could do this but I am looking for a solution that are more elegant.
hello();
function hello() {
// Some code
}
$(window).on('keyup load', '.some-class', function (e)
{
hello();
});
Whilst you CAN trigger the keyup function on page load, I wouldn't recommend it. You're much better off defining the function you want to run elsewhere, then calling it on both load and keyup.
This way if you ever want to add anything to the keyup event that doesn't need to run on load, you can.
Something like, but not necessarily this, would work:
var myFunction = function() {
// Do some function stuff
return;
}
$(document).ready(myFunction);
$('.myElement').on('keyup', myFunction);
Or if you need to pass arguments to the function (which is a little closer to your use-case):
var myFunction = function(args) {
// Do some function stuff
return;
}
$(document).ready(function() {
myFunction(args)
});
$('.myElement').on('keyup', function(e) {
e.preventDefault();
myFunction(args);
// You can add more code here that won't be triggered on load
});
Maybe you are searching for $( document ).ready(). When the document is ready just run the code
$( document ).ready(function() { /* YOUR CODE HERE (maybe the $(document).on('key up'... */})
It sounds to me like you are wanting something like the following:
jQuery(document).ready(function(){
//Code Here
)};
Or window load (which was deprecated in 1.8 thanks to #charlietfl):
jQuery(window).load(function(){
//Code Here
)};

Jquery change event not fired when using selected attribute on select item

I have a HTML code generated dynamically from a model using .NET MVC. Between the field there is a select with selected option (based on the data from the model).
<select class="myClass" data-val="true" id="sampleSelect" name="sampleSelect">
<option value="">Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="selected">3</option>
</select>
I want to attach change event using jQuery like this:
$('#sampleSelect').change(function () {
var test = $('#sampleSelect').val();
});
Or like this:
$('#sampleSelect').on('change', function () {
var test = $('#sampleSelect').val();
});
Or even with delegate... none of those works. It seems that there is no change done, option value 3 remains with selected attribute.
I don't want to modify the HTML, I just one to use the right javascript code to catch the event.
Do you have any suggestions?
Edit: Attribute selected remains on value 3. Even if I select different item. And the change event doesn't fire. I don't know why. This is my problem.
FINAL EDIT: My bad, the selecting was done in a right way. The problem is that there were 2 selects with the same id and jQuery kept choosing the hidden one somewhere else on the screen.
Thanks for the fast answers though.
Your HTML code generated dynamically.So, you have to use $(document).on(); jquery
For example:
$(document).on('change','#sampleSelect', function () {
// your code
});
You could try:
$(document).on("change", "#sampleSelect", function () {
// Stuff
});
Your code seems file.
DEMO : http://jsfiddle.net/6cLs6hcx/
I guess you might want to add an event handler inside the ready() method :
Document : https://api.jquery.com/ready/
$( document ).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to the recommended way:
$(function() {
// Handler for .ready() called.
});
So your code could go like this:
$(function() {
$('#sampleSelect').change(function () {
var test = $('#sampleSelect').val();
});
});
A tutorial is here :
https://www.tutorialspoint.com/jquery/jquery-events.htm
$(document).on('change', '.selectOption', function() {
console.log($(this).val());
});
I think you mean the HTML content is loaded in after page load? If so use
$(document).on('change', '#sampleSelect', function () {
var test = $('#sampleSelect').val();
// OR
var test = $(this).val();
// OR
var test = this.value;
});
Which attaches the event even if the element isn't available initially.

window.load will not fire

I need to run a function after the HTML on my page has been rendered (because I need to get the height of a particular dynamic div). I have tried several methods, but I cannot get window.load to fire (I am using Chrome).
I've placed all of the following code below in the constructor of my TypeScript ViewModel.
This doesn't work:
$(window).on('load', function () {
...code...
});
And neither does this:
$(window).load(function(){
...code...
});
Or this:
window.addEventListener('load', function () {
...code...
});
Any ideas why none of these work? If there's another method to go about doing this, I'm open to suggestions.
Try putting it inside the following:
$(document).ready(function() {
jQuery.event.add(window, "load", myFunction);
myFunction() {
...code...
}
});
This worked for me when I had to manipulate a <div> based on its height after rendering.

Jquery issue with variable

I have the following example: http://jsfiddle.net/gespinha/yTjUL/13/
The variable should be triggered on click, making the link change class from on to off and change colour from red to green. But instead it starts already green, thus making the function useless.
Why does it not work?
HTML
<a id="link" href="javascript:void(0)" class="on">CLICK HERE</a>
JQUERY
$(document).ready(function () {
var $myVar = $(document).find('.on').addClass('off').removeClass('on');
$('link').click(function () {
$myVar
});
});
You seem to be under the impression that the variable will store a chain of actions to perform later, when the variable is 'called,' but that's not (clearly) what happens: the first line, within the ready() handler, in the var assignment, finds the .on element and performs the actions you specify, storing the .on element(s) in the variable (as jQuery methods almost all return the this object).
Instead:
$(document).ready(function () {
// use the `#link` notation, since 'link' is the id of the element:
$('#link').click(function () {
// assign a function to the click-event handler:
$('.on').addClass('off').removeClass('on');
});
});
Or, more simply (if you want to toggle between 'states') use toggleClass() and $(this) (rather than selecting from the whole of the document each time the user clicks the given element):
$(document).ready(function () {
$('#link').click(function () {
$(this).toggleClass('on off');
});
});
Also, rather than using javascript:void(0) in the href, simply use jQuery to prevent the default action, with:
$(document).ready(function () {
$('#link').click(function (e) {
e.preventDefault();
$(this).toggleClass('on off');
});
});
JS Fiddle demo.
References:
click().
event.preventDefault().
toggleClass().
It doesn't work that way, the variable will just contain the result of whatever methods you called, and for jQuery that means the element will be returned, so the variable $myVar only equals $(document) inside the event handler, it does not call the chained methods again.
You have to do:
$(document).ready(function () {
$('#link').on('click', function () {
$('.on').toggleClass('on off');
});
});
$(document).ready(function () {
$('#link').click(function () {
$(".on").addClass("off").removeClass("on");
});
});
As Guilherme Sehn noted, the $myVar variable is not needed. Just put your code in the click event. In addition, the link selector needs to be "#link", not "link".
By doing this, you'll be executing these actions and storing the return value (which will be the jQuery elements) inside $myVar. You can just put your code inside the click trigger function.
$('#link').click(function () {
$('.on').addClass('off').removeClass('on');
});
Also, you forgot the # before your ID. Without that your code will select link tags, not the element with the id link. And you do not need to explicity use $(document).find('.on') as all DOM elements are inside it.
I guess you meant $("#link")... and not $("link")
And if I understand right - the full script should be:
$(document).ready(function(){
$("#link").click(function(){
$(".on").addClass("off").removeClass("off");
});
});
You don't invoke the function and your selector is wrong.
$(document).ready(function () {
$('#link').click(function () {
$(document).find('.on').addClass('off').removeClass('on');
});
});

On change event not fired with dynamically loaded data

I am dynamically loading data in the input type text and triggering alert if the value of the text box is changed. But my code does not seem to work. Please provide suggestions.
visit this page for code: http://jsfiddle.net/NbGBj/103/
I want the alert to be shown when the page is loaded
You should remove your " around document
$("document").ready(function(){
...
should be
$(document).ready(function(){
...
or use the shortcut
$(function(){
...
From the official documentation:
All three of the following syntaxes are equivalent:
- $(document).ready(handler)
- $().ready(handler) (this is not recommended)
- $(handler)
http://api.jquery.com/ready/
But I guess what you want is the keyup event
$(function () {
$("#upload").val("sample");
$("#upload").keyup(function () {
alert($(this).val());
});
});
And for better readability, you can use chaining
$(function () {
$("#upload").val("sample").keyup(function () {
alert($(this).val());
});
});
http://jsfiddle.net/BXNkq/
You can just fire the change function directly after you set the value in the text box like this:
....
$("#upload").val("sample");
$("#upload").change();
....

Categories

Resources