Read select=multiple not working - javascript

I have a multi select option filed like the follows;
<select name="cars" id="carsId" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit" onclick="readValues()">
I need to read all the values into an array on readValues function. The array shopuld be like
A = [Volvo,Saab,opel,audi]
Please help me guys!!

You may try this also:
var readValues = function () {
var options = document.getElementById('carsId').options;
var list = [],
i = options.length;
while (i--) {
list.push(options[i].value);
}
console.log(list);//<-- ["audi", "opel", "saab", "volvo"]
};
In-case you need the text shown to user, use list.push(options[i].innerHTML);

http://www.w3schools.com/jsref/coll_select_options.asp
var x = document.getElementById("mySelect");
var options = [];
for (var i = 0; i < x.length; i++)
{
options.push(x.options[i].value);// or .text for the text
}
with jquery :
How to get all options of a select using jQuery?
var options = [];
$("#id option").each(function()
{
options.push($(this).val());
});

You can try this:
If you're using jQuery you can try following
jQuery solution
function readValuesJQuery(){
var A = $("select option").map(function(){
return this.value;
}).get();
console.log(A);
}
OR
javascript solution
function readValuesJavascript(){
var ddlArray= new Array();
var ddl = document.getElementsByTagName('select')[0];
for (i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl .options[i].value;
}
console.log(ddlArray);
}
Demo

using jQuery:
function readValues() {
var values = [];
$('[name="cars"] option').each(function() {
values.push($(this).val());
});
return values;
}
using pure javascript:
var readValues = function () {
var options = document.getElementById('carsId').children;
var values = [];
for(i = 0; i < options.length; ++i) {
values.push(options[i].value);
}
console.log(values);
return values;
}
Demo: http://jsfiddle.net/q94ndrcc/

click here
$("#sel").click(function(e) { // when link clicked
e.preventDefault();
$("#foo option:selected ").each(function() {
var v = $(this).attr("value"); // first select's value
$('#bar option').each(function() {
if ($(this).attr("value") == v) {
$(this).attr("selected",true); // select if same value
}
});
});
})

Try following its working.
HTML
<select name="cars" id="carsId" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="button" id="btnClick" value="getValue">
Script: jQuery 1.9.1
//1. for selected value:
$(document).ready(function(){
$('#btnClick').click(function(){
var selText = [];
$("#carsId option:selected").each(function () {
var $this = $(this);
if ($this.length) {
selText.push($this.text());
}
});
alert(selText);
});
});
//2. get all value without any selection:
$(document).ready(function(){
$('#btnClick').click(function(){
var selText = [];
$("#carsId option").each(function () {
var $this = $(this);
if ($this.length) {
selText.push($this.text());
}
});
alert(selText);
});
});
Running Demo

Related

Javascript find in List

<datalist id="MyList">
<option title="SomeId">SomeName</option>
<option title="SomeId">SomeName</option>
<option title="SomeId">SomeName</option>
<option title="SomeId">SomeName</option>
</datalist>
Connected to this input:
<input id="MyPicker" type="text" list="MyList" onclick="this.value = ''">
Then I have this code:
document.querySelector('input[list="MyList"]').addEventListener('input', onInput);
function onInput(e) {
var input = e.target,
val = input.value;
list = input.getAttribute('list'),
options = document.getElementById(list).childNodes;
var myItem;
for (var i = 0; i < options.length; i++) {
var trimmed_option = options[i].innerText;
try {
trimmed_option = trimmed_option.trim();
} catch (err) { }
if (trimmed_option == val.trim()) {
myItem = options[i];
alert("I got it");
break;
}
}
}
What I am doing is: Find current item in the list. I am however only able to find item only in some occasions.
What I want to do: I want to be able to find item everytime.
My idea: I could find it based on id of <option> but I was unable to do that.
Thanks for all help.
I am really uncertain about what you want. The <datalist> mechanism you are using here already works without any JavaScript, see below (I commented out the attachment of the event-listener). What exactly do you want to achieve with your script?
// document.querySelector('input[list="MyList"]').addEventListener('input', onInput);
function onInput(e) {
var input = e.target,
val = input.value;
list = input.getAttribute('list'),
options = document.getElementById(list).childNodes;
var myItem;
for (var i = 0; i < options.length; i++) {
var trimmed_option = options[i].innerText;
try {
trimmed_option = trimmed_option.trim();
} catch (err) { }
if (trimmed_option == val.trim()) {
myItem = options[i];
alert("I got it");
break;
}
}
}
<datalist id="MyList">
<option title="hp">Harry Potter</option>
<option title="hg">Hermione Granger</option>
<option title="rw">Ron Weasley</option>
<option title="gw">Ginny Weasley</option>
</datalist>
<input id="MyPicker" type="text" list="MyList" onclick="this.value = ''">

Loop through a data array variable and select items from multi-select dropdown

Created a multi-select dropdown, when I click on any of the options I have a input field which stores the values in a textbox. When the page reloads- I want to reselect the values in the multi-select drop down. The text box keeps its values so i was hoping to loop through this if i put it in an array.
E.g. Text contains: "cheese,mozarella"
It is important to only check the items that have the value in the textbox
Jquery:
document.getElementById("txt1").value = "cheese,mozarella";
var data = document.getElementById("txt1").value;
var dataarray = data.split(","); //splits values (,)
console.log(dataarray);
var i;
for (i = 0; i < dataarray.length; i++) {
}
HTML:
<input type="text" runat="server" id="txt1" visible="true" value="0" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="cheese">Cheese</option>
<option value="tomatoes">Tomatoes</option>
<option value="mozarella">Mozzarella</option>
<option value="mushrooms">Mushrooms</option>
<option value="pepperoni">Pepperoni</option>
<option value="onions">Onions</option>
</select>
</div>
I have a codeply to demonstrate: https://www.codeply.com/go/mCcxCM0vHs
My aim is to get some jquery code to loop through a dataarray variable and check the box if the value exists and tick it.
This function receives a select and a value and will cycle through the select's options, compare to the given value and mark matching options as selected.
function prepopulateOptions(selectElement, value) {
var options = selectElement.options;
for (var i = 0, numberOfOptions = options.length; i < numberOfOptions; i++) {
if (options[i].value == value) {
options[i].selected = true;
}
}
}
This function clears all selected options.
function clearSelect(selectElement) {
var options = selectElement.options;
for (var i = 0, numberOfOptions = options.length; i < numberOfOptions; i++) {
options[i].selected = false;
}
}
Then tweak your script:
var data = "cheese,mozarella",
dataarray = data.split(","),
selectElement = document.getElementById('basic');
// clear select first
clearSelect(selectElement);
for (var i = 0; i < dataarray.length; i++) {
prepopulateOptions(selectElement, dataarray[i]);
}
Check the fiddle
With jQuery this could be rewritten even easier:
https://jsfiddle.net/rtm0n53b/
Use the localStorage and jQuery.
<script type="text/javascript">
function fnLoadOptions(text){
//--clear selection
$('#basic option').prop("selected", false);
//--load selection
text = text||'';
var items = text.split(',');
for(var i in items) {
$('#basic option[value="'+items[i]+'"]').prop("selected", true);
}
if($.fn.multiselect!=null) {
$('#basic').multiselect('refresh'); //--if using the bootstrap multiselect plugin, then refresh it.
}
}
var key = 'checkedOptions';
//--load previous selection
var previousSelection = localStorage.getItem(key);
fnLoadOptions(previousSelection);
$("#txt1").val(previousSelection);
//--bind to new selection
$('#basic').change(function () {
var v = $('#basic').val();
$("#txt1").val(v);
localStorage.setItem(key,v);
});
$('#txt1').bind("keyup change",function () {
fnLoadOptions($(this).val());
});
</script>

Javascript function to get sum of selected values from html select menu

My HTML code is:
<div data-role="fieldcontain"style="padding:0; margin:0; padding-top:0px;">
<div style = "margin-top:-5px">
<select name="selectmenue1" id="sm" data-native-menu = "false" multiple = "multiple" >
<option value="1" selected="selected">iOS</option>
<option value="2">Android</option>
<option value="3">BlackBerry</option>
<option value="4">Others</option>
</select>
</div>
</div>
and I am using this Javascript function to get a sum of selected values:
function check_sm()
{
var c_value = 0;
for (var i=0; i < document.myform.sm.length; i++)
{
if (document.myform.sm[i].checked)
{
c_value = (eval(c_value) + eval(document.myform.sm[i].value));
}
}
alert(c_value);
}
function is not working. need some suggestions.
Using selected should solve your problem. See below code
function check_sm() {
var c_value = 0;
var sm1 = document.getElementById("sm");
for (var i = 0; i < sm1.length; i++) {
if (sm1[i].selected)
{ c_value = (eval(c_value) + eval(sm1[i].value)); }
} alert(c_value);
}
Do you mean:
var c_value = 0;
function check_sm() {
var Selected = document.myform.selectmenue1.selectedIndex;
var selectedVal = document.myform.selectmenue1.options[Selected].value;
selectedVal = parseInt(selectedVal, 10);
c_value +=selectedVal;
alert(c_value);
}
I don't think there is "checked" property available in select element. You have to use .selected property to find out whether option is selected or not, something like -
function getSum(){
var sm = document.getElementById("sm");
var sum = 0;
for(var i=0;i<sm.options.length;i++)
{
if(sm.options[i].selected){
sum+=parseInt(sm.options[i].value);
}
}
alert(sum);
}
You can do better using jquery:-
$("select").change(function () {
var count = 0;
$("select option:selected").each(function () {
count = Number(count) + Number($(this).val());
});
alert(count);
}).change();

Setting One Drop Down after Selecting from Another

I have a couple select elements:
<select name="empID" onchange='setSupervisor(this);'>
<option value="111" sid="222">Eric Employee</option>
...
</select>
<select name="supervisorID">
<option value="333">Susie Supervisor</option>
<option value="222">Stan Supervisor</option>
</select>
And a javascript function:
function setSupervisor(sender)
{
??
}
How can I set the supervisor dropdown after the user selects from the employee dropdown? The tricky part here (at least to me) is having to use a custom sid and not the value from the employee dropdown.
function setSupervisor(sender) {
var selectedOption = sender.getElementsByTagName("option")[sender.selectedIndex];
var sid = selectedOption.getAttribute("sid");
var supervisorSelect = document.getElementsByName("supervisorID")[0];
for (var i = 0, len = supervisorSelect.options.length, option; i < len; ++i) {
option = supervisorSelect.options[i];
if (option.value == sid) {
option.selected = true;
return;
}
}
}
Try this:
var empID = document.getElementsByName("empID").item(0);
var supervisorID = document.getElementsByName("supervisorID").item(0); //This becomes a bit easier if you set an ID as well as a name in your HTML
var index = empID.selectedIndex;
var sid = empID.options[index].getAttribute("sid");
for(var i=0; i<supervisorID.options.length; i++)
{
if(supervisorID.options[i].value == sid)
{
supervisorID.selectedIndex = i;
break;
}
}

Is there any way to repopulate an Html Select's Options without firing the Change event (using jQuery)?

I have multiple selects:
<select id="one">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<select id="two">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
What I want is to select "one" from the first select, then have that option be removed from the second one.
Then if you select "two" from the second one, I want that one removed from the first one.
Here's the JS I have currently:
$(function () {
var $one = $("#one");
var $two = $("#two");
var selectOptions = [];
$("select").each(function (index) {
selectOptions[index] = [];
for (var i = 0; i < this.options.length; i++) {
selectOptions[index][i] = this.options[i];
}
});
$one.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[1].length; i++) {
var exists = false;
for (var x = 0; x < $two[0].options.length; x++) {
if ($two[0].options[x].value == selectOptions[1][i].value)
exists = true;
}
if (!exists)
$two.append(selectOptions[1][i]);
}
$("option[value='" + selectedValue + "']", $two).remove();
});
$two.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[0].length; i++) {
var exists = false;
for (var x = 0; x < $one[0].options.length; x++) {
if ($one[0].options[x].value == selectOptions[0][i].value)
exists = true;
}
if (!exists)
$one.append(selectOptions[0][i]);
}
$("option[value='" + selectedValue + "']", $one).remove();
});
});
But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the disabled attribute on the option I want to remove, but that doesn't work with IE6.
I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler while you repopulate the items or, at the least, set a flag that you then test for and based on its value, handle the change.
Here's the final code that I ended up using, the flag (changeOnce) worked great, thanks #Jason.
$(function () {
var $one = $("#one");
var $two = $("#two");
var selectOptions = [];
$("select").each(function (index) {
selectOptions[index] = [];
for (var i = 0; i < this.options.length; i++) {
selectOptions[index][i] = this.options[i];
}
});
var changeOnce = false;
$one.change(function () {
if (changeOnce) return;
changeOnce = true;
var selectedValue = $("option:selected", this).val();
filterSelect(selectedValue, $two, 1);
changeOnce = false;
});
$two.change(function () {
if (changeOnce) return;
changeOnce = true;
var selectedValue = $("option:selected", this).val();
filterSelect(selectedValue, $one, 0);
changeOnce = false;
});
function filterSelect(selectedValue, $selectToFilter, selectIndex) {
for (var i = 0; i < selectOptions[selectIndex].length; i++) {
var exists = false;
for (var x = 0; x < $selectToFilter[0].options.length; x++) {
if ($selectToFilter[0].options[x].value == selectOptions[selectIndex][i].value)
exists = true;
}
if (!exists)
$selectToFilter.append(selectOptions[selectIndex][i]);
}
$("option[value='" + selectedValue + "']", $selectToFilter).remove();
sortSelect($selectToFilter[0]);
}
function sortSelect(selectToSort) {
var arrOptions = [];
for (var i = 0; i < selectToSort.options.length; i++) {
arrOptions[i] = [];
arrOptions[i][0] = selectToSort.options[i].value;
arrOptions[i][1] = selectToSort.options[i].text;
arrOptions[i][2] = selectToSort.options[i].selected;
}
arrOptions.sort();
for (var i = 0; i < selectToSort.options.length; i++) {
selectToSort.options[i].value = arrOptions[i][0];
selectToSort.options[i].text = arrOptions[i][1];
selectToSort.options[i].selected = arrOptions[i][2];
}
}
});
Or you can just hide the option you don't want to show...
function hideSelected($one, $two)
{
$one.bind('change', function()
{
var val = $one.val();
$two.find('option:not(:visible)').show().end()
.find('option[value='+val+']').hide().end();
})
}
hideSelected($one, $two);
hideSelected($two, $one);
EDIT: Oh sorry, this code does not work with IE6...

Categories