Retrieving text on focusout/blur - javascript

I have mulitple textarea's, when you're finished editing them i'm looking to retrieve the new text when the field doesn't have focus anymore.
The solution i've been trying is
$('textarea').live('focusout', function() {
console.log(this.text);
});
or
$('textarea').live('blur', function() {
console.log(this.text);
});
Both return as undefined, due to it not knowing what 'this' is referring to.
Is there another event that can make this possible?

Use the value property (this.value) to get the contents. Even in JQuery, the .text() method doesn't return the right contents of a textarea.
If you want to use a JQuery method:
$('textarea').live('focusout', function() {
console.log($(this).val());
}

Related

second this is wrong? [duplicate]

I'm not quite sure if I'm not using this in the correct scope or what, but I have a script that basically captures a link click and causes the page to fade out before going to the linked page. However, if the link is a JavaScript onclick, the script fails.
Here's my code:
<script type="text/javascript">
pageObj = {
init: function(){
$("body").fadeTo("slow", 1);
},
redirectPage: function(redirect){
window.location = redirect;
},
linkLoad: function(location){
$("body").fadeOut(1000, this.redirectPage(location));
}
};
$(document).ready(function() {
pageObj.init();
$("a").click(function(e){
e.preventDefault();
if (this.attr('onclick') !== undefined) {
eval(this.attr('onclick').val());
} else {
var location = this.href;
pageObj.linkLoad(location);
}
});
});
</script>
As you can see, I'm trying to do a check to see if the link has the onclick attribute, and then call the onclick function if it exists. How can I achieve this?
Use: $(this).attr instead of this.attr
This forces it into the context of jQuery.
While Diodeus is correct that you need to wrap this in a jQuery collection before using attr() (it's a method of a jQuery collection, not of an HTMLElement), you can just as well skip attr().
$("a").click(function(e){
var location;
e.preventDefault();
if ($.isFunction(this.onclick)) {
this.onclick.call(this, e);
} else {
location = this.href;
pageObj.linkLoad(location);
}
});
Note that I used the property (when an HTML document loads, attributes are usually preloaded into properties, with on_______ attributes being preloaded as methods. Also note that I used this.onclick.call() rather than eval(), setting the correct this for onclick methods, and ensuring access to the event object as an argument.

How I can add functionality to a jQuery method?

How I can add functionality to a jQuery method? For example, when using hide on an element (<a> or <p> or something else):
HTML
click me
jQuery
$("a").hide()
I tried creating a type of plugin, but I want to keep the native functionality and then add more.
jQuery.fn.extend({
hide: function () {
alert("hidden element: " + $(this));
}
});
The easiest way, of course, would be to give it a different name. If you really don’t want to do that, you can keep a reference to the original method, then pass both this and any received arguments using Function.prototype.apply:
var originalHide = jQuery.fn.hide;
jQuery.fn.hide = function () {
alert('hidden element: ' + this); // == $(this); neither is meaningful
return originalHide.apply(this, arguments);
};

Modify change event of Kendo UI Dropdownlist

I'm trying to change the "change" event of a Kendo UI Dropdownlist, but unfortunately I haven't had any luck. Here's the code I've tried so far: http://trykendoui.telerik.com/ukeV
Specifically, here's my dropdownlist initializer:
var onChange = function(e)
{
alert("something changed");
};
// create DropDownList from input HTML element
$("#dropdown").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
index: 0,
change: onChange
});
And this is my attempt to change that function later:
onChange = function(e){alert("attempt 1");};
var dropDownData = $("#dropdown").data("kendoDropDownList");
dropDownData.options.change = function(e){alert("attempt 2");}
dropDownData.refresh();
Specifically, I first tried just changing the onChange function, and then (when that didn't work), I tried changing the options.change function directly. While the options.change function did change (when I examined it in chrome debugger), the dropdownlist's actual functionality remained unchanged. I think I need to refresh the dropdownlist or something to make my edits actually take effect. Does anyone know how I can actually get the kendo grid to refresh and display my data?
I see you've already found a work-around, but I thought I'd add some more explanations.
The reason why changing it like this
onChange = function(e){alert("attempt 1");};
doesn't work is that you're passing a function to the widget, and the widget calls that function at appropriate times. You're not passing a reference to the variable onChange. So changing the variable won't affect the widget.
The reason why
dropDownData.options.change = function(e){alert("attempt 2");}
doesn't work is that Kendo stores handlers in its own structure (which is necessary since you can bind multiple handlers for the same event!), so it doesn't call whatever is in options.change at any given moment in time.
However, there is a setOptions method, and with that you could've made your second approach work:
dropDownData.setOptions({
change: function (e) {
alert("attempt 2");
}
});
I ended up using a simple work-around. When I put in the line
change: onChange
Kendo actually hardcoded in the function body into the dropDownData.options.change function, rather than referencing my named javascript function. It looked like this in the debugger:
function(e)
{
alert("something changed");
};
So my workaround was simply to use an anonymous function in the Kendo call. So I changed change: to
change: function(e) { onChange(e) };
Then when I changed onChange later, kendo referenced the named javascript function and called my updated version. Here's the working demo: http://trykendoui.telerik.com/AkIW/2

always trigger "change"-event for <select>, even if the select2-option clicked is already selected

I have a native <select>-element based on which I'm initializing a select2-dropdown-menu.
I bound a change-event via select2 which is called whenever the select2/select-option is changed. However, I need to fire the event even if the currently selected option is selected again.
function onSelectChange(){
alert('changed');
};
$("#select").select2().bind('change', onSelectChange);
I prepared a http://jsfiddle.net/rb6pH/1/ - if "Alaska" is currently selected and then selected again via the select2-dropdown, onSelectChange() should fire again, triggering the alert.
I have a hard time expressing myself, please ask if something isn't clear enough.
Motivated by the absolutely valid remarks by #FritsvanCampen, I sat my ass down and figured out a way myself: What I really needed was a way to access the currently selected val, even if it hadn't changed. By using select2's undocumented close-event instead of change, I can access just that like so:
function onSelectChange(event){
alert( $("#select").select2("val") );
};
$("#select").select2().bind('close', onSelectChange);
Find an updated jsFiddle at http://jsfiddle.net/rb6pH/42/
A similar question was asked here. I have made a fiddle for your question based on the code in the link.
http://jsfiddle.net/rb6pH/55/
function onSelectChange(){
alert('changed');
};
var select2 = $("#select").select2().data('select2');
select2.onSelect = (function(fn) {
return function(data, options) {
var target;
if (options != null) {
target = $(options.target);
}
if (target) {
onSelectChange();
return fn.apply(this, arguments);
}
}
})(select2.onSelect);
I think you might refer to this link, i stuck once in same situation,
Change event is not fired when the selection is changed using Select2's val() method.
The event object contains the following custom properties:
val
the current selection (taking into account the result of the change) - id or array of ids.
added
the added element, if any - the full element object, not just the id
removed
the removed element, if any - the full element object, not just the id
For more information you might refer to this.
Thanks!
I read the question and it's so close to my problem so I decided not to post another question. What I want to do is after select2 closed, a simple text input become focused but it doesn't work. please check
function onSelectChange(){
alert('closed');
$('#hey').focus();
};
$("#select").select2().bind('close', onSelectChange);
$('#hey').on('focusin)', function(){alert('in');}
http://jsfiddle.net/sobhanattar/x49F2/5/
I tried to make sure that the input become focused and it showed that the input become focused but I don't know why it doesn't show the curser
a little old question but i spent a few hours last week to find a solution.
I am using Select2 version: 4.0.5.
My working solution is this one:
$("#exampleId").on("select2:open", function() {
var checkExist = setInterval(function() {
var $selectedChoiceInsideSelect2Dropdown = $("li.select2-results__option[id^='select2-" + exampleId + "-result'][aria-selected=true]");
if ($selectedChoiceInsideSelect2Dropdown.length) {
$selectedChoiceInsideSelect2Dropdown.on("mouseup", function() {
$(this).trigger("change");
});
clearInterval(checkExist);
}
}, 100); // check every 100ms
});
It's very important to use the interval!
var prev_val = $('#select2').val();
$('#select2').blur( function() {
if( $(this).val() == prev_val )
// not changed
else {
// changed
prev_val = $(this).val();
}
});

Add Text To Span After Image Error

Note: I am very new to Javascript.
Here is my attempt at achieving this:
$("#img").onerror = function(evt) {
$(".card-error").next("#img-error").html("Error with image url");
});
This did not work.
When an "onerror" occurs - how do I add a text error message inside my "img-error" span?
Try that instead:
$('#img').error(function () {
$(".card-error").html("Error with image url");
});
You need to use an jQuery event handler method:
$('#img').on("error", function() {
$("#img-error").text("Error with image url");
});
You were assigning a property "onerror" to the jQuery wrapper object, where it does nothing than getting garbage-collected. Assigning to the DOM element would've worked, such as
$("#img").get(0).onerror = … // or with plain DOM:
document.getElementById("img").onerror = …

Categories