jQuery selector, contains to equals - javascript

I have the folowing selector
var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
.find("option:contains('LIKE')");
this checks for an option which contains the word 'like' right?
How do i find an option which is exactly with the word 'like'?
Somthing like this:
var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
.find("option:equals('LIKE')");

Just select all the options from the select and filter them by text() value:
var likeComperssionOption = $('select[id*=ComparisionType]:first option').filter(function() { return $(this).text() == "LIKE" });

If you want to select based on the value attribute of the options, you need to use the attribute equals selector to select elements with a specific value for their value attribute:
var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
.find("option[value='LIKE']")
Otherwise, to select based on the display text of the options, use:
var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
.find("option").filter(function() {
return $(this).text() == 'LIKE';
});
Update: You might be having some problems with your initial selector, it looks very strange. You should probably change
$('select[id*=ComparisionType]').eq(0)
to something simple like
$('#ComparisionType')
The concept of this answer works fine, you can see it in action here.

Related

Programmatically set the text of a select - jquery

I need to programmatically set an option of an existing select box when I only know the text of the option and not the value.
Here is my code:
$("#" + eventQuestions[x].code).find('option[text="' + eventAnswers[x].vAnswerString + '"]').attr("selected");
Don't focus too much on selecting the right html element or the right text being inside the vAnswerString - I can confirm those are correct.
Basically the option is not being selected. What is wrong with my code?
Check out this answer.
You can use that filter to check the inner text and then you put the selected attribute like this:
.attr("selected", true);
Example I tested it with:
$(function() {
$("#select").find("option").filter(function() {
return this.innerHTML == "InnerText";
}).attr("selected", true);
})
Here is a working example for jquery 1.6+.
Select the option using the filter function:
var text = "theTextToFind";
var matchingOption = $("select#myselect option").filter(function () {
return $(this).text() == text;
});
Set the value using the property function:
matchingOption.prop('selected', true);
Also check out this Answer.

How to select the DropDownList/Select that triggered the change event

I'm new to JQuery and I noticed this line $('#DivID [type=checkbox]') and I was wondering if I can also find the select or option tags using the same method.
Update: I have a div that has more than more tag, I'm trying to get the DropDownList/Select that it's value's just changed.
Update2 I'm using InstaFilta a JQuery plugin that filter the content based on a customized attribute appended to my content tags. Below is a snippet for the function that do the same when working with CheckBoxes, and I'm trying to edit it to work with DropDownLists/Select controls.
var $ex10Checkboxes = $('#ex10 [type=checkbox]');
$ex10Checkboxes.on('change', function() {
var checkedCategories = [];
$ex10Checkboxes.each(function() {
if ($(this).prop('checked')) {
checkedCategories.push($(this).val());
}
});
ex10.filterCategory(checkedCategories, true);
});
You would find the option tags as follows:
$("#DivID option")
Likewise the select tags:
$("#DivID select")
You can then iterate over the returned objects to inspect the individual elements:
var foo = $("#DivID option");
var i;
for (i = 0; i < foo.length; i += 1) {
console.log(foo[i].val()); //or whatever
}
To find the selected element you could check out this question:
$("#DivID option:selected")
I would suggest checking out the JQuery page on Selectors JQuery Selectors

Filling a select box of a form using the text inside the <option> tags with CasperJS

I would like to fill the "Acheter un billet" form of this site : http://www.leguichet.fr/
This is what I've done so far :
var casper = require('casper').create();
casper.start('http://www.leguichet.fr/', function() {
this.fill('form#search_tickets', {'departure':'1', 'arrival':'2'}, false);
this.click('input[value="Rechercher"]');
this.wait(1000, function() {
this.echo(this.getCurrentUrl());
});
});
casper.run(function(){
this.exit();
});
The documentation says that fill() uses the value attribute to match against but I would like to use the text inside the option tags. For instance they have :
<option value="Montpellier">Montpellier</option>
<option value="Montpellier">Béziers</option>
Thus if I want to select Béziers I have to write 'departure':'Montpellier'.
Is there a way to use the text inside the option tags?
The easiest way would be to retrieve the element value of the option that you want to select and use that value later. It may be the case that during the subsequent selection another option is selected, but the value will be the same, so it should not make a difference:
var x = require('casper').selectXPath;
casper.start('http://www.leguichet.fr/', function() {
var textToSelect = "Béziers";
var value = this.getElementAttribute(x("//form[#id='search_tickets']//select[#name='departure']/option[contains(text(), '" + text + "')]"), 'value');
this.fill('form#search_tickets', {'departure': value, 'arrival':'2'}, false);
this.click('input[value="Rechercher"]');
this.wait(1000, function() {
this.echo(this.getCurrentUrl())
});
});
You can easily select DOM nodes with XPath by testing their text content with the text() function. Do the same thing for arrival.

Case insensitive jQuery attribute selector

I am doing the following using attribute contains selector $('[attribute*=value]')
<input name="man-news">
<input name="milkMan">
<script>
$( "input[name*='man']").css("background-color:black");
</script>
This works for the 1st input but not the second input as "Man" has a capital "M"
How can I make $( "input[name*='man']") an case insensitive selector?
The simplest way to do this is to add a case insensitivity flag 'i' inside the regex part of the selector:
So instead of
$( "input[name*='man']")
You could do
$( "input[name*='man' i]")
JS fiddle: https://jsfiddle.net/uoxvwxd1/3/
You can always use .filter():
var mans = $('input').filter(function() {
return $(this).attr('name').toLowerCase().indexOf('man') > -1;
});
mans.css('background-color', 'black');
The key part here is toLowerCase() which lowercases the name attribute, allowing you to test it for containing man.
var control = $('input').filter(function() {
return /*REGEX_VALUE*/i.test($(this).attr('id'));
});
*REGEX_VALUE* - the value you want to find
I ended up using regex to validate whether the attribute 'ID' satisfy... regex is much more flexible if you want to find a certain matching value or values, case sensitive or insensitive or a certain range of values...
I was just able to ignore jQuery's case sensitivity altogether to achieve what I want using below code,
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
You can use this link to find code based on your jQuery versions,
https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/
Also there is an article where it does to many good things with jQuery: http://www.ultechspot.com/jquery/using-jquery-search-html-text-and-show-or-hide-accordingly
This works for me using jQuery and if i'm adding item to a table
// check if item already exists in table
var inputValue = $('#input').val(); // input
var checkitem = $('#exampleTable td.value div.editable').filter(function() {
//check each table's editable div matches the input value in lowercase
if ($(this).text().toLowerCase() === inputValue.toLowerCase()) {
itemexists = true;
}
});
if (itemexists) {
alert("item exists in the table");
return;
}

How do I access the "displayed" text of a select box option from the DOM?

Given the following HTML:
<select name="my_dropdown" id="my_dropdown">
<option value="1">displayed text 1</option>
</select>
How do I grab the string "displayed text 1" using Javascript/the DOM?
var sel = document.getElementById("my_dropdown");
//get the selected option
var selectedText = sel.options[sel.selectedIndex].text;
//or get the first option
var optionText = sel.options[0].text;
//or get the option with value="1"
for(var i=0; i<sel.options.length; i++){
if(sel.options[i].value == "1"){
var valueIsOneText = sel.options[i].text;
}
}
var mySelect = document.forms["my_form"].my_dropdown;
// or if you select has a id
var mySelect = document.getElementById("my_dropdown");
var text = mySelect.options[mySelect.selectedIndex].text;
Assuming you want the selected option's text:
var select = document.getElementById('my_dropdown');
for(var i = 0; i < select.options.length; i++) {
if(select.options[i].selected) {
break;
}
}
var selectText = select.options[i].text;
In Prototype:
var selectText = $$('#my_dropdown option[selected]')[0].text;
Edit: And jQuery for completeness' sake (assuming jQuery's CSS selector support is roughly equivalent to that of Prototype's):
var selectText = $('#my_dropdown option[selected]').get(0).text;
The displayed text is a child node of the option node. You can use:
myOptionNode.childNodes[0];
to access it, assuming the text node is the only thing inside the option (and not other tags).
EDIT: Oh yeah, as others mentioned, I completely forgot about:
myOptionNode.text;
Assuming you modified your code a bit to have an id / class on the and were using jQuery you could have something like the following. It will pop up an alert for each option with the text of the option. You probably won't want to alert for all the text, but it illustrates how to get at the text in the first place:
$('select#id option').each(function() {
alert($(this).text());
});
If you use a class instead of an id, then you'd just have to change the 'select#id' to 'select.class'. If you didn't want to add a class/id there are other ways to get at the select.
I leave figuring those ways out if you want to go that route as an activity for the reader.
If you were using Prototype, you could get at it like this:
$$('#my_dropdown option[value=1]').each( function(elem){
alert(elem.text);
});
The above is using a CSS selector that says find all option tags with value="1" that are inside the element that has id="my_dropdown".

Categories

Resources