$input.disabled = true;
or
$input.disabled = "disabled";
Which is the standard way? And, conversely, how do you enable a disabled input?
jQuery 1.6+
To change the disabled property you should use the .prop() function.
$("input").prop('disabled', true);
$("input").prop('disabled', false);
jQuery 1.5 and below
The .prop() function doesn't exist, but .attr() does similar:
Set the disabled attribute.
$("input").attr('disabled','disabled');
To enable again, the proper method is to use .removeAttr()
$("input").removeAttr('disabled');
In any version of jQuery
You can always rely on the actual DOM object and is probably a little faster than the other two options if you are only dealing with one element:
// assuming an event handler thus 'this'
this.disabled = true;
The advantage to using the .prop() or .attr() methods is that you can set the property for a bunch of selected items.
Note: In 1.6 there is a .removeProp() method that sounds a lot like removeAttr(), but it SHOULD NOT BE USED on native properties like 'disabled' Excerpt from the documentation:
Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.
In fact, I doubt there are many legitimate uses for this method, boolean props are done in such a way that you should set them to false instead of "removing" them like their "attribute" counterparts in 1.5
Just for the sake of new conventions && making it adaptable going forward (unless things change drastically with ECMA6(????):
$(document).on('event_name', '#your_id', function() {
$(this).removeAttr('disabled');
});
and
$(document).off('event_name', '#your_id', function() {
$(this).attr('disabled','disabled');
});
// Disable #x
$( "#x" ).prop( "disabled", true );
// Enable #x
$( "#x" ).prop( "disabled", false );
Sometimes you need to disable/enable the form element like input or textarea. Jquery helps you to easily make this with setting disabled attribute to "disabled".
For e.g.:
//To disable
$('.someElement').attr('disabled', 'disabled');
To enable disabled element you need to remove "disabled" attribute from this element or empty it's string. For e.g:
//To enable
$('.someElement').removeAttr('disabled');
// OR you can set attr to ""
$('.someElement').attr('disabled', '');
reference: http://garmoncheg.blogspot.fr/2011/07/how-to-disableenable-element-with.html
$("input")[0].disabled = true;
or
$("input")[0].disabled = false;
There are many ways using them you can enable/disable any element :
Approach 1
$("#txtName").attr("disabled", true);
Approach 2
$("#txtName").attr("disabled", "disabled");
If you are using jQuery 1.7 or higher version then use prop(), instead of attr().
$("#txtName").prop("disabled", "disabled");
If you wish to enable any element then you just have to do opposite of what you did to make it disable. However jQuery provides another way to remove any attribute.
Approach 1
$("#txtName").attr("disabled", false);
Approach 2
$("#txtName").attr("disabled", "");
Approach 3
$("#txtName").removeAttr("disabled");
Again, if you are using jQuery 1.7 or higher version then use prop(), instead of attr(). That's is. This is how you enable or disable any element using jQuery.
Use like this,
$( "#id" ).prop( "disabled", true );
$( "#id" ).prop( "disabled", false );
You can put this somewhere global in your code:
$.prototype.enable = function () {
$.each(this, function (index, el) {
$(el).removeAttr('disabled');
});
}
$.prototype.disable = function () {
$.each(this, function (index, el) {
$(el).attr('disabled', 'disabled');
});
}
And then you can write stuff like:
$(".myInputs").enable();
$("#otherInput").disable();
If you just want to invert the current state (like a toggle button behaviour):
$("input").prop('disabled', ! $("input").prop('disabled') );
this works for me
$("#values:input").attr("disabled",true);
$("#values:input").attr("disabled",false);
Update for 2018:
Now there's no need for jQuery and it's been a while since document.querySelector or document.querySelectorAll (for multiple elements) do almost exactly same job as $, plus more explicit ones getElementById, getElementsByClassName, getElementsByTagName
Disabling one field of "input-checkbox" class
document.querySelector('.input-checkbox').disabled = true;
or multiple elements
document.querySelectorAll('.input-checkbox').forEach(el => el.disabled = true);
You can use the jQuery prop() method to disable or enable form element or control dynamically using jQuery. The prop() method require jQuery 1.6 and above.
Example:
<script type="text/javascript">
$(document).ready(function(){
$('form input[type="submit"]').prop("disabled", true);
$(".agree").click(function(){
if($(this).prop("checked") == true){
$('form input[type="submit"]').prop("disabled", false);
}
else if($(this).prop("checked") == false){
$('form input[type="submit"]').prop("disabled", true);
}
});
});
</script>
An alternate way to disable the input field is by using jQuery and css like this:
jQuery("#inputFieldId").css({"pointer-events":"none"})
and to enable the same input the code is as follows:
jQuery("#inputFieldId").css({"pointer-events":""})
Disable:
$('input').attr('readonly', true); // Disable it.
$('input').addClass('text-muted'); // Gray it out with bootstrap.
Enable:
$('input').attr('readonly', false); // Enable it.
$('input').removeClass('text-muted'); // Back to normal color with bootstrap.
Disable true for input type :
In case of a specific input type (Ex. Text type input)
$("input[type=text]").attr('disabled', true);
For all type of input type
$("input").attr('disabled', true);
<html>
<body>
Name: <input type="text" id="myText">
<button onclick="disable()">Disable Text field</button>
<button onclick="enable()">Enable Text field</button>
<script>
function disable() {
document.getElementById("myText").disabled = true;
}
function enable() {
document.getElementById("myText").disabled = false;
}
</script>
</body>
</html>
I used #gnarf answer and added it as function
$.fn.disabled = function (isDisabled) {
if (isDisabled) {
this.attr('disabled', 'disabled');
} else {
this.removeAttr('disabled');
}
};
Then use like this
$('#myElement').disable(true);
2018, without JQuery (ES6)
Disable all input:
[...document.querySelectorAll('input')].map(e => e.disabled = true);
Disable input with id="my-input"
document.getElementById('my-input').disabled = true;
The question is with JQuery, it's just FYI.
Approach 4 (this is extension of wild coder answer)
txtName.disabled=1 // 0 for enable
<input id="txtName">
In jQuery Mobile:
For disable
$('#someselectElement').selectmenu().selectmenu('disable').selectmenu('refresh', true);
$('#someTextElement').textinput().textinput('disable');
For enable
$('#someselectElement').selectmenu().selectmenu('enable').selectmenu('refresh', true);
$('#someTextElement').textinput('enable');
Related
I have a simple code that I'm trying to wrok into my website to clear a textbox with a default value, when a user click on it, the default value should clear out so that the user can enter his/her value. Here is what I have but I'm not sure if its correct since its not working. I just started on JQuery
$(document).ready(function()
{
$('#startDateBox').click(function()
{
if(('#startDateBox')=='Beginning')
{
$('#startDateBox').val('');
}
})
});
You missed the first .val(), and the $ in front of the ('#startDateBox') on the same line.
You could also use $(this) to reference the textbox, as within that function this refers to the textbox DOM element itself. Wrapping it with the jQuery function $() gives you access to all the framework's goodies.
$(document).ready(function()
{
$('#startDateBox').click(function(){
if($(this).val() == 'Beginning')
^^^^^^ Here
{
$(this).val('');
}
})
});
You're wrong in this part:
if(('#startDateBox')=='Beginning')
First, you missing $.
Second, I think you want compare the startDateBox value, then use val().
Try this:
$(document).ready(function()
{
$('#startDateBox').click(function()
{
if($('#startDateBox').val()=='Beginning')
{
$('#startDateBox').val('');
}
})
});
Well, if(('#startDateBox')=='Beginning') will always be false...
I think you meant something more like:
if($('#startDateBox').val() == 'Beginning')
I wrote a very small jquery plugin for this purpose recently:
https://gist.github.com/rmcvey/5136582
$('#input').placeholder("Placeholder Text");
if($('#input').val() === $('#input').placeholder()){ return false; }
I would suggest for HTML5 browsers use this
<input type="text" id="Beginning" placeholder="Beginning" />
if($('#startDateBox').val() =='Beginning')
this is the line that needs to be changed
also
$('#startDateBox').on("focus", function()
{
// code here
the click will not handle hitting tab until that text box is focused
I have a jsfiddle here.
jQuery
$(function() {
//var input = $('form :input[type="text"]')
$('form :input[type="text"]').live('keyup', function() {
$('form .create-playlist-button')
.attr('disabled', $('form :input[type="text"]').val().length == 0);
});
});
Needed
When I start entering the data in the textbox, create should be enabled.
When I remove all text from the textbox, create should be disabled.
I am very new to jQuery and this thing is not working for me.
$('form :input[type="text"]').live('keyup', function() {
var val = $.trim(this.value); // this.value is faster than $(this).val()
$('form .create-playlist-button').prop('disabled', val.length == 0);
});
DEMO
Here, I used .prop() instead of .attr(), according to jQuery doc .prop() should be use. I also used .trim() for removing the whitespace from the beginning and end of value.
About your code
In your code you used $('form :input[type="text"]') two times, one for bind event and one to getting the value of text field. But that is not necessary, because within keyup event handler function this will refers to that input element on which keyup event binded.
If you sometime need to use any selector multiple times for any purpose it will be better to cache that in a variable and reuse that variable. Just for example:
var input = $('form :input[type="text"]');
input.on('click', function() {
alert( this.value );
input.addClass('something');
});
If would be better if you use .on() instead of .live() for delegate event handler, because .live() has been deprecated.
You can use .on() like following:
$('form').on('keyup', ':input[type="text"]', function() {
var val = $.trim(this.value);
$('form .create-playlist-button').prop('disabled', val.length == 0);
});
Note
Syntax of .on() for delegate event handling is like:
$(staticContainer).on( eventName, target, handlerFunction )
Here, staticContainer point to an element which belong to DOM at page load, i.e which is not dynamic and also container of target on which you want to bind your event.
Just for some more go here
.prop() vs .attr()
http://forum.jquery.com/topic/whats-the-difference-between-jquery-attr-and-jquery-prop
Updated:
$(function(){
//var input = $('form :input[type="text"]')
$('form :input[type="text"]').live('keyup',function(){
$(this).closest('form').find('.create-playlist-button').prop('disabled',$(this).val().length==0);
});
});
In the "keyup" handler, you use this (or $(this) to use it via jQuery) to get at the text field that's actually involved. I also changed the code to ensure you'll find the correct "companion" button. It looks up the chain of parent elements to find the enclosing <form>, then finds the button inside that form.
The way you're assigning the event handlers is deprecated. It should be:
$('form').on('keyup', ':input[type="text"]', function(){ ...
Also if you checked for "keypress" instead of "keyup" you'd fix the bug wherein the button doesn't work until the second character.
edit — oh and one more thing: you should usually use .prop() to update attributes, not .attr(). It's a confusing thing about the newer jQuery API, but the times you need to use .attr are kind-of rare. Unfortunately, there's a ton of old instructional material out there that was written back before jQuery 1.6 was released.
You should use the .change() method !
And inside it juste do a test:
if ($(this).val().length > 0)
...
else
...
here ya go... using your original fiddle:
http://jsfiddle.net/9kKXX/4/
Only a small change is necessary.
$(function(){
//var input = $('form :input[type="text"]')
$('form :input[type="text"]').live('keyup',function(){
$('form .create-playlist-button').attr('disabled',$(this).val().length==0);
});
});
Fiddle: http://jsfiddle.net/9kKXX/36/
I can't figure out why my button won't re-enable when another button is clicked. Any help will be most appreciated
My code is as follows:
$(document).ready(function() {
$('#btnAdd').click(function() {
// enable the "remove" button
$('#btnDele').attr('disabled','');
}
});
demo here: http://jsfiddle.net/ATzBA/2/
$('#btnDele').attr('disabled',false);
should do the trick.
You could also try $("#btnDele").removeAttr('disabled');
The prop function is the correct way to do this in JQuery.
$('#btnDele').prop('disabled', false); //enabled
$('#btnDele').prop('disabled', true); //disabled
$('#btnDele').prop('disabled'); //returns true if disabled, false if enabled.
See documentation here.
The "disabled" attr has to be removed completely, not just set to null/an empty string. You need to use jQuery's removeAttr():
$(function(){
$('#btnAdd').click(function(e){
$(this).removeAttr('disabled');
});
});
Somebody talks about it/browser compatibility issues here: Toggle input disabled attribute using jQuery
Instead of using the .attr function I'd use Jquery UI and use $('#btnDele').button("enable");
http://docs.jquery.com/UI/Button#methods
$(document).ready(function() {
$('#btnAdd').click(function() {
// to enable the "remove" button
// set 'disabled to false'
$('#btnDele').attr('disabled','false');
});
});
This is pretty standard stuff here, and I cannot understand why it isn't working.
When the enable function is called, I receive my alert but the select fields are still disabled. Any thoughts?
$(window.document).ready(function() {
$('#selectmenu1').attr('disabled','true');
$('#selectmenu2').attr('disabled','true');
$('#selectmenu3').attr('disabled','true');
});
function enableCoreChange(){
alert('called');
$('#selectmenu1').attr('disabled','false');
$('#selectmenu2').attr('disabled','false');
$('#selectmenu3').attr('disabled','false');
}
The click event:
Click here to enable
It's driving me crazy!
Pass a boolean, not a string, as the second parameter of .attr().
$(function() { // use document ready shorthand
// combine the selectors to stay DRY
$('#selectmenu1, #selectmenu2, #selectmenu3').attr('disabled', true);
});
function enableCoreChange() {
$('#selectmenu1, #selectmenu2, #selectmenu3').attr('disabled', false);
// alternately:
$('#selectmenu1, #selectmenu2, #selectmenu3').removeAttr('disabled');
}
Note the other general style improvements as well.
HTML:
Click here to enable
jQuery:
function enableCoreChange(){
$('#selectmenu1, #selectmenu2, #selectmenu3').prop('disabled', false);
}
$(document).ready(function(){
$('#selectmenu1, #selectmenu2, #selectmenu3').prop('disabled', true);
$('#enable').on('click',function(e){
e.preventDefault();
enableCoreChange();
});
});
demo jsFiddle
Note:
Instead of $('#selectmenu1, #selectmenu2, #selectmenu3'): starts with ^ selector:
$('select[id^="selectmenu"]').prop('disabled', false);
The attribute "disabled" does not need a value (backward compatibility) as soon as this attribute is available, it is disabled.
To activate it again use this function:
function enableCoreChange(){
alert('called');
$('#selectmenu1').removeAttr('disabled');
$('#selectmenu2').removeAttr('disabled');
$('#selectmenu3').removeAttr('disabled');
}
You should be using .prop() instead of .attr()
http://api.jquery.com/prop/
The problem here is you're specifying the string 'false' instead of the boolean false. Personally I'd use removeAttr for clarity
function enableCoreChange(){
alert('called');
$('#selectmenu1').removeAttr('disabled');
$('#selectmenu2').removeAttr('disabled');
$('#selectmenu3').removeAttr('disabled');
}
Fiddle: http://jsfiddle.net/6pznn/
I have some object (div, input/checkbox) in an HTML page. The values for their "checked" and "disabled" attributes are set via some JS functions. I want to listen to changes of these attributes, but couldn't find any function or listener to perform that.
How can I add an event listener that listen on changes of "checked" or "disabled" and execute some code (e.g. changing style of checkbox / div) depending on the attributes' status?
Thanks
Regarding the "disabled" change, you may be able to listen to DOMAttrModified events. See this test case for details:
http://jsfiddle.net/4kWbp/1/
Note that not all UAs support DOM mutation events like DOMAttrModified, and in those that do support them, listening to them may cause performance to detoriate.
Setting .checked directly does not trigger "change" events, and doesn't seem to trigger DOMAttrModified either (only tested in Opera though, and this is the sort of under-specified between-the-spec-gaps stuff that might well be very inconsistent across browsers. Perhaps it's an Opera bug.)
The last resort would perhaps be defining getters/setters for those properties. That would be a rather ugly hack though..
You can use the pseudo-selectors for :checked and :disabled and trigger an empty animation which causes an animationstart event. For example:
select > option:checked {
animation: checked 1ms;
}
select > option:not(:checked) {
animation: unchecked 1ms;
}
#keyframes checked { from {}; to {}; }
#keyframes unchecked { from {}; to {}; }
and then in javascript you can use:
document.body.querySelector('select').addEventListener('animationstart',
function (ev) {
console.dir(ev);
});
The event has available animationName and target properties which give you enough to work with.
$('#Checkboxid:checked') this will return true if checkbox value is on and false if checkbox value is off.
this is jquery selector function :checked can be use to check radio and checkbox values.
syntax is as follows:
$('#checkboxid:checked')
To 'listen' to when a checkbox has been toggled use change():
$('.target').change(function() {
console.log(this.checked ? 'Checked' : 'Not Checked');
});
Use the :checked to determine the checked radio or checkbox on the page or container.
First of all check this jsfiddle
after this follow this stackoverflow question Jquery get selected checkboxes to write for your desired result.
you can check disabled or not as:
var set=1;
var unset=0;
jQuery( function() {
$( '.checkAll' ).live('click', function() {
$( '.cb-element' ).each(function () {
if(set==1){ $( '.cb-element' ).attr('checked', true) unset=0; }
if(set==0){ $( '.cb-element' ).attr('checked', false); unset=1; }
});
set=unset;
});
});
Check these links for detail:
Jquery get selected checkboxes
Setting "checked" for a checkbox with jQuery?
I don't have answer to your question, but I could suggest you to try something like Event Bus (in GWT is Event Handler).
For JQuery you can use Events.