Select option with cheerio (jquery) by text - javascript

I'm trying to select an option from a select dropdown with the text() attribute of the HTML element with cheerio. So far what I'm doing is that I'm trying to set the attr as selected matching, the element with the specific text.
This is what I'm trying:
$('#ddl_city option[text="testing"]').attr('selected', 'selected');
I'm not getting any changes on the html when I do this. I print the html document on the console after doing this operation and I don't see that the option has changed to the one I'm selecting. Any idea why is not working or another workaround?

You can try this:
$('#ddl_city option').
filter(function () { return $(this).text() == 'testing'; }).
attr('selected', true);
Credits to Godsbest's answer in this post on the jQuery forum.

You can use the :contains filter to get the specific option element based on the text and set the value of the select element to it's value:
$('#s1').val($("#s1 option:contains('Val B')").val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="s1">
<option value="a">Val A</option>
<option value="b">Val B</option>
</select>

Related

How to dynamically append selected option to a div and update if selected option is changed?

I have my HTML: a <select>, and a <div>:
<select>
<option>Please select one</option>
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
<div></div>
When I select an option, I want to append the being selected option value to the <div> element.
This in my js code:
$('select').on('change', function (e){
$('div').append("//not sure how to write code here");
});
What should I add in the append(), so that when a user select an option, it will shows up on my div, if the user change to another option, it will update the content?
For example, if I select Volvo, "Volvo" text will show in my div, if I change to Saab, "Saab" text will show up in my div to replace "Volvo"
$.append adds new html element inside the target element.
Use instead $.text. It will replace the div content to the new value. Also use $.val to get the current selected value from the select tag. Note that this refers to the select tag
Try this:
$('select').on('change', function (e){
$('div').text($(this).val());
});
See demo:
$('select').on('change', function(e) {
$('div').text($(this).val());
});
div {
border: 1px dashed #999;
padding: 15px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option>Please select one</option>
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
<div>Anything selected yet</div>
Sorry, I know this is an old post, but while the initial answer helped, it was not the solution. I figured out a modification which was however, as follows:
$('select').on('change', function (e){
var lang = $(this).val();
$('.someClass').append(lang);
I am posting it incase it helps someone else. This will append the selected text to whatever you need it attached to. In my case, it was to attach it to an anchor.
Use .text() instead of .append(). Like below
$('select').on('change', function(e) {
$('div').text($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option>Please select one</option>
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
<div></div>

get the text value in the dropdown with class

how to get the selected text of the option.
<select class="float-left groupNames" name="Group">
<option value="preview[object Object]0">test</option>
<option value="preview[object Object]1">test1</option>
<option value="preview[object Object]2">test2</option>
</select>
I tried $(".groupNames option:selected").text();
but its not the right value. so I am getting testtest2 if I am selecting the third option.
$(".groupNames").val() is all you need.
jsFiddle example
However if you have multiple .groupNames elements, you'll need to be more specific with the selector.
$(".groupNames option:selected").text(); as you probably saw, will get the selected option's text, not the select's value.
hi please add an id to easily access the select here is an tested fiddle http://jsfiddle.net/elviz/259m3qkb/1/
$("#newSkill").change(function(){
var kamote = document.getElementById("newSkill").options[document.getElementById('newSkill').selectedIndex].text;
alert(kamote);
});

jQuery Multiple Select

I have a multiple select HTML element.
<select multiple="multiple" id="mult_sel">
<option value="1">Dog</option>
<option value="2">Cat</option>
</select>
I'm using the following jQuery to capture when a single option in this multiple select is clicked on with the following:
$('#mult_sel').click(function(v){
console.log(v);
});
This event triggers as expected, however, I'm not sure how to get the value and text values of the single option that was clicked for a multiple select field.
Thanks!
try
$('#mult_sel option').click(function(){
alert('the value ' $(this).val()); //for get the value
alert('the text' $(this).text()); //for get the text
});
The .val() return the value of the option, and the .text() return the text of the option selected.
Jsfiddle
jsfiddle
$('#mult_sel').click(function(event){
// event.originalEvent.srcElement isn't fully supported
console.log(e.target);
});
there ya go :-) (do check if it's an [option] or a [select] element)
Try to use Select2 JQuery
you must download the code from GitHub and copy the dist directory to your project.
Include the following lines of code in the <head> section of your HTML.
<link href="../css/select2.min.css" rel="stylesheet" />
<script src="../js/select2.min.js"></script>
Initialize Select2 on the <select> element that you want to make it multiple select boxes.
<script type="text/javascript">
$('#select2-multiple').select2();
</script>
Example Code (Remember to declared with the multiple attribute)
<select class="select2-multiple" multiple="multiple">
<option value="WWL">Wong Wai Ling</option>
<option value="AE">Alessia Enzler</option>
<option value="ASL">A-Young SON LAuren</option>
</select>

jQuery UI MultiSelect are selecting all <select> in the page

I'm using the plugin jQuery UI MultiSelect http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/.
But I want just one <select> determinated by me to be multiple!
I alrealy have others <select> on my page (simple selects), like this:
<select name='simple_select' id='simples_select'>
<option value='1'>Option 1</option>
</select>
And, for the multiple <select>:
<select multiple="multiple" name='multiple_select' id='multiple_select'>
<option value='1'>Option 1</option>
</select>
When I change this function from "select" to something else, (like "div") all the divs stay "multiple". So, like this function (downloaded from the plugin site), all the <select> will be multiple... and I just one specific.
<script type="text/javascript">
$(function(){
$("select").multiselect();
});
</script>
Anyone have any idea how can I make it? Thanks for reading and I'm sorry about the terrifying english (I'm brazilian). ^^
Try using :not() to exclude a select you don't want calling it's ID inside :not()
$(function(){
$("select:not(#simples_select)").multiselect();
});
Demo
Or just use the ID selector for the one that you want, since it has ID:
$(function(){
$("#multiple_select").multiselect();
});
Demo
Unless you specifically want to apply something across a group of tags or objects it's much better practice to use IDs. To apply the code to the specific ID use the # symbol with the ID.
You can learn about CSS selectors with jQuery here: http://api.jquery.com/category/selectors/
<script type="text/javascript">
$(function(){
$("#multiple_select").multiselect();
});
</script>
If you want to select all <select> use $('select') and if you only want to select a specific <select> use $('#mySelect').
See this link for more info

jQuery get specific option tag text

All right, say I have this:
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
What would the selector look like if I wanted to get "Option B" when I have the value '2'?
Please note that this is not asking how to get the selected text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:
$("#list[value='2']").text();
But it is not working.
If you'd like to get the option with a value of 2, use
$("#list option[value='2']").text();
If you'd like to get whichever option is currently selected, use
$("#list option:selected").text();
It's looking for an element with id list which has a property value equal to 2.
What you want is the option child of the list:
$("#list option[value='2']").text()
This worked perfectly for me, I was looking for a way to send two different values with options generated by MySQL, and the following is generic and dynamic:
$(this).find("option:selected").text();
As mentioned in one of the comments. With this I was able to create a dynamic function that works with all my selection boxes that I want to get both values, the option value and the text.
Few days ago I noticed that when updating the jQuery from 1.6 to 1.9 of the site I used this code, this stop working... probably was a conflict with another piece of code... anyway, the solution was to remove option from the find() call:
$(this).find(":selected").text();
That was my solution... use it only if you have any problem after updating your jQuery.
Based on the original HTML posted by Paolo I came up with the following.
$("#list").change(function() {
alert($(this).find("option:selected").text()+' clicked!');
});
It has been tested to work on Internet Explorer and Firefox.
$("#list option:selected").each(function() {
alert($(this).text());
});
for multiple selected value in the #list element.
If there is only one select tag in on the page then you can specify select inside of id 'list'
jQuery("select option[value=2]").text();
To get selected text
jQuery("select option:selected").text();
Try the following:
$("#list option[value=2]").text();
The reason why your original snippet wasn't working is because your OPTION tags are children to your SELECT tag, which has the id list.
This is an old Question which has not been updated in some time the correct way to do this now would be to use
$("#action").on('change',function() {
alert($(this).find("option:selected").text()+' clicked!');
});
I hope this helps :-)
I wanted to get the selected label. This worked for me in jQuery 1.5.1.
$("#list :selected").text();
$(this).children(":selected").text()
You can get selected option text by using function .text();
you can call the function like this :
jQuery("select option:selected").text();
$("#list [value='2']").text();
leave a space after the id selector.
While "looping" through dynamically created select elements with a .each(function()...): $("option:selected").text(); and $(this + " option:selected").text() did not return the selected option text - instead it was null.
But Peter Mortensen's solution worked:
$(this).find("option:selected").text();
I do not know why the usual way does not succeed in a .each() (probably my own mistake), but thank you, Peter. I know that wasn't the original question, but am mentioning it "for newbies coming through Google."
I would have started with $('#list option:selected").each() except I needed to grab stuff from the select element as well.
Use:
function selected_state(){
jQuery("#list option").each(function(){
if(jQuery(this).val() == "2"){
jQuery(this).attr("selected","selected");
return false;
}else
jQuery(this).removeAttr("selected","selected"); // For toggle effect
});
}
jQuery(document).ready(function(){
selected_state();
});
I was looking for getting val by internal field name instead of ID and came from google to this post which help but did not find the solution I need, but I got the solution and here it is:
So this might help somebody looking for selected value with field internal name instead of using long id for SharePoint lists:
var e = $('select[title="IntenalFieldName"] option:selected').text();
A tip: you can use below code if your value is dynamic:
$("#list option[value='"+aDynamicValue+"']").text();
Or (better style)
$("#list option").filter(function() {
return this.value === aDynamicValue;
}).text();
As mentioned in jQuery get specific option tag text and placing dynamic variable to the value
I needed this answer as I was dealing with a dynamically cast object, and the other methods here did not seem to work:
element.options[element.selectedIndex].text
This of course uses the DOM object instead of parsing its HTML with nodeValue, childNodes, etc.
As an alternative solution, you can also use a context part of jQuery selector to find <option> element(s) with value="2" inside the dropdown list:
$("option[value='2']", "#list").text();
I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen $(this).find... earlier):
<script type="text/javascript">
$(document).ready(function(){
$("select[showChoices]").each(function(){
$(this).after("<span id='spn"+$(this).attr('id')+"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'> </span>");
doShowSelected($(this).attr('id'));//shows initial selections
}).change(function(){
doShowSelected($(this).attr('id'));//as user makes new selections
});
});
function doShowSelected(inId){
var aryVals=$("#"+inId).val();
var selText="";
for(var i=0; i<aryVals.length; i++){
var o="#"+inId+" option[value='"+aryVals[i]+"']";
selText+=$(o).text()+"<br>";
}
$("#spn"+inId).html(selText);
}
</script>
<select style="float:left;" multiple="true" id="mySelect" name="mySelect" showChoices="true">
<option selected="selected" value=1>opt 1</option>
<option selected="selected" value=2>opt 2</option>
<option value=3>opt 3</option>
<option value=4>opt 4</option>
</select>
You can get one of following ways
$("#list").find('option').filter('[value=2]').text()
$("#list").find('option[value=2]').text()
$("#list").children('option[value=2]').text()
$("#list option[value='2']").text()
$(function(){
console.log($("#list").find('option').filter('[value=2]').text());
console.log($("#list").find('option[value=2]').text());
console.log($("#list").children('option[value=2]').text());
console.log($("#list option[value='2']").text());
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
Try this:
jQuery("#list option[value='2']").text()
Try
[...list.options].find(o=> o.value=='2').text
let text = [...list.options].find(o=> o.value=='2').text;
console.log(text);
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>

Categories

Resources