Loop through string of dropdown options and select - javascript

I want to select an option in a string, where the string will be the contents of a dropdown, but I dont know how to loop through the string as an object please.
In the example I would like "Saab" to be selected and the string alerted.
var x = '<select><option>Volvo</option> <option>Saab</option> <option>Mercedes</option> <option>Audi</option> </select>';
$.each($(x), function(index, value) {
if ($(this).val() == "Saab"){
$(this).attr("selected","selected")
}
});
alert(x);

Start by turning the string into a jQuery object:
var x = $(x);
Then just select the correct option and set it as selected:
$('option:contains("Saab")', x).prop('selected', true);
FIDDLE

$.each($('option', x), function(index, value) {
if ($(this).text() == "Saab"){
$(this).attr("selected","selected")
}
});

Is this in an HTML page? If yes, why not just use something like $("option").each()?

Don't need to loop, jquery can do that for ya
$(x).children('option:contains("Saab")').attr('selected','selected');
ref: http://api.jquery.com/category/selectors/

Related

Cannot set multiple value of bootstrap select from array

So I have this string: 93, 94 which are the references of the values of a select.
I'm trying to set these values using:
let values = "93, 94";
$('#property-categories').selectpicker('val', values);
but not working, none of the value is selected in the select control.
If I write: $('#property-categories').selectpicker('val', [93,94]);
works, any idea?
To turn a comma delimited string in to an array, which is the type required here, use split().
let values = "93, 94";
$('#property-categories').selectpicker('val', values.split(', '));
Please check this one for simple select control
var values="93,94";
$.each(values.split(","), function(i,e){
$("#strings option[value='" + e + "']").prop("selected", true);
});
For selectpicker you need to set below code
$('.selectpicker').selectpicker();
$('.selectpicker').selectpicker('val', ['93','94']);
Check here working demo - > Click here

JQuery get the value of the newly selected/unselected element of a select [duplicate]

I have a HTML select list, which can have multiple selects:
<select id="mySelect" name="myList" multiple="multiple" size="3">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option> `
<option value="4">Fourth</option>
...
</select>
I want to get an option's text everytime i choose it. I use jQuery to do this:
$('#mySelect').change(function() {
alert($('#mySelect option:selected').text());
});
Looks simple enough, however if select list has already some selected options - it will return their text too. As example, if i had already selected the "Second" option, after choosing "Fourth" one, alert would bring me this - "SecondFourth". So is there any short, simple way with jQuery to get only the "current" selected option's text or do i have to play with strings and filter new text?
You could do something like this, keeping the old value array and checking which new one isn't in there, like this:
var val;
$('#mySelect').change(function() {
var newVal = $(this).val();
for(var i=0; i<newVal.length; i++) {
if($.inArray(newVal[i], val) == -1)
alert($(this).find('option[value="' + newVal[i] + '"]').text());
}
val = newVal;
}); ​
Give it a try here, When you call .val() on a <select multiple> it returns an array of the values of its selected <option> elements. We're simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1 if not found) then that's the new value. After that we're just using an attribute-equals selector to grab the element and get its .text().
If the value="" may contains quotes or other special characters that would interfere with the selector, use .filter() instead, like this:
$(this).children().filter(function() {
return this.value == newVal[i];
}).text());
Set a onClick on the option instead of the select:
$('#mySelect option').click(function() {
if ($(this).attr('selected')) {
alert($(this).val());
}
});
var val = ''
$('#mySelect').change(function() {
newVal = $('#mySelect option:selected').text();
val += newVal;
alert(val); # you need this.
val = newVal;
});
or let's play some more
val = '';
$('#id_timezone')
.focus(
function(){
val = $('#id_timezone option:selected').text();
})
.change(
function(){
alert(val+$('#id_timezone option:selected').text())
});
Cheers.

How do I select a value from a dropdownlist case insensitive?

I am trying to find "CAT" in a dropdown where the values of the dropdown are ["Cat","Rat","Mat"] as a result am not a able find by text and i dont have ID for "CAT" to find by id. Any suggestion?
EDIT: lowercase() will change "CAT" to cat right?? But my dropdown has "Cat"
Try to compare values lowercase :
if(myvalue.toLowerCase() === ddl[i].toLowerCase()) {
//...
}
Little late, and is basically what Mysteryos answer is following up with jsFiddle to back it.
This function will return the option back:
function Find(searchContent)
{
var options = $('#dropDown option');
var foundOption;
$.each(options, function (key, value)
{
value = $(value);
if(value.html().toLowerCase() == searchContent.toLowerCase())
{
foundOption = value;
}
});
return foundOption;
}
See a working example at: http://jsfiddle.net/7fWxZ/
Check this out:
HTML Code:
<select id="ats">
<option>Cat</option>
<option>Rat</option>
<option>Mat</option>
</select>
jQuery Code:
function findmyat(comparetext){
$('#ats option').each(function(){
if ($(this).val().toLowerCase()==comparetext.toLowerCase()){
//found the option i was looking for, do what i want
alert($(this).val()+' has been found');
}
}
}

Check if an select option exists based on text in jQuery 1.7

So I have the following piece of HTML:
<select id="sel">
<option value="0">Option1</option>
<option value="1">Option2</option>
<option value="2">Option3</option>
<option value="3">Option4</option>
</select>
How do I check to see if #sel has an option based on the text value? ("Option1")
Try the following:
var opt = 'Option1';
if ($('#sel option:contains('+ opt +')').length) {
alert('This option exists')
}
Demo
edit: The above snippet uses the jQuery contains selector which filters elements that their textContent contains the specified value. For an exact match you can use the code snippet suggested in christian-mann's answer.
How to do this with Javascript (not jquery) – Jerry
var optionExists = [].some.call(document.getElementById('sel').options, function(option) {
return option.textContent === 'value';
});
The jQuery filter function accepts a function as its argument:
$('#sel option').filter(function() {
return $(this).text() === "Option1";
});
var length = $('#sel option').filter(function() {
return $(this).text() === "Option1";
}).length;
if(length == 0)
console.log('This option text doesn't exist.');
else
console.log('This option text exists ' + length + ' times.');
If length is 0, it doesn't exist. I typically don't like using contains, because it's not an exact match.
var hasOption1=$("option:contains('Option1')", "#sel").length==1; //true or false

Jquery Javascript HTML selects

So I've got a standard select dropdown. One of the options in the select(the last one) I've got as a text string- var abc.
<select id="exampleselect">
<option>123</option>
<option>xyz</option>
<option>ABC</option>
</select>
var abc = "ABC";
What I'm trying to do is search through the select, find a match against var abc then change the match of var abc to being the selected option.
What I've tried:
//gets all the options from the select
var selectoptions = $('#exampleselect').find('option').text();
//if there is a match of var abc to any of the options in the select
if (selectoptions == abc)
{
//work out how to get the index/eq of the matched element
//put matched element as selected value
$('#exampleselect').val(matchedelementindex);
}
Live example.
As you don't use the value attribute, you can use this code:
var myVar = 'xyz';
$('#exampleselect option').each(function(e) {
var $this = $(this);
if ($this.text() === myVar) {
$this.prop('selected', true);
return false; // stops the iteration
}
});
You could also do it in one line by using the :contains() selector. But this would may not work if you have an option with text "ABC" and another with "ABCD":
$('#exampleselect option:contains('+myVar+')').prop('selected', true);
Although, I would recommend that you add a value attribute to your option elements:
<select id="exampleselect">
<option value="123">123</option>
<option value="xyz">xyz</option>
<option value="ABC">ABC</option>
</select>
this way you can do:
$('#exampleselect').val(myVar);
Try this:
var abc = "ABC";
$("#exampleselect option").each(function() {
if ($(this).text() == abc) {
$(this).attr("selected", true);
return false; // exit each loop
}
})
Or this, although this is slightly less readable:
var abc = "ABC";
$("#exampleselect option").each(function() {
$(this).attr("selected", $(this).text() == abc);
})
This fiddle may help you .
You can achieve this by CSS Selectors which are supported by jQuery
var searched="abc";
$('select option['+searched+']').attr("selected","selected");
http://jsfiddle.net/7EzqU/
// iterate all select options using jquery .each method
$('#exampleselect option').each(function () {
// check if current option text is equal to 'ABC'
if ($(this).text() == 'ABC') {
// get index of option
var index = $('#exampleselect').index($(this))
// set selectedIndex property to change to this option
$('#exampleselect').prop('selectedIndex', index);
}
})
this should do the trick:
http://jsfiddle.net/xXEVw/

Categories