how to get text of option knowing just its value - javascript

Let's say i have such code:
<select id="select" multiple="multiple">
<option value="A1">abc</option>
<option value="A2">cde</option>
<option value="A3">efg</option>
</select>
And an array:
var selected = ["A1", "A3"];
I want to iterate through selected array to get second array containing text of option markups with appropriate values. Values are unique:
var texts = [ "abc", "efg" ];
How to achieve that in jquery?

Can use :selected selector to find selected options and map() to create array
var texts = $('#select option:selected').map(function(){
return $(this).text()
}).get();
Or use attribute selector while iterating the selected array
var $opts = $('#select option')
var texts = selected.map(function(val){
return $opts.filter('[value="' + val + '"]').text()
});

You can use the attribute "value" selector for option:
var selected = ["A1", "A3"];
var text= [];
for(var i=0; i < selected.length; i++) {
text.push($('#select option[value=' + selected[i] + ']').text());
}

Use attribute equals selector to get elements using value attribute and generate the array using map() method. Where use Array#join method to generate a single selector to avoid iteration over the array.
var selected = ["A1", "A3"];
var res = $('[value="' + selected.join('"],[value="') + '"]').map(function() {
return this.text; // or $(this).text();
}).get();
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select" multiple="multiple">
<option value="A1">abc</option>
<option value="A2">cde</option>
<option value="A3">efg</option>
</select>
If you are trying to get selected elements text then use :selected pseudo-class selector.
var res = $('select option:selected').map(function() {
return this.text; // or $(this).text();
}).get();
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select" multiple="multiple">
<option value="A1" selected>abc</option>
<option value="A2">cde</option>
<option value="A3" selected>efg</option>
</select>

Related

store selection from multiselect element inside string

I have multiple select box like
<select id="myMultiSelect" class="multiselect form-control" name="Status" multiple="multiple">
<option value="AA">AA option</option>
<option value="BB">BB option</option>
...
<option value="FF">FF option</option>
</select>
How can I usig jquery store selected values inside string separated with comma like
var string = "AA,BB,CC";
You could use the .map() method to get the array of values and then join them:
Example Here
var selectValueString = $('#myMultiSelect > option').map(function () {
return this.value;
}).get().join(',');
console.log(selectValueString); // "AA,BB,FF"
Alternatively, without jQuery:
Example Here
var options = document.querySelectorAll('#myMultiSelect > option');
var selectValueString = Array.prototype.map.call(options, function(el){
return el.value;
}).join(',');
console.log(selectValueString); // "AA,BB,FF"
Simply assign it to variable. The .val() returns an array of values:
var myval = $('select#myMultiSelect').val();
Here is a sample fiddle to show it working: http://jsfiddle.net/MarkSchultheiss/6jyrfcfo/

Find duplicate values in pairs - select dropdown

I have pair of text boxes. I need to find duplicate pair values in my select dropdown.
JSFIDDLE example
txt12 txt12
txt2 txt1
txt3 txt3
txt4 txt5
txt12 txt12
In my example, txt12 select pair is duplicated. I could possibly find each duplicate values by considering each select dropdowns.
var selects = document.getElementsByTagName('select');
var values = [];
for(i=0;i<selects.length;i++) {
var select = selects[i];
if(values.indexOf(select.value)>-1) {
alert('duplicate - '+select.value); break;
}
else
values.push(select.value);
}
How is it possible to find duplicate pair of select dropdown values
You can use something like
function chkVal() {
var selects = document.getElementsByTagName('select');
var values = [];
for(i=0;i<selects.length;i++) {
var select = selects[i];
if(values.indexOf(select.value)>-1) {
alert('duplicate - '+select.value);
}
else
values.push(select.value);
}
}
You have to just remove the break in the if block as it is moving out of the for loop in the first loop when it find text12.
Refer to the fiddle : "http://jsfiddle.net/sL6ofchd/9/"
With jQuery, try something like this:
$('.check-value').on('click', function() {
var duplicates = $('select+br').prev().filter(function() {
return $(this).val() == $(this).prev().val();
});
console.log( duplicates.length );
});
$('.check-value').on('click', function() {
var duplicates = $('select+br').prev().filter(function() {
return $(this).val() == $(this).prev().val();
});
console.log( duplicates.length + ' duplicates' );
duplicates.each(function(i) {
console.log( i, this, $(this).prev()[0] );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="txt12">txt12</option>
</select> <select>
<option value="txt12">txt12</option>
</select><br><br>
<select>
<option value="txt2">txt2</option>
</select> <select>
<option value="txt1">txt1</option>
</select><br><br>
<select>
<option value="txt3">txt3</option>
</select> <select>
<option value="txt3">txt3</option>
</select><br><br>
<select>
<option value="txt12">txt12</option>
</select> <select>
<option value="txt12">txt12</option>
</select><br><br>
<input type="button" value="save" class="check-value">

Get Option HTML by it's value in Jquery

How we can get the option HTML in jquery by it's value in jQuery.
HTML
<select multiple="" style="width: 147px;" id="list" name="list" class="list_class">
<option value="21">A</option>
<option value="22">B</option>
<option value="23">C</option>
<option value="24">D</option>
<option value="2">E</option>
</select>
Array
var id_arry = ['21','24','2'];
I have this array that have some values related to values in the drop down. Now i want to get all the options that matches the value in dropdown HTML
like
<option value="21">A</option><option value="24">D</option> <option value="2">E</option>
This is the final out put i want from the drop-down.Kindly help me in this
I want to add those options html in this dropdown:
<select multiple="" style="width: 147px;" id="list" name="list1" class="list_class">
</select>
Maybe something like this:
var id_arry = ['21','24','2'];
var optionMatches = $('#list option').filter(function() {
return $.inArray($(this).val(), id_arry);
});
Breaking it down:
$('#list option') - returns all of the options in the select list with ID "list"
.filter(callback) - a simple filter function -- the callback decides whether the option makes it into the final list
$.inArray($(this).val(), id_arry) - checks if the current option value is in the array id_arry
After studying your example, it looks like you'll first want to obtain the selected options from your multi-select drop-down list to build your id_arry, which is very easy:
var id_arry = $('#list').val();
Once you have these and the optionMatches array of elements, you can clone them over to a new drop-down:
optionMatches.clone().appendTo('#otherSelect');
One solution is using join and split:
var id_arry = ['21', '24', '2'];
$("#list").val(id_arry.join(',').split(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" style="width: 147px;" id="list" name="list" class="list_class">
<option value="21">A</option>
<option value="22">B</option>
<option value="23">C</option>
<option value="24">D</option>
<option value="2">E</option>
</select>
You can use jQuery's attribute equals selector to target elements with a specific attribute value:
$( "option[value='21']" )
Using this selector and a simple loop, you can extract all the elements you need:
var elements = [];
var id_array = ['21','24','2'];
for ( index in id_array ){
var elem = $( "option[value='" + id_array[ index ] + "']" );
if ( elem ) {
elements.push( elem );
}
}
Your elements array now contains all option elements who's values appear in id_array.
var id_arr = ['21','24','2'];
var entireHTML = "";
var options = $('select').find('option');
var tempDiv = $('div');
//id_arr = $('select').val(); //Uncomment this line to get value from the select element.
$.each(id_arr, function(index, value){
entireHTML = "";
$(options).each(function(){
if( $(this).val() === value)
{
$(this).clone().appendTo(tempDiv);
}
});
});
entireHTML = $(tempDiv).html();
Since you need the HTML content of the 'option' elements, they're cloned and wrapped in a temporary div so that the inner HTML of that temporary div is copied and appended to our final HTML string.
Check it out for yourself : JSFiddle Test Link

Javascript/jQuery: Set Values (Selection) in a multiple Select

I have a multiple select:
<select name='strings' id="strings" multiple style="width:100px;">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On">On</option>
</select>
I load data from my database. Then I have a string like this:
var values="Test,Prof,Off";
How can I set this Values in the multiple select? Already tried change the string in an array and put it as value in the multiple, but doesnt work...!
Can someone help me with this? THANKS!!!
Iterate through the loop using the value in a dynamic selector that utilizes the attribute selector.
var values="Test,Prof,Off";
$.each(values.split(","), function(i,e){
$("#strings option[value='" + e + "']").prop("selected", true);
});
Working Example http://jsfiddle.net/McddQ/1/
in jQuery:
$("#strings").val(["Test", "Prof", "Off"]);
or in pure JavaScript:
var element = document.getElementById('strings');
var values = ["Test", "Prof", "Off"];
for (var i = 0; i < element.options.length; i++) {
element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}
jQuery does significant abstraction here.
Just provide the jQuery val function with an array of values:
var values = "Test,Prof,Off";
$('#strings').val(values.split(','));
And to get the selected values in the same format:
values = $('#strings').val();
Pure JavaScript ES6 solution
Catch every option with a querySelectorAll function and split the values string.
Use Array#forEach to iterate over every element from the values array.
Use Array#find to find the option matching given value.
Set it's selected attribute to true.
Note: Array#from transforms an array-like object into an array and then you are able to use Array.prototype functions on it, like find or map.
var values = "Test,Prof,Off",
options = Array.from(document.querySelectorAll('#strings option'));
values.split(',').forEach(function(v) {
options.find(c => c.value == v).selected = true;
});
<select name='strings' id="strings" multiple style="width:100px;">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On">On</option>
</select>
var groups = ["Test", "Prof","Off"];
$('#fruits option').filter(function() {
return groups.indexOf($(this).text()) > -1; //Options text exists in array
}).prop('selected', true); //Set selected
Basically do a values.split(',') and then loop through the resulting array and set the Select.
Pure JavaScript ES5 solution
For some reason you don't use jQuery nor ES6? This might help you:
var values = "Test,Prof,Off";
var splitValues = values.split(',');
var multi = document.getElementById('strings');
multi.value = null; // Reset pre-selected options (just in case)
var multiLen = multi.options.length;
for (var i = 0; i < multiLen; i++) {
if (splitValues.indexOf(multi.options[i].value) >= 0) {
multi.options[i].selected = true;
}
}
<select name='strings' id="strings" multiple style="width:100px;">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On" selected>On</option>
</select>
Use this:
$('#demo').multiselect('select', value);
For multiple values just use a loop
For more properties this page is very good
this is error in some answers for replace |
var mystring = "this|is|a|test";
mystring = mystring.replace(/|/g, "");
alert(mystring);
this correction is correct but the | In the end it should look like this \|
var mystring = "this|is|a|test";
mystring = mystring.replace(/\|/g, "");
alert(mystring);

Counting no. of dropdownlists inside a div

<div id="myDiv">
<select id="ddl1" name="31">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3" selected="selected">Three</option>
</select>
<select id="ddl2" name=32>
<option value="1">A</option>
<option value="2" selected="selected">B</option>
<option value="3">C</option>
</select>
</div>
Thats my div. The number of dropdowns inside this div vary. What I want is this in a string:-
31,3||32,2
The above is name attribute value of dropdowns, 2nd number after comma is the "value" of the selected option and values of both dropdownlists are separated by pipe symbol. The dropdowns can be 3 and 4 in number too. How can I acheive this in jquery?
A little something like this:
var selects = [];
$("#myDiv select").each(function() {
selects.push(this.name + "," + $(this).val());
});
var output = selects.join("||");
Where the .each() method is used to iterate through all the select elements and push their name and current value into the selects array, then the array .join() method is used to turn the array into a string using "||" as the separator.
try this snippet:
var output = [];
$('#myDiv select').each(function() {
output.push([this.name, $(this).val()].join(','));
});
console.log(output.join('||'));
Try the following:
var values = [];
$('#myDiv select').each(function() {
values.push($(this).attr('name') + ',' + $(this).val());
});
var result = values.join('||');
var val = "";
$("select").each(function(){
val += $(this).attr("name") + "," + $("option:selected",this).val()+ "||";
})
if(val != "")
val = val.substring(0, val.length - 2);
console.log(val);

Categories

Resources