I need to check if a <select> has an option whose text is equal to a specific value.
For example, if there's an <option value="123">abc</option>, I would be looking for "abc".
Is there a selector to do this?
Im looking for something similar to $('#select option[value="123"]'); but for the text.
This could help:
$('#test').find('option[text="B"]').val();
Demo fiddle
This would give you the option with text B and not the ones which has text that contains B.
For recent versions of jQuery the above does not work. As commented by Quandary below, this is what works for jQuery 1.9.1:
$('#test option').filter(function () { return $(this).html() == "B"; }).val();
Updated fiddle
You can use the :contains() selector to select elements that contain specific text.
For example:
$('#mySelect option:contains(abc)')
To check whether a given <select> element has such an option, use the .has() method:
if (mySelect.has('option:contains(abc)').length)
To find all <select>s that contain such an option, use the :has() selector:
$('select:has(option:contains(abc))')
None of the previous suggestions worked for me in jQuery 1.7.2 because I'm trying to set the selected index of the list based on the value from a textbox, and some text values are contained in multiple options. I ended up using the following:
$('#mySelect option:contains(' + value + ')').each(function(){
if ($(this).text() == value) {
$(this).attr('selected', 'selected');
return false;
}
return true;
});
I faced the same issue below is the working code :
$("#test option").filter(function() {
return $(this).text() =='Ford';
}).prop("selected", true);
Demo : http://jsfiddle.net/YRBrp/83/
This worked for me: $("#test").find("option:contains('abc')");
This is the best method for select text in dropdownlist.
$("#dropdownid option:contains(your selected text)").attr('selected', true);
I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.
$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());
another way of writing it in a more readable fasion:
var valofText = $("#my-Select" + " option").filter(function() {
return this.text == myText
}).val();
$(ElementID).val(valofText);
Pseudocode:
$("#my-Select").val( getValOfText( myText ) );
This work for me
$('#mySelect option:contains(' + value + ')').attr('selected', 'selected');
Use following
$('#select option:contains(ABC)').val();
For jquery version 1.10.2 below worked for me
var selectedText="YourMatchText";
$('#YourDropdownId option').map(function () {
if ($(this).text() == selectedText) return this;
}).attr('selected', 'selected');
});
This works for me:
var result = $('#SubjectID option')
.filter(function ()
{ return $(this).html() == "English"; }).val();
The result variable will return the index of the matched text value. Now I will just set it using it's index:
$('#SubjectID').val(result);
This will work in jQuery 1.6 (note colon before the opening bracket), but fails on the newer releases (1.10 at the time).
$('#mySelect option:[text=abc]")
That was 10 years ago.
Now jquery is EOL, we can use ordinary DOM for this simple job
document.getElementById("SomeSelectId").querySelectorAll("option").forEach(o => o.selected = o.innerText == text);
August 25, 2022.
For jQuery v3.5.1 what really worked for me is this:
$('#selectID option:contains("label")').prop('selected', true);
If you have the text in a variable, do this:
ddText = 'Text to find';
$('#selectID option:contains("' + ddText + '")').prop('selected', true);
use prop instead of attr
$('#mySelect option:contains(' + value + ')').each(function(){
if ($(this).text() == value) {
$(this).prop('selected', 'selected');
return false;
}
return true;
});
This what worked for me on jquery V3.6.0 in 2022
$("#select >option").filter( function()
{
if ($(this).text() === "123")
{
$(this).prop("selected", true);
}
});
This will also work.
$('#test').find("select option:contains('B')").filter(":selected");
As described in this answer, you can easily create your own selector for hasText. This allows you to find the option with $('#test').find('option:hastText("B")').val();
Here's the hasText method I added:
if( ! $.expr[':']['hasText'] ) {
$.expr[':']['hasText'] = function( node, index, props ) {
var retVal = false;
// Verify single text child node with matching text
if( node.nodeType == 1 && node.childNodes.length == 1 ) {
var childNode = node.childNodes[0];
retVal = childNode.nodeType == 3 && childNode.nodeValue === props[3];
}
return retVal;
};
}
This works for me
var options = $(dropdown).find('option');
var targetOption = $(options).filter(
function () { return $(this).html() == value; });
console.log($(targetOption).val());
Thanks for all the posts.
Either you iterate through the options, or put the same text inside another attribute of the option and select with that.
Related
I am using this simple code to filter through a search form with many text inputs and see if they have a value and then add a class.
Works perfectly in Chrome, safari and Firefox but not in IE9.
$('input[type="text"]').filter(function() {
if ($(this).val() !== '') {
$(this).addClass('used');
}
});
Please advice, thanks in advance!
EDIT
Change to each but doesn't solve the issue... Here it is with the event that triggers the function...
$(document).on('event-ajax-form-is-loaded', function() {
$('input[type="text"]').each(function() {
if ($(this).val() !== '') {
$(this).addClass('used');
}
});
});
From the limited information you shared, this is how you should be doing this:
$('input[type="text"]').filter(function() {
return $(this).val() !== '';
}).addClass('used');
.filter() is supposed to reduce a set of matched elements so its filter function should always return a bool instead of manipulating the DOM.
Edit: Based on your updated code snippet and the page link you shared in the comments, if you are using jQuery in WordPress, then its always safer to wrap the code like so:
(function($) {
/* jQuery Code using $ object */
})(jQuery);
enter code hereIn JS you can check the element value by getting their tag name
for (var i = 0; i < document.getElementsByTagName('input').length; i++){
if (document.getElementsByTagName('input')[i].value == "")
{
alert("The value of textbox at " + i + " is empty");
}
}
Working Demo
Or like what other people suggest, use a .each in JQuery
$('input[type="text"]').each(function(i){
if ($(this).val() == "") {
alert("The value of textbox at " + i + " is empty");
}
});
anohter Working Demo
If you insist to use filter and here you go
$('input[type="text"]').filter(function()
{ return $( this ).val() != ""; }).addClass("used");
Last Working Demo
and jquery filter reference
I have the following structure:
<div id="campaignTags">
<div class="tags">Tag 1</div>
<div class="tags">Tag 2</div>
<div class="tags">Tag 3</div>
</div>
And I'm trying to match user input against the innerText of each children of #campaignTags
This is my latest attempt to match the nodes with user input jQuery code:
var value = "Tag 1";
$('#campaignTags').children().each(function(){
var $this = $(this);
if(value == $(this).context.innerText){
return;
}
The variable value is for demonstration purposes only.
A little bit more of context:
Each div.tags is added dynamically to div#campaignTags but I want to avoid duplicate values. In other words, if a user attempts to insert "Tag 1" once again, the function will exit.
Any help pointing to the right direction will be greatly appreciated!
EDIT
Here's a fiddle that I just created:
http://jsfiddle.net/TBzKf/2/
The lines related to this question are 153 - 155
I tried all the solutions, but the tag is still inserted, I guess it is because the return statement is just returning the latest function and the wrapper function.
Is there any way to work around this?
How about this:
var $taggedChild = $('#campaignTags').children().filter(function() {
return $(this).text() === value;
});
Here's a little demo, illustrating this approach in action:
But perhaps I'd use here an alternative approach, storing the tags within JS itself, and updating this hash when necessary. Something like this:
var $container = $('#campaignTags'),
$template = $('<div class="tags">'),
tagsUsed = {};
$.each($container.children(), function(_, el) {
tagsUsed[el.innerText || el.textContent] = true;
});
$('#tag').keyup(function(e) {
if (e.which === 13) {
var tag = $.trim(this.value);
if (! tagsUsed[tag]) {
$template.clone().text(tag).appendTo($container);
tagsUsed[tag] = true;
}
}
});
I used $.trim here for preprocessing the value, to prevent adding such tags as 'Tag 3 ', ' Tag 3' etc. With direct comparison ( === ) they would pass.
Demo.
I'd suggest:
$('#addTag').keyup(function (e) {
if (e.which === 13) {
var v = this.value,
exists = $('#campaignTags').children().filter(function () {
return $(this).text() === v;
}).length;
if (!exists) {
$('<div />', {
'class': 'tags',
'text': v
}).appendTo('#campaignTags');
}
}
});
JS Fiddle demo.
This is based on a number of assumptions, obviously:
You want to add unique new tags,
You want the user to enter the new tag in an input, and add on pressing enter
References:
appendTo().
filter().
keyup().
var value = "Tag 1";
$('#campaignTags').find('div.tags').each(function(){
if(value == $(this).text()){
alert('Please type something else');
}
});
you can user either .innerHTML or .text()
if(value === this.innerHTML){ // Pure JS
return;
}
OR
if(value === $this.text()){ // jQuery
return;
}
Not sure if it was a typo, but you were missing a close } and ). Use the jquery .text() method instead of innerText perhaps?
var value = "Tag 1";
$('#campaignTags').find(".tags").each(function(){
var content = $(this).text();
if(value === content){
return;
}
})
Here you go try this: Demo http://jsfiddle.net/3haLP/
Since most of the post above comes out with something here is another take on the solution :)
Also from my old answer: jquery - get text for element without children text
Hope it fits the need ':)' and add that justext function in your main customised Jquery lib
Code
jQuery.fn.justtext = function () {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
$(document).ready(function () {
var value = "Tag 1";
$('#campaignTags').children().each(function () {
var $this = $(this);
if (value == $(this).justtext()) {
alert('Yep yo, return');)
return;
}
});
//
});
I have a few select menus that include blank options. When both are blank (usually on the first page load), I would like to show some hidden div.
This is what I have:
$('.variant_options select').each(function() {
if ($(this).attr('value') === '') {
// some code here to show hidden div
console.log("No options chosen");
}
});
This doesn't seem to work.
Edit 1
For what it's worth, I have tried something like this:
if (!$(this).attr('value'))
And that has seemed to work, but it breaks functionality elsewhere.
<select> elements don't have a value attribute, so you need to use .val() on the element to find out if the currently selected option is empty.
if ($(this).val() === '') {
// value of select box is empty
}
this.value === '' should also work
To check whether no options are selected:
if (this.selectedIndex == 0) {
// no option is selected
}
You can do so by using the following:
if($(this).val() === '') {
// value is empty
}
I believe also the following too:
if(!$(this).prop('value')) {
// It's empty
}
You can simply do this:
$('.variant_options select').each(function () {
if ($.trim($(this).val()) === '') {
// some code here...
}
});
jQuery can check for value by using $(this).val()
So you would do if ($(this).val === '')`
If you wanted to check for some other attribute, like href or src, you could do
if ($(this).attr('href') === ''
In case if you have spaces, use this trick:
if ($.trim($(this).val()) === '') { ...
I have a script that only works in jquery 1.7.2. I'm also getting a lot of conflicts with this script.
Is there an alternative to this approach? I'm trying to count the number of input's and textarea's that have data typed inside them. I just need a number.
Here is my current script:
$('#form_register').on('keyup', function() {
var number = $('#form_register').find('input, textarea')
// filter out every empty input/textarea
.filter(function() {
return $(this).val() != '';
}).length;
$('.inputCount').val('There are ' + number + ' empty input fields');
console.log('test');
});
I'd use the change handler too, to prevent someone paste the text inside a field.
EDIT :
To count upwards as you asked in your comment:
jsBin demo
$('#form_register').on('keyup change', function() {
var number = 0;
$(this).find('input, textarea').each(function(){
if( this.value !== ''){
$('.input_count').val(number++);
}
});
});
To redo to count downwards (DEMO) just use === and exclude the print from the each function:
if( this.value === ''){
number++;
}
$('.input_count').val(number);
If you have more issues, try to wrap the code into:
(function($){ // remap '$' to jQuery
// CODE HERE
})(jQuery);
I have a question actually I need one if/else for hide or show one div, I had wrote the following function but it didn’t work:
jQuery(document).ready(function(){ /*show div OtraUniversidad when option:selected = 165*/
var optionValue = $("#Universidad option:selected").val();
$("#OtraUniversidad").hide();
if(optionValue == 165){
$("#OtraUniversidad").show();
}
});
Actually works: $("#OtraUniversidad").hide();
I don't know what's wrong; I'm new in JavaScript and jQuery
Some help is always welcome.
I think this should work:
jQuery(document).ready(function() {
$('#Universidad').change(function() {
var optionValue = $("#Universidad").val();
if(optionValue == 165) {
$("#OtraUniversidad").show();
} else {
$("#OtraUniversidad").hide();
}
}).change();
});
Demo: http://jsfiddle.net/gGX2E/1/
optionValue == 165
This comparison is wrong, you must use this:
if(optionValue == "165")