What is the difference between jQuery change and onchange of HTML? - javascript

I have the following HTML code :
<select name="test123" id="test123" onchange="testOnchange()">
<option>Chocolate</option>
<option>Candy</option>
<option>Taffy</option>
<option>Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<script>
$( "#test123" ).change(function() {
console.log("change");
});
function testOnchange() {
console.log("onchange");
}
</script>
If I use JS to set a value for the select like this:
$("#test123").val("Candy");
why does testOnchange() trigger, but jQuery change doesn't?
What exactly is the difference between change and onchange?

It is because you didn't ensured that <select> is loaded in dom before binding the change event, check this fiddle
and check this fiddle again when these scripts were wrapped inside onload event of the document.
Also, if you are setting the value programmatically, you need to trigger the change() event programmatically as well, check here and here
$( document ).ready( function(){
$( "#test123" ).change(function () {
console.log("change");
});
});
function testOnchange(){
console.log("onchange")
}

why does testOnchange() trigger, but jQuery change not?
This is because onchange is an event defined in DOM api but .change is from jQuery's event object.
So, although when you apply a change event with jQuery code $("#test123").val("Candy") it causes a change event in DOM so the native one is fired only.
In case if you want to trigger the jQuery's change event too, then you need to trigger it manually as the other answer suggested. $("#test123").val("Candy").change();

$("#test123").val("Candy") does not trigger onchange event see, http://jsfiddle.net/j58s9ngv , http://jsfiddle.net/j58s9ngv/1
Try calling .change() after setting value to trigger onchange event
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<select name="test123" id="test123" onchange="testOnchange()">
<option>Chocolate</option>
<option>Candy</option>
<option>Taffy</option>
<option>Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<script>
$( "#test123" ).change(function () {
console.log("change");
});
function testOnchange(){
console.log("onchange")
}
$("#test123").val("Candy").change()
</script>

$("#test123").val("Candy") does not trigger onchange event. I think both same.

Related

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.

Basic javascript questioning

I'm trying to set a script to dynamically change a textarea content.
After some Googling I got this :
$(document).ready(function() {
// This is a first text modification that works fine
$('textarea#modifyme').val('Some useless text');
// Catching a select change
$('select#changemyvalue').bind('change keyup input',function() {
// This alert triggers but twice
alert('I know you want to change text');
// This is not displaying...
$('textarea#modifyme').val('I do not want to be display');
});
});
First value setting is good, but when it comes to select change detection it gets a bit odd.
Alert is triggering twice, and the second value setting is not functioning.
Any help greatly appreciated! Thanks.
Thanks to your answers I've fixed the double trigger, but still the secon .val('sometext') is not triggering.
I'm trying to apply this to a textarea displaying as a wysiwyg editor, I can only change the text on load (first .val('xx') call).
I also notice that if I invert these 2 lines :
// This alert triggers now only once
alert('I know you want to change text');
// This is not displaying...
$('textarea#modifyme').val('I do not want to be display');
To :
// This is not displaying...
$('textarea#modifyme').val('I do not want to be display');
// This alert does not trigger if placed here
alert('I know you want to change text');
Code seem to break at the first line, preventing 'alert' to display.
Is the nature of wysiwyg editor preventing text change after page load?
Here is the short version of html code :
<select name="" id="selectMe">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<textarea class="textarea callhtml5" name="changeMe" id="changeMe"></textarea>
<!-- Bootstrap WYSIHTML5 -->
<script src="path to wysihtml5 bootstrap"></script>
<script>
$(".callhtml5").wysihtml5();
</script>
<script>
$(document).ready(function() {
$('textarea#changeMe').val('Initial text setup');
$('select#selectMe').bind('change keyup',function() {
alert('Test');
$('textarea#changeMe').val('Final text setup');
});
});
<script>
Solved this problem by using :
$('.wysihtml5-sandbox').contents().find('body').html("I got you modified");
Instead of this method :
$('textarea#changeMe').val('Final text setup');
It's because of keyup and input. If you bind both events the callback executes two times.
To over come this use these two bind input. You can omit the keyup.
One thing I would like to mention about input event is that it can't be captured. What I mean is it won't let you capture event.
Just noticed that the element is <select> element so better to use change keyup. You should avoid using input event as you are not putting text values in it but changing it with mouse or keys.
You need to either take out change or input from .bind(). Both events are triggering thus running the function twice.
Hope this helped! :)
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. http://api.jquery.com/bind/
You could probably change your code like this to work.
$(document).ready(function() {
$('textarea#modifyme').val('Some useless text');
$('select#changemyvalue').on('change', 'keyup', 'input',function() {
alert('I know you want to change text');
$('textarea#modifyme').val('I do not want to be display');
});
});
EDIT: Instead to using three things, one would work properly. Use input or keyup
You Remove keyup input on your Script
Try This Jquery like this
$(document).ready(function() {
$('textarea#modifyme').val('Some useless text');
$('select#changemyvalue').on('change', function(e) {
// This alert triggers but twice
alert('I know you want to change text');
// This is not displaying...
$('textarea#modifyme').val('I do not want to be display');
});
});
You can add event parameter to your handler and check what event is raised
As you can see below: first - input event, then - change event
So you should select just one of them.
This interesting, but seems input event for select raised just in Chrome.
Sample:
$(document).ready(function() {
$('textarea#modifyme').val('Some useless text');
$('select#changemyvalue').on('change keyup input', function(e) {
console.log('Now raised: '+e.type+' event');
$("#events").append('Now raised: '+e.type+' event <br/>');
// This is not displaying...
$('textarea#modifyme').val('I do not want to be display');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="" id="modifyme" cols="30" rows="10"></textarea>
<select name="" id="changemyvalue">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="events"></div>

Changed ID not being found by jQuery

Tough to come up with the title for this question.
More for proof of concept, I'm wondering why this doesn't work. What I'm attempting to do is use a jquery event to change the ID attribute, then use another jquery event bound to this newly changed ID.
For example:
<?php
echo <<<END
<html>
<head>
<style>
#before {
color:maroon;
}
#after {
color:blue;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<title>Test</title>
<script type="text/javascript">
$(document).ready(function(){
$("#before").hover(function() {
$(this).attr("id","after");
});
$( "#after" ).click(function() {
alert( "Handler for .click() called." );
});
});
</script>
</head>
<body>
<p id="before">TEST TEXT</p>
</body>
</html>
END;
?>
On hover over my test text, the color changes from maroon to blue, as expected. It is my understanding that the text would now have an ID of "after" and the click event handler function would apply when clicked. However that is not the case the quick event handler and its associated alert does not appear to trigger.
I am new to jquery is there perhaps an update handlers function I'm overlooking?
It works with the same principle as Event binding on dynamically created elements?.
When you add a event handler to an element where the element is found using a selector, the selector is executed only once when the code is executed after that the handler is added to the element. Once is has happend if you change the selector values associated with the element it will not reflect in the attached handlers.
For example in your case you are adding the a handler to the element with id before in dom ready handler, so once the dom ready event is fired your selector is evaluated and it returns a single element to which you are adding the handler. In the same dom ready handler you are trying to add a click handler to an element with id after, but at dom ready there are no elements with that id so that handler is not attached to any element.
Now at a later time you are changing the id of the elemnet, but it will not affect in the already attached handler nor will it add a new handler.
The solution here is to use a mechanism known as event delegation.
Demo:
$(document).ready(function() {
//there is no need to use hover as your want to add the class when the mouse enter the element and you don't want to do anything in mouseleave
$("#mytarget").mouseenter(function() {
$(this).addClass("after").removeClass('before');
});
//look at the use of event delegation
$(document).on('click', '.after', function() {
alert("Handler for .click() called.");
})
});
.before {
color: maroon;
}
.after {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="mytarget" class="before">TEST TEXT</p>
You can fire the click event after the hover event
$(document).ready(function(){
$("#before").hover(function() {
$(this).attr("id","after");
$( "#after" ).click(function() {
alert( "Handler for .click() called." );
});
return false;
});
});

How to access value attributes of dynamically created <select> tag dropdown, using jQuery?

Here's the jsfiddle link to a small mockup of what I am trying to do http://jsfiddle.net/dscLc/8/
Javascipt code
newc=function(){
$('#div').html('<center><select id="resClass"><option value="" selected>FIRST</option></select><center>');
for(var i=0;i<10;i+=1)
{
$('#resClass').append('<option value="'+i+'">'+i+'</option>');
}
}
$(document).ready(function(){
$("#resClass").change(function(){
alert($(this).val());
});
});
HTML code goes here
<div id="div">
<center>
<button type="button" onclick="newc()">Compare</button>
</center>
</div>
Also this seems that you have a static parent with an id #div so you can delegate to this element. Although $(document) && $(document.body) are always available to event delegation, but this is very slow in terms of performance.
Better to delegate the event to the closest static parent, where dom lookup time is low and performance is fast.
change this:
$("#resClass").change(function(){
to this:
$("#div").on('change', "#resClass", function(){
This is a case of event delegation.
What this means if any element is dynamically generated then you can't bind an event to that element the way you are currently trying to bind, because when dom was ready this element was not available at that point of time.
As you are adding the select dynamically, You need event delegation:
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$("#div").on('change','#resClass',function(){
alert($(this).val());
});
Working Demo
Working demo: http://jsfiddle.net/Lcr5t/
API: .on - http://api.jquery.com/on/
Rest should fit the need :)
Code
newc=function()
{
$('#div').html('<center><select id="resClass"><option value="" selected>FIRST</option></select><center>');
for(var i=0;i<10;i+=1)
{
$('#resClass').append('<option value="'+i+'">'+i+'</option>');
}
}
$(document).ready(function(){
$(document).on('change',"#resClass",function(){
alert($(this).val());
});
});
You event hookup needs to use 'on' to apply it to any controls that are subsequently created after it has been registered:
$(document).ready(function(){
$(document).on("change", "#resClass", function(){
alert($(this).val());
});
});
Your must to use delegated events like as .on, .bind, .live
There is a small problem in your code.
First, you have not called the function newc().
Secondly, since the select element is dynamically added, change() is not triggered.
Please check the following code:
newc=function(){
$('#div').html('<center><select id="resClass"><option value="" selected>FIRST</option></select><center>');
for(var i=0;i<10;i+=1) {
$('#resClass').append('<option value="'+i+'">'+i+'</option>');
}
}
newc();
$(document).on('change','#resClass',function(){
alert($(this).val());
});
FIDDLE

onchange select run function

<select onchange="alert();">
<option>d</option>
<option>de</option>
<option>dewe</option>
<option>dewee</option>
</select>
I want the onchange event of a <select> element to display an alert but it's not working.
Any ideas what's wrong?
I'm assuming your issue is that the alert() call displayed undefined instead of the value of the <select>.
If you want to see the value of the <select>, do this instead:
<select onchange="alert(this.value);">
<option>d</option>
<option>de</option>
<option>dewe</option>
<option>dewee</option>
</select>
jsfiddle example
Or, if you actually are using jQuery, you can do it like this:
//This is an anonymous function that calls itself with the jQuery object as an argument
//This allows you to use the `$` when making jQuery calls but the code
//will run without modification if jQuery is in noConflict() mode
(function($) {
//This is the important part
//Here, we bind to the change event and alert the value
$('select').change( function(e) {
alert($(this).val());
});
})(jQuery)
jsfiddle example 2
That should work but you can also try this provided you include jQuery on your page
$(function(){
$("select").change(function(){
alert($(this).val());
});
});
You should give a string as a parameter in your alert function if you want it to work...

Categories

Resources