I have a function which simply disables all select elements using following line of code
$('select').prop('disabled', true);
It works fine for all those select elements which already exist in DOM, however. There are several places where select elements are added using javascript/jquery. And above line of code does not disable those elements. One way to work around is that call that particular plugin everytime those select elements are added to the DOM but this would be a lot of work and needs.
Is there a better way to disable all these select elements?
<a id="myBtn" href="#">Insert select</a>
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script>
$(function() {
$("#myBtn").click(function() {
$("body").prepend("<select></select>");
});
$(document).on('DOMNodeInserted', function(e) {
if (e.target.tagName === "SELECT") {
console.log("doing stuff!");
}
});
});
</script>
You need this
$(document).on('DOMSubtreeModified', 'select', function () {
$(this).prop('disabled', true);
});
you can try somoething like this:
$('body').on('DOMNodeInserted', 'select', function () {
$(this).prop('disabled', true);
});
EDIT: it seems that DOMNodeInserted is deprecated. So you should use MutationObserver.
If you need IE9/10 support you can take a look at Polyfill.
Related
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());
}
});
I am using jquery´s "ui.js" and "ui.css".
When i have this snippet:
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
Everything works fine, but when user chooses one item, i want to fire an event:
$(document).ready(function () {
$('input#tags').on('change', function() {
alert("event")
});
});
It doesnt work, anybody knows how to fire event´s when user select´s item?
Greetings!
Your code works fine as-is:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/Vnhd8/
Couple of notes...
As you are using change and not keyup you need to leave the field for it to fire the event.
The modern/preferred onload syntax is simply $(function{...});
As id's are supposed to be unique on a page, and are the fastest lookup method, adding an input selector before the id may actually slow down the search.
Neater version
$(function () {
$('#tags').on('change', function() {
alert("event")
});
});
If you were to allow for dynamically created elements, use the deferred syntax of on applied to an element that does not change (and is an ancestor of the target):
Deferred "on" version:
$(function () {
$(document).on('change', '#tags', function() {
alert("event")
});
});
If you want per-keypress events instead:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/Vnhd8/4/
$(function () {
$(document).on('keyup', '#tags', function() {
alert('event');
});
});
Only the last JSFiddle above uses jQueryUI (just to make sure it made no different to the events).
I am quite new to javascript, but I am using it at my website. Last week I found a script that loads additional content to my page via jQuery. Everything was all right until I noticed that my other scripts stopped working because of that. For example I have a script that binds checkboxes:
<script>
$(document).ready(
function() {
$('.class_of_checkbox').click(
function() {
if(this.checked == true) {
$(".class_of other_checkbox").attr('checked', this.checked);
}
}
);
}
);
</script>
It is inline code. I have read that it could be caused by function ready(), which fires only when the DOM is loaded, but I am not sure how to solve this problem.
Dynamic elements loaded with ajax needs delegated event handlers :
$(document).ready(function() {
$(document).on('change', '.class_of_checkbox', function() {
if (this.checked)
$(".class_of other_checkbox").prop('checked', this.checked);
});
});
Replace the second document with the closest non-dynamic parent, use prop() for properties, and use the change event to capture changes in the state of a checkbox.
Use $.ajaxComplete to rebind your actions when the ajax call completes
http://api.jquery.com/ajaxComplete/
$(document).ajaxComplete(function() {
$('.class_of_checkbox').click(
function() {
if(this.checked == true) {
$(".class_of other_checkbox").attr('checked', this.checked);
}
}
);
});
I need to trigger click events of "a" tags which are in "deletable" class. I saw some similar question in SO, but following code doesn't work for me. What i'm trying to do is to delete relevant <li> from <ul>.
$(document).ready(function () {
$('.deletable').live("click", function () {
alert("test"); // Debug
// Code to remove this <li> from <ul>
});
});
<form ...>
<ul>
<li>OneDelete</li>
<li>TwoDelete</li>
<li>ThreeDelete</li>
</ul>
</form>
I assume i'm using incorrect object hierarchy inside $('...') tag. But i don't have enough js/jquery/DOM knowladge to solve this problem. please help.
EDIT
Thanks for the answers, but none of them works for me. Actually i'm adding <li>s dynamically. There maybe a problem. Please check,
#sps - a listbox
#add - a button
#splist - another listbox
#remove - a button
$(document).ready(function() {
$('#add').click(function(e) {
var selectedOpts = $('#sps option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#splist').append($(selectedOpts).clone());
$('ul').append('<li>' + selectedOpts.text() + 'Remove' + '</li>');
e.preventDefault();
});
$('#remove').click(function(e) {
var selectedOpts = $('#splist option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$(selectedOpts).remove();
e.preventDefault();
});
});
The .live() method of jQuery has been deprecated. You can get similar functionality using $('body') and delegating to .deletable like I did in the following code:
$('body').on('click', '.deletable', function(e){
e.preventDefault();
// this is the li that was clicked
$(this).parent().remove();
});
The preventDefault method is used to keep the link from loading a new page should there be something targeted in the href attribute. If you keep the same HTML structure as you have in your example, then you can simply take the anchor element (this) and grab the parent, then remove it from the DOM.
It would be wise to, instead of using $('body'), target the container for the .deletable anchors, which, in this case, would be $('ul'). The function would look like this:
$('ul').on('click', '.deletable', function(e){
e.preventDefault();
// this is the li that was clicked
$(this).parent().remove();
});
Using $('body') means that every event on the page would have to be filtered to see if it originated from a .deletable anchor. By scoping it to the ul preceding your li's, you limit the number of times your function is called increasing performance.
Some things first: if you're using jQuery 1.9, the .live() function is not anymore supported. Versions prior, that particular function is deprecated anyway, so you shouldn't really use it.
That being said, your syntax looks about correct. So I'm assuming that it's your hierarchy inside the handler function that's incorrect.
Something like this should work if you're trying to delete the parent <li>:
$('.deletable').on('click', function (e) {
// since you're working with a link, it may be doing wonky default browser stuff
// so disable that for now
e.preventDefault();
// then we delete the parent li here:
$(this).parent('li').remove();
});
If you really want to make that into a delegate signature, something like this should work:
$('form').on('click', '.deletable', function (e) {
// same banana
});
you can use $('a.deletable') selector ... this finds the <a> with class deletable.
u can go through the on delegate events too.. here is the docs
try this
$('a.deletable').on("click",function(){
alert("test"); // Debug
// Code to remove this <li> from <ul>
$(this).parent("li").remove();
});
if in case your <li> is added dynamically..
$(document).on("click",'a.deletable',function(){ .... //even more better if u replace the document with closest elements to a.deletable ..like $(form)
live() is depricated..
$('a.deletable').live("click",function(){
alert("test"); // Debug
$(this).parent('li').remove();
});
I have a list of checkboxes. I need to know which was was clicked.
I can't do a loop with
if(form1.news[i].checked)
Because there can be others that are already checked.
I've tried using
this.form.id
this.from.checkboxname.id
but it didn't work.
The event object will contain a reference to the element that was clicked.
For example (using YUI to abstract the browser differences for event binding, other libraries do similar things and you can use raw DOM if you don't mind abandoning old-Internet Explorer):
YUI().use('node', 'event', function (Y) {
Y.one('#container').delegate('click', function (e) {
alert(e.target.get('value'));
e.stopPropagation();
}, 'input[type=checkbox]');
});
UPDATED DEMO:
$(function() {
$('#myButton').click(function() {
$('input:checkbox:checked').each(function(i) {
alert(this.value);
});
});
});
If your onclick() function is on the checkbox, this.id should work just fine.