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/
Related
I would like to iterate through the selected values from a multiple select box and check them against a string, returning false as soon as a match is not found. First I tried:
var exampleString = "example";
var mySelections = $("#mySelect option:selected");
for (selection in mySelections) {
if (exampleString.indexOf(mySelections[selection].text()) === -1) {
return false;
};
};
This code gives me an error, however: "text is not a function". I am given to understand that this is because using the index gets the option object itself, not wrapped in jQuery, and it is jQuery that provides the text() method.
I tried an alternative version using the each function:
var result = $("#mySelect option:selected").each(function () {
if (exampleString.indexOf($( this ).text()) === -1) {
return false;
}
});
However, I do not understand the result I'm getting. I naively assumed that my variable result would be set to false or true, but it seems to just return the objects being iterated over. Is there any way to access the results of those string comparisons short of creating a global variable that gets set to true or false inside the function?
Edited to add: upon request, here's the relevant html:
<select multiple="" class="filterSelect" id="mySelect" style="display: none;">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
This is what I would do (I'm not a jQuery user any more):
let testStr = "dd";
document.getElementById('sel').addEventListener('change', (e) => {
const values = []
for (let i=0; i<e.target.selectedOptions.length; i++) {
values.push(e.target.selectedOptions[i].value);
}
console.log(!values.includes(testStr));
return !values.includes(testStr);
})
<select id="sel" multiple>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
<option value="ee">ee</option>
</select>
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>
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
I am tring to set selected values in a dropdown from a comma seperated string,here i want to set text1,text2,text3,text4 as selected in the dropdown.
Thanks..
var string='text1,text2,text3,text4';
<select id="dropdown">
<option value="0">text1</option>
<option value="1">text2</option>
<option value="2">text3</option>
<option value="3">text4</option>
<option value="4">text5</option>
<option value="5">text6</option>
<option value="6">text7</option>
</select>
Here we go, you can make selected values like following:
var string='text1,text2,text3,text4';
var opts = string.split(",");
function selectOptions() {
var obj = $('#dropdown');
for (var i in opts) {
obj.find('option[value=' + i + ']').prop('selected', true);
}
}
selectOptions();
Fiddle Demo
Hope this will work!
I think you can use string.split(',')
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);