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.
Related
I'm new here, can someone please help me...
i have 2 div's #main and #side.
In my #main div i have few check boxes ,
on checked event, i apend my check box label into #side div and add/remove some classes and it's working perfectly
but when i unchecked my input, it's not working not add/remove classes or apend to #main div
here is my code
$('input[type="checkbox"]').change(function() {
if (this.checked) {
$(this).next('label').removeClass("icon");
$(this).next('label').addClass("icon-active");
$(this).next('label').detach().appendTo('#side');
}
else
{ // This condition not working //
$(this).next('label').addClass("icon");
$(this).next('label').removeClass("icon-active");
$(this).next('label').appendTo('#main');
}
});
Thanks in Advance
Here is a full code.
http://jsfiddle.net/o8n1b8z1/4/
First, since you're using jQuery, I suggest you do not use this.checked, but $(this).is(':checked').
However, the reason your code is not working in reverse is because you're moving the .next('label') in DOM on checking the checkbox. So, on unchecking, .next('label') won't exactly return the label, as it is has been moved.
This is how I'd write your function:
$('input[type="checkbox"]').on('change', function(){
var label = $('label[for="'+$(this).attr('id')+'"]'),
checked = $(this).is(':checked');
label.toggleClass("icon icon-active").appendTo(checked?'#side':'#main')
})
Now, another problem with your script is that, on return, it appends the labels to the end of the div, instead of after the checkboxes. To fix that, here's what you should use:
$('input[type="checkbox"]').on('change', function() {
var label = $('label[for="' + $(this).attr('id') + '"]'),
checked = $(this).is(':checked');
label.toggleClass("icon icon-active")[
checked ? 'appendTo' : 'insertAfter'
]($(checked ? '#side' : this));
})
Updated your fiddle
Did some changes to your else statement and it works. The issue is the Label gets shifted out and the else part no longer identifies the Labels anymore.
Here is the fiddle http://jsfiddle.net/o8n1b8z1/5/
else
{ // This condition working //
var id=$(this).attr('id');
var label = $('label[for="' + id + '"]');
label.addClass("icon");
label.removeClass("icon-active");
$( "#"+id ).after(label);
}
JSFIDDLE LINK
var $select = $('select');
$select.on('change', function () {
var value = $(this).val();
var modifier = value.split('_')[0];
var target = modifier + '_target';
console.log(target);
$('div').filter(target).addClass('active');
});
If you open console and select any option from the select, you'll see that the text that is thrown to the console is legit (as I want to select modifier1_target depending on the selected option).
However, I can not make a jQuery selector out of this, so as the div is selected and applied an active class.
I tried $(el).attr('class', target) but it didn't work surely.
I am running out of ideas where am I wrong here?
You have to tell jQuery that it's a class you're looking for ('.' + target):
$('div').filter('.' + target).addClass('active');
Updated Fiddle
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
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.
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.