Get dropdown option element by display text - javascript

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').$('..')

Related

.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.

How to identify that Chosen plugin initialized on element

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.

How to define span tag within an option of a drop down list

I am using HAML to create a drop down list as shown below:
%select.categories
%option{:category => 'question'}
Top Questions in
%span#topic-name
%option{:category => 'muse'}
Top Muses in
%span#topic-name
%option{:category => 'user'}
Top Users in
%span#topic-name
.clear
My intention is to add the topic name to the span id 'topic-name'. However when I try to find the span using jQuery $('#topic-name'), an empty array was returned.
I checked the generated HTML and I was not able to see the span tags defined
Can anyone advise me on how I can create a span with the purpose of adding a 'topic name'
Thanks
HTML cannot be inserted inside option elements - only text. What you are asking cannot be achieved.
Alternatively, you could add the topic name as a data-x parameter, although this would only be valid in HTML5. I don't know how to achieve this in HAML, but the HTML would look like:
<select>
<option data-topicname="ABC">Top Questions in</option>
</select>
As #Rory McCrossan said, you cannot have a span inside of an option. It is invalid HTML.
You can however find the Option you want to modify and use JQuery's .append() function to insert the new text.
For example:
%select.categories
%option{:id =>'optQuestion', :category => 'question'}
Top Questions in
The JQuery to add text would be
$('optQuestion').append("some text"); // where "some text" is what you want to insert
If you have multiple copies of the same select and want to update them all with the same "some text" you can use a class instead of an ID for your targeting.
The only way to do this is to use a plugin which simulates combobox behavior. I don't know about for jQuery, but ExtJS components have capabilities like that--but they're not provided by standard HTML and CSS as Rory mentioned.
This might be a good starting point:
http://www.designdim.com/2011/07/10-important-jquery-selectboxdropdown-plugins/
you ca use optgroup html tag
see docu here
http://www.w3schools.com/tags/att_optgroup_label.asp
That looks like a good candidate for an optgroup which allows for a non-selectable "header" option and groups its enclosed options together.

I'm having difficult time referencing the correct DOM node via Javascript. What is the issue?

Here's the code:
<script type="text/javascript">
document.write(document.getElementsByTagName("select").value);
</script>
<form>
<select value="slct">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
The rest has been redacted for brevity. I've tried using "nodeValue" and "value" at the end of the string without success. When I cut out the value it outputs "[object]".
I know I'm likely missing something obvious, but I can't seem to get the referencing of elements down. I'm trying to develop a checkbox which enables a dropdown box, but I keep getting stuck at this jumping off point.
Thank you in advance.
The element doesn't exist at the time you call document.getElementsByTagName. Move the script to after the select element, or delay it (e.g. by making it a function you call onload … except you are using the (ugly, problematic, best avoided) document.write which doesn't play nice after the load event fires.
document.getElementsByTagName returns a NodeList, not a single DOM node, so it won't have a value property
value is not well supported cross-browser on select elements. Get the selectedIndex, use that to get the selected option element, then get the value of that element.
Your problem is the getElemenstByTagName returns a node list.
try
document.write(document.getElementsByTagName("select")[0].value
Assuming that is the first select in your document. You can also usegetElementById if you add an id attribute to the select.
getElementsByTagName() returns a NodeList of elements, not a single element. To retrieve the .value you must address one of the elements (as if an array), e.g.
document.write(document.getElementsByTagName("select")[0].value);
Note this returns a list even if there is only one select element on your page.

Setting an attribute to the last position

Is it possible to set a new attribute to the last position of a html element using javascript/jQuery?
This would be helpfull for me in a case where the attribute order is important to decide whether the paragraph has changed or not.
Example:
<p attribute1="true" attribute2="true">
Now, i would like to add a third attribute so that the resulting paragraph would look like
<p attribute1="true" attribute2="true" attribute3="true">
No, it's not possible. Attributes are unordered in HTML and XHTML markup languages, so browsers are free to return them in whatever order they like, e.g. alphabetic, specified, etc.
You should rethink your approach, for instance using the .data() method to track changes:
$("#el").data("changeHistory", []);
// ...
$("#el").data("changeHistory").push(new Date().toString());
Optimally you should never be in a position where you need to read attributes in order (by index).
If you have an element like so <div id="container">, you can add an attribute using jQuery like so $('#container').attr('disabled', true);. Keep in mind this should add the attribute to the end of the element.
Another tip is if you are looking to modify a DOM element attribute such as style, consider looking at the jQuery API to see what methods are avialable before writing anything too crude. For example, if you wanted to add a style you could simply do $('#container').addClass('hover');

Categories

Resources