Get Option HTML by it's value in Jquery - javascript

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

Related

how to get text of option knowing just its value

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>

Filtering elements by tagName

Example Fiddle.
I need to add conditions so my code support inputs (1 button need to generate the whole Json).
I've tried filtering with :
elements.tagName
But it gives me an undefined, I suppose it is because
var elements = document.getElementsByClassName('selectVal');
Returns a nodelist. How can I filter or adapt my code so the same function supports inputs?
I need to storage the selected item in list and the strings in the inputs just with one button.
elements is the array of elements you get from getElementsByClassName. You should check tagName on elements[index] inside the loop instead.
Add the input (replace the selectVal with a better class to all form objects though):
<input id="textbox" class="selectVal" value="text value">
You can change the inner part of the loop to look for the tag
...
var strSel = '';
if (element.tagName == 'SELECT')
strSel = element.options[element.selectedIndex].text;
else if (element.tagName == 'INPUT')
strSel = element.value;
...
As #adeneo mentioned in the above comment you could use querySelectorAll with multiple selector separated by comma , To get the .selectVal and input values :
document.querySelectorAll('.selectVal, input');
Hope this helps.
function getSelectedItems(){
var elements = document.querySelectorAll('.selectVal, input')
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.tagName==='SELECT')
console.log(element.options[element.selectedIndex].text);
else
console.log(element.value);
}
}
<select id="Sobre" class="selectVal">
<option value="1" selected>fasfaf</option>
<option value="2">afsaf</option>
<option value="3">Fraasfsafe</option>
</select>
<select id="asdafa" class="selectVal">
<option value="1">fassad</option>
<option value="2" selected>fasfsa</option>
<option value="3">asdasf</option>
</select>
<select id="asdf" class="selectVal">
<option value="1">fdsa</option>
<option value="2">asdfg</option>
<option value="3" selected>dsaf</option>
</select>
<input name="test" value='input value' />
<button onClick="getSelectedItems()">AƱadir</button>
I don't know an elegant way of filtering the list other than using something like jQuery. You might be stuck with an old school solution:
var elements = document.getElementsByClassName('selectVal');
for (var i = 0; i < elements.length; ++i) {
var element = elements[i];
if (i.tagName == 'DIV') {
// whatever
}
}
That said, this will find you all the <div>s of class selectVal:
var elements = document.querySelectorAll('div.selectVal');
That might be enough depending on your use case.

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/

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);

Javascript to populate an option box with an array

Hi was wondering if you could help, i need to use JavaScript to populate the clothes option box with appropriate options when the user specifies what type of gender they are. This is the code I have so far,
<script type="text/javascript">
var subListArray = [];
subListArray[0] = 'Select a type first';
subListArray[1] = ['skirt', 'dress', 'tights'];
subListArray[2] = ['jeans', 'hat'];
</script>
Person
Gender Type: <select name="genderType" id="genderType" >
<option value="">Gender Type?</option>
<option value="girl">Female</option>
<option value="boy">Male</option>
</select> </br>
Clothes <select name="clothType">
<option value="">Choose a Type</option>
</select>
Use objects instead of arrays so that you can map the subList to the selected gender. You don't have to do this, but it simplifies things a bit. Add a "change" listener to the gender selector that creates the option elements for the new select box:
var subListArray = {
'default': ['Select a type first'],
'girl': ['skirt', 'dress', 'tights'],
'boy': ['jeans', 'hat'],
};
document.getElementById('genderType').addEventListener('change', function () {
var sel = document.getElementById('clothType'),
value = this.value ? this.value : 'default';
sel.innerHTML = '';
subListArray[value].forEach(function (item) {
sel.appendChild(new Option(item));
});
});
http://jsfiddle.net/VdXk6/
See this page which explains adding elements to the DOM:
http://www.javascriptkit.com/javatutors/dom2.shtml
You need to use createElement, setAttribute and appendChild. E.g:
html:
<select id="mySelect">...</select>
<select id="mySubSelect"></select>
javascript:
var myNewOption = document.createElement( 'option' );
myNewOption.setAttribute( 'value', 'myOptionValue' );
document.getElementById( 'mySubSelect' ).appendChild( myNewOption );
This can go in a loop. Also you can detect when the selection changes like this:
javascript:
document.getElementById('mySelect').addEventListener('change',function(){
document.getElementById('mySelect').selectedIndex; // a number showing which element is selected
});
With jQuery it is a lot easier.

Categories

Resources