I know this might appear paradoxical but I'm trying to work out how to detect a change on a text input when the value is updated by jquery.
During the user using the page my javascript does this:
$('#LicenseOwnerId').val(company.Id);
What I want to do is react to this value being set and execute another function.
So far I've tried the following methods:
var obj = document.getElementById('LicenseOwnerId');
obj.onChange = function () {
alert('select changed!');
};
And I've tried this:
$('#LicenseOwnerId').bind('change input propertychange', function(event) {
alert('select changed!');
});
And I've also tried this:
$('#LicenseOwnerId').change(function () {
alert('select changed!');
});
None of these seem to get fired when the value is updated and I cannot think of any other methods to try and hook this up. What is the correct way (if any) to wire this up?
I'm starting to wonder if this is even possible and consequently is also cross browser safe.
It's as easy as this:
$('#LicenseOwnerId').val(company.Id).trigger('change');
using
$('#LicenseOwnerId').change(function () {
alert('select changed!');
});
There is no other way (without modifying jquery core methods), you have to trigger the event yourself.
Related
I am trying to write some code for change() event using jQuery Text Editor (jqte), I have two functions which give jqte functionality to textarea's
One for editors loaded with JavaScript, when clicking some elements in a page:
function onLoadEditor(){
jQuery(".comment-editor").jqte({
// some jqte params, such as fsize: false,indent: false...
change: function(){ observeEditor(); }
});
}
And other, generic function, for pages with one single editor
jQuery(function() {
jQuery(".comment-editor").jqte({
// some jqte params, such as fsize: false,indent: false...
change: function(){ observeEditor(); }
});
});
I want to access the id of the concrete textarea (all textareas in the page have an id) which has fired the change() event
How should I write observeEditor() function to achieve this? Or... how I should define the function in jqte change property?
After reading this jQuery blur event with ID and value I have solved it, with following code (simplified)
function onLoadEditor(){
jQuery(".comment-editor").each(function(idx, elem) {
jQuery(this).jqte({
// some jqte params, such as fsize: false,indent: false...
change: observeEditor(elem.id),
});
}
jQuery(function() {
onLoadEditor();
});
But now I have another problem...
As you can read in the original question, onLoadEditor() is called when clicking some elements in a page. Then another javascript function jsComment() is called, builds a form (with a textarea.comment-editor field included) and it is rendered this way
function jsComment(){
...
var form = '<div class="comments_wrapper ... ';
jQuery(form).insertAfter(some_element).fadeIn('fast');
onLoadEditor();
}
Problem is change() event is being fired only once, when form fades in, while the idea is the opposite, event should fire when user adds some text, not when appearing... Any tips?
UPDATE
After reading Event binding on dynamically created elements? I have solved it this way
function onLoadEditor(){
jQuery('.comment-editor').each(function(idx, elem) {
jQuery(this).jqte({
// some jqte params, such as fsize: false,indent: false...
});
jQuery(document).on('change',
jQuery('.comment-editor'),
function(){
observeEditor(elem.id);
}
);
});
}
jQuery(function() {
onLoadEditor();
});
Although finally I am not using change() event, as it was being fired constantly. Performing better with keyup() & paste(), for instance
I'm trying to set a textbox to 'readonly', add a class, and put a text into the textbox at that moment when I check the checkbox. Moreover, I'm also trying to remove 'readonly' attribute from the textbox, add a class, and delete text in the textbox.
I have
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
This code doesn't work for me.
Thanks,
Phillip
Thanks everyone for answers.
According to your comments and answers, I've changed my code but it's still not working.
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').prop('readonly', true);
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text('disabled');
}
else {
$('#TextBoxSectionCode').prop('readonly', false);
$('#TextBoxSectionCode').removeClass('disabled').addClass('enabled');
$('#TextBoxSectionCode').text('');
}
});
I'm using chrome browser to run this code, and using developer tools in chrome and put a break point at the code above to see what's happening in the jquery. However, when I click the check box to check/uncheck, nothing happens there.
document.getElementById('TextBoxSectionName').val this is wrong. You really should cache your jQuery object so it's not navigating the DOM over and over. Then you mix in native JS and .val is not a DOM property or method, nor is it a jQuery property, it should be .value for a DOM object or .val() for a jQuery object.
Obligatory explanation by #Archy Wilhes:
"Just to clarify; when #SterlingArcher says caching the jQuery object,
she/he means doing something like var obj = $('#TextBoxSectionCode')
then calling the functions using the variable like this:
obj.attr(...); obj.addClass(...). Every time you do a $(something) you
are calling a function in jQuery that looks for the DOM."
since everytime you are adding the class the element is going to end up having both the two classes. Consider removing the other class before adding one. For example,
$(selector).removeClass('disabled').addClass('enabled')
Try with change event instead of click:
$('#CheckBoxSectionCode').change(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
You could do the following way.
//Cache reference to DOM as DOM scan is expensive!
var textBox = $('#TextBoxSectionCode');
$('#CheckBoxSectionCode').click(function () {
//Use prop as opposed to attr
textBox.prop("readOnly", false).removeClass('disabled').addClass('abled').text("");
if ($(this).is(':checked')) {
textBox.prop("readOnly", true).removeClass('abled').addClass('disabled').text($("#TextBoxSectionName").val());
}
});
Take the following code,
// Update button clicked
function updateEntity(e) {
e.preventDefault();
var name = $(this).attr("name");
...
// some stuff
...
}
$(document).on("click", ".updateEntity", updateEntity);
Currently I have this for (go figure) updating an entity I've editted on button click. Now, its parameter is particularly expecting a jQuery event. However, I want to also be able to call this function (end goal: to minimize code) outside of a jQuery event. Like so,
// Do an update but then redirect to prevent adding the same estimate twice.
function createEstimate(e) {
updateEntity(e);
var link = $(this).attr("href");
window.location.href = link;
}
$(document).on("click", ".createEntity", createEstimate);
Question: How would I go about calling updateEntity or setting the function up, so that I can supply it to the click-event handler and call it like a function and still have it used correctly? Is this goal realistic or should I be structuring this differently if I want to achieve such a goal?
(Encase it is not obvious, my current problem is that on the function call updateEntity(e); $(this) becomes window instead of the clicked link.)
Use .call to set this correctly:
updateEntity.call(this, e);
Learn more about this.
I have unordered list of links and i am trying to get the clicked link text.
So when i click on some link i would like to display in paragraph or textbox at the bottom of my list text that is cliked.
So if I have something like this:
item1
item2
item3
If i click on item2 i would like to get it like: "You just clicked:item2 "
And i manage that with this:
jQuery(function () {
$('a').click(function () {
alert('Text is: ' + $(this).text());
});
});
But that is displaying an alert message. then i do this:
jQuery(function () {
$('a').click(function () {
var name = $(this).text();
$("p#selector").text(name);
$("input#textbox").val(name);
});
});
And it works it send text value of a link to paragraph but it disappear really fast, it show it about second and it's gone, is there any way to prevent this? To stop it from disappearing?
Try this:
jQuery(function () {
$('a').click(function (e) {
e.preventDefault();
var name = $(this).text();
$("#selector").text(name);
$("#textbox").val(name);
});
});
e.preventDefault() will prevent the link from doing whatever it is doing by default (which sounds like it could be refreshing the page...).
Here's a demo.
I've also amended your selectors - p#selector is inefficient, you should simply use #selector when selecting by ID, as documented in the jQuery API.
For id selectors, jQuery uses the
JavaScript function
document.getElementById(), which is
extremely efficient. When another
selector is attached to the id
selector, such as h2#pageTitle, jQuery
performs an additional check before
identifying the element as a match.
EDIT: As it's become apparent that the click handler isn't what you need here, try this solution:
Parse the URL to get the current page using a jQuery URL Parser, and then find the link that corresponds to the URL and get the text:
var url = "one.htm";
var linktext = $("a[href='" + url + "']").text();
$('#output').text(linktext);
Working demo of that bit (just do the URL parsing instead of setting the URL manually).
Try preventing the click event from propagating after you handle it by returning false from the function.
jQuery(function() {
$('a').click(function () {
var name = $(this).text();
$("p#selector").text(name);
$("input#textbox").val(name);
return false;
});
});
EDIT 1: Which is functionally identical to the answer provided by #Town, who beat me to it
EDIT 2: return false is not quite identical to .preventDefault() (which prevents the default event from occurring, but does not prevent other registered handlers from firing) or indeed .stopPropagation() (which stops event 'bubbling' and prevents handlers further up the DOM from firing). Returning false causes both but as #Town says, if the handler errors before returning, the default event will occur.
Basically... do what he said.
I have a page that has multiple forms. Anytime the user clicks an input or modifies text in an input I would like a function to be called. Any ideas on how to do this efficiently and in a way where it doesn't require the form IDs?
JavaScript events bubble up. So how about:
$('form').change(function() {
// do something
}).click(function() {
// do something
});
In each case you can query for the element that triggered the event and do what you please.
$('form input').each(function() {
var val = this.value;
$(this).click(function() { }
$(this).blur(function() {
}
});
You can also use delegate for better performance. It would help seeing your source and your exact needs.