I have a problem determining status of an input field. I want JS to determine whether it is disabled or enabled but my code below always return 'false'. What am I doing wrong? Thanks
<input name="ctl00$ctl00$ctl00$ctl00$ContentPlaceHolderDefault$RobinBodyPlaceHolder $LoggedInBodyPlaceHolder$AddEditUser1$EmailTextBox" type="text" value="email#mail.com" id="ContentPlaceHolderDefault_RobinBodyPlaceHolder_LoggedInBodyPlaceHolder_AddEditUser1_EmailTextBox" class="EmailTextBox" disabled="disabled"/>
function ConfirmEmailChange() {
alert($('.EmailTextBox').disabled==true);
}
You're trying to access the disabled property of a jQuery object (I'm assuming it's jQuery, but it could be some other JS library using the $ character), but jQuery objects don't have a disabled property.
If it is jQuery, you can access the actual DOM node contained within the jQuery object using array notation:
alert($('.EmailTextBox')[0].disabled);
Alternatively, you can use the get method:
alert($('.EmailTextBox').get(0).disabled);
Or, as others have shown, you can use the jQuery prop method. Notice that I've removed the == true part, as disabled is a boolean property and will return true or false anyway.
The question isn't tagged jQuery, but since you seem to be using it, you can do this:
alert($('.EmailTextBox').is(':disabled'))
Live Demo
function ConfirmEmailChange() {
alert($('.EmailTextBox').prop('disabled'));
}
Just change it to check the disabled property this way. You were trying to access .disabled which isn't a valid jQuery property.
Related
This is my code:
var chk="checked";
document.getElementById("chk").chk=true;
where I used variable to set attribute in the second line.
but this is not working with no error.
Please help me to find this.
You might want:
document.getElementById("chk").setAttribute(chk, true);
which will set it as HTML attribute (not the object property - for that you'd use [] brackets). This is what you're probably looking for because you're operating on an HTMLElememnt.
To clarify:
setAttribute - set's an attribute on an HTML element. It will turn this: <div> into that: <div checked="true"> (assuming the element under question is a div)
[] - use for plain JS objects. In that case the name 'property' is rather used, not 'attribute'
Also note that if the element is <input>, both approaches will work. That's because HTMLInputElement contains the 'checked' attribute. See HTMLInputElement MDN page for details.
Use like this.
document.getElementById("chk").setAttribute(chk, true);
Try this:
document.getElementById("chk")[chk] = true;
This one sets the property
or use the .setAttribute property
document.getElementById("chk").setAttribute(chk, true);
This will set the attribute. If you are using it on HTML elements then this one is a better pick for you as this will set the HTML attribute.
Try,
document.getElementById("chk")[chk] = true;
You can add variables to any JavaScript object which is why the code will run without an error, but -- as you've observed -- it won't have any side effects if the property is not a predefined, semantically meaningful one. For that, you should read some documentation for the given element. For the checkbox element, the name of the property you are looking for is checked. (Note that using the dot syntax treats the text to the right as the name of the property, it does not evaluate it, first. For dynamic evaluation of the property name, use the [] syntax for normal objects and setAttribute for HTML attributes).
chk is a javascript variable in your case. When you getElementById, it refers to the HTML document and the tags in it. Example,
<input id=appleId type="radio" name="fruit" value="Apple" />
In JS, you can then say,
document.getElementById("appleId").checked = true;
Refer to How can I check whether a radio button is selected with JavaScript?
After reading (the interesting) .prop() vs .attr() and jQuery Performance : attributes doubt arise in my mind about what is better to use: .prop() or .val() ? I want to set an input text value.
The jQuery .prop() page said the following:
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.
But regarding to performance .prop() seems to be better than .val() setting values:
So I don't have an answer.
What I should do?
$('#element').prop('value', 'Example');
or
$('#element').val('Example');
EDIT1:
.prop() is always better than .val()
EDIT2:
I've tried now getting a value, also .prop() is faster
EDIT3:
As #BeatAlex says if we want performace native js is extremely faster
var x = document.getElementById('element').value;
As some of you said it may be faster, but if .val() exist we'd use it.
PS: while I am writing this, current jQuery version is 1.11 or 2.1
You want to use val(). That's what the function is for, specifically for the value of the input.
It's also quicker to write, easier to understand and while using val, you can change the value multiple times if need be.
Your chart says
Higher is better
and val() higher.
Also, like you've already quoted,
The .val() method should be used for getting and setting value.
This means that unless you're dealing with disabled properties, use:
$('input').val();
Also as a side note, the link you posted, after running tests, shows that val() is faster than prop().
Since you LOVE to show some graphs and pictures, i'm going to add some:
Taken from this link
Pure JS is better if you're arguing over speed.
Dude, you cannot compare prop to val, that makes no sense!
val is designed to set/get the attribute "value" from the current selected node(s). So that's the only method you need for your use-case. (I want to set an input text value).
Of course you can workaround val by using attr('value') or prop('value') but why do you want to make boilerplate code?
You seem to be confused on what prop was designed for. So let me explain a little.
prop was designed to solve the issue of retrieving Boolean-like properties from the selected DOM node. It should be compared to the method attr not to val
Consider the following four cases
<input type="checkbox" checked />
<input type="checkbox" checked="checked" />
<input type="checkbox" checked="false" />
<input type="checkbox" checked="true" />
You will never ever get the state checked/unchecked of the input using val()
You are not sure what is the checked state of the control if you retrieve it using attr('checked'). This will give you back a string.
If you use the result of attr('checked') inside of an if statement, you are at risk of getting false positives, e.g., if('false')
The only way to consistently get the checked state out of the control is by using the prop method.
So if you wanna make a real comparison please compare it to attr, not to val
The other answers explain the main differences pretty well with one exception.
Since jQuery "normalizes" browser differences val() removes carriage returns.
This affects textareas in IE 8 and below.
Example:
For the textarea input of
HEL
LO
.val() gives you the string "HEL\n\nLO" and a length of 7
.prop("value") gives you the string "HEL\r\n\r\nLO" with a length of 9
Your charts are indicating that prop() is better than val() in terms of performance.
val() could be internally using the same logic of prop() along with some additional code statements for completing the actual operation(Ex: setting value), that additional code of val() might lead to little low performance than prop().
It would be nice to use val() for setting a value for an element perhaps that is what this function is meant for, in general it's preferred to go with the operation specific functions instead of using the generic ones.
In your case, if you don't want to loose even a slight variation in performance then go with prop() itself.
That's not a question of performance, they are actually made for quite different things. jQuery seems to have decided to handled "out of spec" usecase, probably for good reason.
attr() is to access the HTML attribute of the element. More probably the initial value as when the page loaded. It though has been altered by the write version of attr() or any other attribute manipulation function
prop() is to access the DOM property of the element, after it has been parsed and displayed.
val() is to access a form element value.
One more bug when using prop(). Under IE 11, the following code wouldn't set the value:
var props = {'value':'test', 'type':'radio'};
var input = $('<input/>').prop(props);
$(document.body).append(input);
I'm using the following code to loop through all the checkboxes in my form. The boxes are gerenated dynamicaly from a php script so I won't know the names or the number of check boxes.
I need to find out which checkboxes have been ticked so I only pass those ones to the php script that handles the form.
$("#panelform input:checkbox").each(function () {
if(this.is(":checked")){
fields = fields+"&"+this.name+"="+this.value;
}
});
When the script gets to the this.is(":checked") it errors but being jquery my console doesn't show me any error messages just stops.
if I alert or console.log "this" after the first line I get the form field so I know that that much works.
try with
if($(this).is(":checked")){
since this is just a reference to the node in the DOM (and you need instead to use the jQuery wrapper to chain the method is().
Try this:
if( this.checked)
this is the plain DOM node, checked is its property to tell you if it's checked or not. Creating a whole new jQuery object just to see if a property is set is redundant.
In that contect, this refers to the DOM element, not the jQuery object - and DOM elements have no method is(). You can wrap it in a jQuery object if you want to use is method:
if($(this).is(":checked")){
or use the DOM Element's checked property:
if(this.checked){
$(this).is(':checked')
if you want to serialize your form try this
$('your-form-selector').serializeArray()
I am trying to use JQuery to get the type of control and following is the code that I am using.
$('#selCity').attr('type')
where selCity is of type select. When I try the above code it returns as undefined but when I use the alternative code with Javascript, it returns the correct type.
Please look into this fiddle to understand it clearly: http://jsfiddle.net/Ye8e9/
Could someone advice on how I can acheive this correctly using JQuery? Is this an issue with JQuery or am I making a mistake?
Use
$('#selCity').prop('type')
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.
Reference
DEMO
if you mean the type of tag, the use this
$("#selCity").get(0).tagName
See your demo here
Use nodeName to get 'type of Tag'. '.type' refers to attribute 'type' which select doesn't have.
document.getElementById('selCity').nodeName
you are getting undefined because there is not type attribute in select.
try this one
$('#selCity')[0].tagName;
If you removeProp on something you should have used removeAttr() on will it silently fail? Will it work? Will it actually remove the entire attribute or just the value inside it?
If checked is added using removeProp(), can it be removed with removeAttr()?
Many questions!
The official jQuery blog provides a very clear explanation:
In the 1.6 release we’ve split apart
the handling of DOM attributes and DOM
properties into separate methods. The
new .prop() method sets or gets
properties on DOM elements, and
.removeProp() removes properties. In
the past, jQuery has not drawn a clear
line between properties and
attributes. Generally, DOM attributes
represent the state of DOM information
as retrieved from the document, such
as the value attribute in the markup
. DOM
properties represent the dynamic state
of the document; for example if the
user clicks in the input element above
and types def the .prop("value") is
abcdef but the .attr("value") remains
abc.
In most cases, the browser treats the
attribute value as the starting value
for the property, but Boolean
attributes such as checked or disabled
have unusual semantics.
For example, consider the markup
<input type="checkbox" checked>. The
presence of the checked attribute
means that the DOM .checked property
is true, even though the attribute
does not have a value. In the code
above, the checked attribute value is
an empty string (or undefined if no
attribute was specified) but the
checked property value is true.
Before jQuery 1.6, .attr("checked")
returned the Boolean property value
(true) but as of jQuery 1.6 it returns
the actual value of the attribute (an
empty string), which doesn’t change
when the user clicks the checkbox to
change its state.
There are several alternatives for
checking the currently-checked state
of a checkbox. The best and most
performant is to use the DOM property
directly, as in this.checked inside an
event handler when this references the
element that was clicked. In code that
uses jQuery 1.6 or newer, the new
method $(this).prop("checked")
retrieves the same value as
this.checked and is relatively fast.
Finally, the expression
$(this).is(":checked") works for all
versions of jQuery.
An attribute of an element is something like 'class'. Whereas its property would be 'className'.
This is the reason for adding jQuery.prop and jQuery.propHooks into version 1.6, to make it easier working with both.
So if the the property had the same name as the attribute you could use both removeProp or removeAttr.
I asked a similar question on jQuery forum, got this answer:
Yes, attr is meant for html attributes
as they are strictly defined. prop is
for properties. So for instance, say
you have a node elem with class
"something" (raw element not jQuery
object). elem.className is the
property, but is where the
attribute resides. Changing the class
attribute also changes the property
automatically and vise versa.
Currently, attr is jumbled and
confusing because it has tried to the
job of both functions and there are
many bugs because of that. The
introduction of jQuery.fn.prop will
solve several blockers, separate code
as it should have been separated from
the beginning, and give developers
faster functions to do what they
expect them to do. Let me make up a
percentage for a sec and say that from
my experience in the support IRC and
reading other's code, 95% of the use
cases for attr will not have to switch
to prop.
EDIT
It may be best to stick to using either jQuery.attr or jQuery.prop. Theres seems to be some strange behaviour when setting and removing the checked attribute using both.
See here for an example: http://jsfiddle.net/tomgrohl/uTCJF/
There is a bug in 1.6 to do with selected: http://bugs.jquery.com/ticket/9079
Using jQuery 1.6, I was was trying to clone a menu item which had several id attributes, and so I did this:
$('ul.menu').clone().filter('*').removeProp('id').appendTo('.sidebar');
When I inspected the elements in Firebug I had a lot of id="undefined" - not what I wanted. So now I am using removeAttr and it seems to work much better.
$('ul.menu').clone().filter('*').removeAttr('id').appendTo('.sidebar');