Handling change event for a dropdown using jQuery - javascript

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

Related

Pass function to click event jQuery

I am just wondering what I need to do to pass the clickAssistanceToggle function to my jQuery click event, I have taken a look at some of the answers on here and can't find a simple solution to this.
So far I have this code:
function clickAssistanceToggle() {
$('.car-hub-header-help, #assistance-overlay, .assistance-close-btn').click(function(){
$('#new-car-hub, #new-car-offer').toggleClass('assistance-active');
$('#pulman-assistance').toggleClass('pulman-assistance-active').css("top", fixedPositionCalculator);
$('#assistance-overlay').toggleClass('assistance-overlay-active');
$('#new-car').toggleClass('assistance-active-body');
$('#new-car-offer-cta').toggleClass('assistance-active-cta');
});
};
$('.new-car-general-enquiry-btn').click(function(){
clickAssistanceToggle();
});
As you can see the function wont run like this because it hasn't been passed as a parameter, I have tried passing the function like so:
$('.new-car-general-enquiry-btn').click(function(clickAssistanceToggle){
clickAssistanceToggle();
});
However this does not seem to work, any idea how I can pass that function to the click event? Thanks
You can call like this,
$('.new-car-general-enquiry-btn').click(clickAssistanceToggle);
Or
$('.new-car-general-enquiry-btn').click(function(){
clickAssistanceToggle();
});
Also there is a chance that, .new-car-general-enquiry-btn element is not being rendered at the time of binding the event. If so you need to wrap the code inside dom ready event.
$(document).ready(function() {
$('.new-car-general-enquiry-btn').click(function() {
clickAssistanceToggle();
});
});
Instead of
$('.new-car-general-enquiry-btn').click(function(clickAssistanceToggle){
clickAssistanceToggle();
});
You need to use
$('.new-car-general-enquiry-btn').click(clickAssistanceToggle);
Basically you need to pass the function to be executed when a click is performed on a .new-car-general-enquiry-btn element.

How can I pass an object value name to a function in Jquery

I'm working with the JQuery Simple modal plugin and I would like to pass a Freemarker variable/object on the click of a link to my Jquery function.
As a test, I created an alert box to see if the value is being passed and it doesn't seem to work.
$(function() {
// Load dialog on page load
//$('#basic-modal-content').modal();
// Load dialog on click
$('#hey').click(function myName(uid) {
var x = uid;
alert(uid);
return false;
});
});
HTML
<div id="disclaimer${item.uid}">
Modal data
</div>
<a onclick="myName('${item.uid}')" id="hey">Read the blog</a>
The alert box just comes up as a blank object. Any help would be appreciated. Thanks!
First off, you look like you are confusing the html onclick attribute with the jquery .click method.
<a onclick="myName('${item.uid}')" id="hey">Read the blog</a>
This will call a javascript function named "myName" and pass it a the string ${item.uid}. Note, this is a string because you wrapped it in single quotes. If you do an alert, your alert will literally say "${item.uid}".
Then you have a jquery bind event for click:
$('#hey').click({....
Ok, you need to pick one. Either use the onclick to call a javascript function or use the bind click event. Both methods can work (I prefer javascript onclick functions myself but that is just opinion).
If you want to use the jQuery bind, put a debugger; line in it so that you can step through it easily and watch. I typically use e for my event variable and e.target gets the target of the event. It will look something like this:
$('#hey').click(function(e){
debugger;
alert($(e.target).attr('data-uid'));
});
--- edit---
Adding my note below here so it is easier to read.
One thing I like to do in my onclick functions is to pass the this pointer. This is especially useful if you have multiple of the same kind of node that are calling the same function.
<a onclick="myName(this)" id="hey2">Read the blog</a>
<a onclick="myName(this)" id="hey3">Read the blog</a>
then, in the javascript you function looks like:
function myName(ptr)
{
$(ptr).....
// do some stuff
}
try using this:
function myName(uid){
alert(uid);
}
You dont need to wrap it in a jquery event handler, because you are already calling it as an onclick event from your Freemarker template.
Alternatively, you could do something like this:
<a data-uid="${item.uid}" id="hey">...</a>
And have your javascript like this:
$('#hey').click(function(){
alert($(this).data('uid'));
}

Trigger a button click on a moon.Button or moon.IconButton with jQuery/Javascript directly

I know the click action can be triggered by assigning ontap a specific function like so:
{
kind: "moon.Button",name :"search_button",
content : "Search" , ontap : "searchAction", classes: "menu-button-style"
}
.
.
.
searchAction : function(){ //do some stuff on click}
I've tried
$('#id_of_my_button').click();
$('#id_of_my_button').trigger('click');
and none of those seem to work.
simplified jsFiddle
Any ideas
Why trigger the click with jquery? You can force an event with Enyo, as well:
this.$.someButton.bubble("ontap", {...});
Here, try this:
http://jsfiddle.net/Djspaceg/2AWb5/6/
Enyo has a global handle (enyo) you can use if you need to access any part of its structure. It's not recommended for use from within our app, since it breaks encapsulation, but since you're already outside enyo (by using jQuery or plain JavaScript) I don't see as much harm.
function TapThat() {
// 'enyo' is the global namespace.
// The '$' refers to the children of the object/kind.
enyo.$.tappyButton.tapAction();
}
Using the native click function of elements seems to work in your case, like this:
window.onload = function (){
document.getElementById('tappyButton').click();
};
Demo
Your problem in the fiddle is that you haven't included jQuery. Also, probably that you don't wait for the element to be added to the DOM before binding a click listener to it.
Demo with jQuery

Passing 'this' as parameter in JavaScript

I have the following code:
HTML:
<label id="copyAddress" class="copyAddress" onclick="CopyAddress(this);">
Copy Address
</label>
JS:
function CopyAddress(copyAddressLink) {
PopulateTarget(copyAddressLink);
}
function PopulateTarget(link) {
var targetGroup = $(link).closest('someClass');
}
In PopulateTarget function 'link' variable is undefined, while in CopyAddress it has values as is should.
What can cause this problem? Is there some restriction for passing parameters in Java Script? How this should behave? If you need more code to post please tell me.
Since you are anyhow using jQuery, why are you using obtrusive Javascript?
Use this instead:
HTML:
<label id="copyAddress" class="copyAddress">Copy Address</label>
Javascript:
$(document).ready(function(){
$('#copyAddress').click(function(){
var targetGroup = $(this).closest('.someClass');
});
});
You're missing a dot on "someClass", it should be ".someClass".
Maybe your code will work after you fix that. However: since you're using jQuery (it seems you are), you should attach the click handler the jQuery way, instead of inline on the HTML. This means:
$(document).ready(function(){
$('#copyAddress').click(CopyAddress);
})
function CopyAddress() {
PopulateTarget(this);
}
function PopulateTarget(link) {
var targetGroup = $(link).closest('someClass');
}
You should not intermix your HTML and JS. You should instead attach your JS handlers programmatically in your JS code:
<!-- note: no onclick in this html -->
<label id="copyAddress" class="copyAddress">Copy Address</label>
// Wait until the page is loaded before starting to look for elements
$(function(){
// Assuming jQuery 1.7
$('#copyAddress').on('click',copyAddress);
// …alternatively, for older jQuery
$('#copyAddress').click(copyAddress);
function copyAddress(evt){
// The 'target' property of the event object passed in is the object
// upon which the event was first triggered.
PopulateTarget(evt.target);
}
});
In the case of the above, you could just use this instead of evt.target, since you bound the event directly on that object. However, this becomes more powerful if you have a variety of items on the page that perform this function. You can attach the event handler once to some parent object, and then ask—during the callback—which element was clicked on. That would look like:
// Watch for any element with a copyAddress class to be clicked on,
// even if they are added after this code has run
$(document.body).on('click','.copyAddress',function(evt){
var target = evt.target;
console.log("You clicked on",target);
});
As it seems you are using jQuery:
You can use jQuery.proxy to bind this to a specific value. It is used like this:
jQuery.proxy(function () { console.log(this); }, this);

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