onchange select run function - javascript

<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...

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>

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

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.

Handling change event for a dropdown using jQuery

I am trying to handle a change event for a dropdrown which looks like this:
<div>
<select id="serviceLine">
<option selected="selected">--Select Option--</option>
<option>Integration</option>
<option>BPM</option>
<option>GWT</option>
<option>Other</option>
</select>
</div>
Now,I want to add a textarea when the user selects option "Others".
The jQuery looks like this:
function otherHandler(){
$(this).siblings("textarea").remove();
if($(this).val()=="Other"){
var textbox="<textarea rows='3'></textarea>";
$(this).parent().append(textbox);
}
}
$("#serviceLine").on("change",function(){otherHandler()});
This doesn't work, because in otherHandler() $(this) contains the reference of the entire window and not just the dropbox.
However if I change my jQuery to this, it works fine:-
function otherHandler(that){
$(that).siblings("textarea").remove();
if($(that).val()=="Other"){
var textbox="<textarea id='slOther'rows='3'></textarea>";
$(that).parent().append(textbox);
}
}
$("#serviceLine").on("change",function(){otherHandler(this)});
My question is why didn't it work in the first case, why do we have to pass the reference explicitly? Am I missing something major here?
In your first case it didn't worked as this is for defined for the event handler.
$("#serviceLine").on("change",function(){
// this is accessible here in event handler not in the otherHandler function call
otherHandler();
});
You should have directly passed the reference of function
$("#serviceLine").on("change", otherHandler);
If you wish you can use .apply(this)
function otherHandler(){
$(this).siblings("textarea").remove();
if($(this).val()=="Other"){
var textbox="<textarea rows='3'></textarea>";
$(this).parent().append(textbox);
}
}
$("#serviceLine").on("change",function(){
otherHandler.apply(this);
});
Raed this keyword
$("#serviceLine").on("change",function(){
//this --> is local to the function block here you cannot use it outside
});
$("#serviceLine").on("change",function(){otherHandler(this)});
//^
Here you pass the reference of this to the function so it works
Better use
$("#serviceLine").on("change", otherHandler);
//^ function name

How to add a property to `change` event in jQuery

I have a <select> box:
<select id="myselect">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
I need to modify it's change event, so it would have a val_after_change property, no matter how event was triggered.
// THIS FUNCTION CANNOT BE MODIFIED
$('#myselect').change(function(e){
// this should alert select value after change
alert(e.val);
});
I know, that here I could just alert $(this).val(), but my real example is more complex and need e.val. I know this works in select2, but I could not understand their source code.
How do I modify the event? Do I need to make a wrapper or something? Any help would be appriciated.
Edit:
I'm making a wrapper on a library, that makes selects use e.val property, so I cannot modify the change event itself. I need the property to be there already when event is triggered. Something like this, but make it a default behavour:
e = jQuery.Event('change', {val: 2});
$('#myselect').trigger(e);
JsFiddle
I'm not sur I got it, here is a shot at it :
(function ($){
// keep a copy of the original "select2" function
var lib_select2 = $.fn.select2;
// wrap it into a call which
// first adds a listener to add the value as a property of the event,
// then adds whatever extra stuff the library adds
$.fn.select2 = function(){
this.change(function(e){
e.val = this.value;
});
lib_select2.apply(this, arguments);
}
})(jQuery)

Categories

Resources