How to identify that Chosen plugin initialized on element - javascript

Is there a standard way to know that jQuery plugin already initialized at specific HTML element?
I want to make some actions if for example select element is under Chosen plugin.

$("#elementId").data("chosen");
This will return the chosen object assigned to the element, or undefined if not assigned.
Note: For other plugins or JQuery versions I worked with, you may need to check the plugin name suffixed with "Obj":
$("#elementId").data("pluginNameObj");

use this $('select#elementID').attr('data-rel');if it gives you the value "chosen" then the select element is under chosen plugin.

Related

Get dropdown option element by display text

I've currently been selecting dropdown elements by using:
$('#dropdownId option[value="value"]')
because most of my elements have been written as
<option value="value">value</option>
However, now I've come across some elements in this project that do not have the value attribute and instead look like
<option>value</option>
Now I'm struggling to select it using the same syntax that I used prior. I'd like to get the element (not just change the selection) using the same style as before, because it's a format that's used dynamically throughout the project. I've tried these so far:
$('#dropdownId option[value="value"]'); // doesn't work, I'd assume because it doesn't have a value attribute
$('#dropdownId option[text="value"]'); // Doesn't work, I'd assume because "text" isn't actually an attribute
$('#dropdownId option[label="value"]'); // Doesn't work, I'd assume because even though the value is used as the display text, it's not actually specified in the attributes.
I can't add a value="value" to the object, I don't have control over the html.
Edit: I realize that WebdriverIO, while it uses selectors similar to jQuery, doesn't necessarily have all of the same functionality. Nathan Hinchey's seems to work for normal jQuery though.
Stolen whole cloth from this answer:
You can use the jQuery contains selector
$('option:contains("value")')
You could dynamically alter the HTML by adding a value attribute to option elements that don't have one and use the .text() of the option as the .value. Then, you could continue to select options as you already are. There are performance cost to altering the DOM (perhaps extensively) so beware of that.
// Get all the <option> elements that don't have a "value" attribute and iterate the group
$("option:not([value])").each(function(){
// Create the "value" attribute for the option and give it the value of the
// current option element's text.
$(this).attr("value", $(this).text());
});
console.log($("select").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>one</option>
<option>two</option>
<option>three</option>
</select>
Nathan Hinchey's answer works for people using base jQuery.
For people who are using WebDriverIO, I found this discussion which uses the selector
$('<element>*=<text>').
So, for my example, I used
$('option*=value')
However, I noticed that I couldn't nicely chain various selects in the single select, such as
$('select#selectId option*=value') // WON'T work
If you need to chain any selections prior to it, such as maybe the select object containing the options, instead use
$('option*=value').$(elementSelector)
I'm currently using this to get the parent object, the object.
$('option*=value').$('..')

.eq() out of order

I'm trying to select the 3rd element of a JQuery object, by using eq() method. But for some reason the 2nd and 3rd selections pop out in changed order:
var selection = $("[name=input0], [name=input1], [name=input2], [name=input3]");
selection.eq(1); //turns out to be input2!!
What could be the reasons for this behavior? Can I trust acessing it by index in my script?
According to:
https://api.jquery.com/multiple-selector/
The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
With the help of the answers and comments and a bit of reading on the documentation.
Turns out that jQuery selects elements in the order they appear in the DOM (HTML), so:
Using a direct array access to a jQuery selection will work if you use that order, but you can only trust it if you are also responsible for the HTML, and you would need to remember this if you are ever going to change the layout.
Bottom line: not the best way to select a specific element.

jquery .focus not working for input:first

We are having an issue where when we open a modal window we are trying to set the focus to the first input element in the modal that is not of type hidden. here is what we are trying:
$("#test-overlay input[type!=hidden]:first").focus();
However, this call works:
$("#test-overlay #loginInput").focus();
The input field has an id of loginInput.
Any thoughts?
The problem is due to the order of precedence in which jQuery interprets the selector. Try the following:
$('#test-overlay input').not('[type=hidden]').first().focus();
This has the added benefit of not using the :first and attribute not equal to selectors since they're jQuery specific and queries using these cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method.

What is the difference between removeProp and removeAttr in JQuery 1.6?

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');

jQuery .attr() and value

I want to make the following use .attr();
selectbox.options[selectbox.selectedIndex].value
sadly,
selectbox.options[selectbox.selectedIndex].attr("value")
is not the same, and seems to defeat the purpose of the .attr altogether. My main question is: How should one use nested .attr()s?
To get the value of any type of input element (including <textarea> and <select>) use .val():
var value = $(selectbox).val();
The .attr() translation would roughly be:
$(selectBox).find(":selected").attr("value");
....but just use .val() :)
The basic problem is that .attr() is a jQuery method. It's on jQuery objects, not on DOM elements directly, the same goes for almost all jQuery methods and plugins.
When using attr(), you have to be working with a jQuery object. So first select the relevant select box, then call attr() (or val() in this case, when you need the value of an input element).
var value = $(selectbox).val();
If you would like to retrieve the selected box's value using your current code simply pass it into the jquery object like so.
$(selectbox.options[selectbox.selectedIndex]).attr('value');
The reason they are not the same is because attr('value') gets the value of the value attribute directly from the original HTML code, it is not updated with the DOM, meaning if the value of value is changed after the page has loaded, either by user input (typing into an <input> element, or via manipulation with JavaScript, these changes will not be reflected in the returned value of .attr().
A better way is to use the .val() method of the jQuery object.
Edit
To get the attribute of the value from a DOM Element (i.e. not returned by the $() or jQuery() function) use the element.getAttribute() method, which is native, you would use it like this:
selectbox.options[selectbox.selectedIndex].getAttribute("value");

Categories

Resources