Chosen select box with multiple selected values on page load - javascript

I'm trying to select multiple values on page load, but it only selects the last value on the array. Take a look at the code
jQuery("#language").chosen();
var str = '12,24,36';
var languageArray = str.split(',');
for (var i = 0; i < languageArray.length; i++) {
jQuery("#language").val(languageArray[i]);
jQuery("#language").trigger("liszt:updated");
}
I get only 36 selected on page load, is there anything wrong with the js ?
Here is the HTML for the select
<select name="language[]" id="language" data-placeholder="Choose Language..." multiple="multiple">
I appreciate your help.
Thanks

You can select multiple options in a multi-value select box by passing an array to the val() method.
Example
Markup
<select name="language" id="language" data-placeholder="Choose Language..." multiple="multiple">
<option value="en">English</option>
<option value="fr">French</option>
<option value="de">German</option>
</select>
JavaScript
var str = 'en,de';
jQuery("#language").val(str.split(','));
And here's a jsFiddle for funsies.

you could set the selected property of matched option element. hope it would help.
var values = ['1', '2', '4'];
$('#languages').find('option').filter(function (idx, option) {
if($.inArray(option.value, values) !== -1) {
return option;
}
}).prop('selected', 'true');

Related

Two dynamic select boxes with data attribute in both and dependant on them

How to get dynamic select boxes dependant on the value of data attributes in both?
Got this code
HTML
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>
JS
var sel1 = document.querySelector('#hours');
var sel2 = document.querySelector('#paxno');
var options2 = sel2.querySelectorAll('option');
function giveSelection() {
sel2.innerHTML = '';
for(var i = 0; i < options2.length; i++) {
if(options2[i].dataset.option === $("#hours").find(":selected").data("option")) {
sel2.appendChild(options2[i]);
}
}
}
I have been trying to do this from the example given on this question on Stackoverflow, and it is working when data-attribute is non numeric but data stored in both will be numeric.
Any thoughts what I am doing wrong here? is this the best approach to 2 dynamic select boxes with both having data attributes?
Since you're using jQuery, you might as well use it all the way.
To make it consistent, always use the jQuery data() method. data() will always try to intelligently convert the value of the data field to another type if it can determine that it is a number, or an object, or an array, or etc. So your original was comparing a dataset.option to a data(), using === which removes type coersion. So nothing would ever be equal.
var sel1 = $('#hours');
var sel2 = $('#paxno');
var options2 = sel2.find('option');
function giveSelection() {
var target = sel1.find(':selected').data('option');
sel2.empty().append(
options2.filter(function(){
return $(this).data('option') === target;
})
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>

Javascript: dropdown, get first element value LIKE?

Given a dropdown with an unknown number of option elements:
<select id="ddlDropDown">
<option value="text1">Some text</option>
<option value="text2">Some text</option>
<option value="text3">Some text</option>
...
<option value="textN">Some text</option>
And given a textbox where I can type in a value:
<input type=text id="txtTextBox" onkeyup="selectDDL();"/>
And given the script function:
function selectDDL(){
var txtElem = document.getElementById("txtTextBox");
var ddlElem = document.getElementById("ddlDropDown");
var typedText = txtElem.value;
//magic happens here
}
How do I, using purely javascript, get select the first option matching LIKE the text in the text box without iterating through the entire collection?
That is to say, assume that I have 500 dropdown option elements with random values between 500 and 1500, how do I get and select the first option (in the list, not in order) that matches what the user has typed so far?
So if their were three items: 1030, 1012, and 1013 in the dropdown and the user types:
1: 1030 is selected.
10: 1030 is still selected
101: 1012 is selected
1013: 1013 is selected
Clarification: without iterating the collection and similar to jquery's ^= operator
You don't need jQuery to use ^=, just use querySelectorAll with the attribute prefix selector:
var texts = document.querySelectorAll("[value^='text']");
console.log(texts);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<select id="ddlDropDown">
<option value="text1">Some text</option>
<option value="text2">Some text</option>
<option value="text3">Some text</option>
<option value="textN">Some text</option>
<option value="notText">123456</option>
</select>
You can use a starts with attribute selector. Only issue with the code is I am not escaping any of the special characters from the selector. So if the user enters in ' it will blow up.
document.querySelector("#x").addEventListener("keyup", function(){
//code to filter out the options
var txt = this.value;
var opts = document.querySelectorAll("#ddlDropDown option[value^='" + txt + "']");
//code to display the options for demo
var out = Array.prototype.slice.call( opts ).map(function (x) {return x.value});
document.querySelector("p").innerHTML = out.join("<br/>");
});
<select id="ddlDropDown">
<option value="text1">Some text</option>
<option value="text2">Some text</option>
<option value="text3">Some text</option>
<option value="text11">Some text</option>
<option value="text21">Some text</option>
<option value="text31">Some text</option>
</select>
<input type="textbox" id="x">
<p></p>
I would use the string#indexOf method to find out if there's a match.
function selectDDL() {
var txtElem = document.getElementById("txtTextBox");
var ddlElem = document.getElementById("ddlDropDown");
var typedText = txtElem.value;
var options = document.querySelectorAll("#ddlDropDown option");
var matches = [];
for (var i = 0; i < 3; i++) {
if (options[i].innerHTML.indexOf(typedText) == 0) {
matches.push(options[i]);
}
}
matches[0].setAttribute("selected", "selected");
}
Those who rely on a selector with [value^=...] will find an option by its value attribute, not by its text.
There is no CSS selector for selecting an option by its text. jQuery supports "has" and "contains", but uses iteration to implement those features.
Just for a fun alternative, but probably not advisable: innerHTML is slow and this will go wrong when the select tag has other tags inside than the options:
var html = ddlElem.innerHTML;
var idx = html.indexOf('>'+typedText);
ddlElem.selectedIndex = idx === -1
? -1
: html.substr(0, idx).match(/\<option/g).length - 1;

How to establish relationship between option tag of different select tags in html

I have three select tags in HTML with option tag.I want to establish relationship between option tags of different select tag.
EDIT-1
When I choose Reference-1 from select name="reference" then 2014-10-10 07:17:00 and 2014-10-10 08:46:00 from select name="from" and select name="to" should only be present in the dropdown list.When I choose Reference-2 then 2014-09-01 10:00:00 and 2014-09-01 11:00:00 should only be present in dropdown list of from and to select tag. My html code for is-
<form method="post">
Select Reference:
<select name="reference">
<option value="Select">Select</option>
<option value="Reference-1">Reference-1;</option>
<option value="Reference-2">Reference-2</option>
<option value="Reference-3">Reference-3</option>
<option value="Reference-4">Reference-4</option>
</select>
From Date:
<select name="from">
<option value="Select">Select</option>
<option value="2014-10-10 07:17:00">2014-10-10 07:17:00</option>
<option value="2014-09-01 10:00:00">2014-09-01 10:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 10:00:00</option>
</select>
To Date:
<select name="to">
<option value="Select">Select</option>
<option value="2014-10-10 08:46:00">2014-10-10 08:46:00</option>
<option value="2014-09-01 11:00:00">2014-09-01 11:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 11:00:00</option>
</select><br>
<b>Select Date to be compared</b>
<p>Date: <input type="text" id="datepicker"></p>
<input type="submit" value="Submit"><br>
</form>
Get the index of the selected option from reference select element and then disable all the options of from and to select elements except the option with index of the previous index you got from reference select option.
javaScript Solution :
var reference = document.getElementsByName("reference")[0];
var fromSelect = document.getElementsByName("from")[0];
var toSelect = document.getElementsByName("to")[0];
reference.onchange = function(){
var selectedIndex = this.selectedIndex;
for(var i = 1; i <= fromSelect.length; i++){
if(i != selectedIndex){
fromSelect.getElementsByTagName("option")[i].disabled = true;
toSelect.getElementsByTagName("option")[i].disabled = true;
} else{
fromSelect.getElementsByTagName("option")[i].disabled = false;
toSelect.getElementsByTagName("option")[i].disabled = false;
}
}
};
jsFiddle
jQuery Solution :
$("select[name='reference']").on("change", function(){
var $fromSelect = $("select[name='from']");
var $toSelect = $("select[name='to']");
var selectedIndex = $(this).children("option:selected").index();
$fromSelect.children("option").removeAttr("disabled");
$toSelect.children("option").removeAttr("disabled");
$fromSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
$toSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
});
jsFiddle
If second selection values are dependent on the first selection option, then you should disable the whole second selection until the first one is selected.
When the first one is selected then disable all the unrelated options in second selection and make it enabled to the user. Let me know if it helped.
$("select[name='reference']").on('change', function() {
var value = $(this).val(); // first selection value
if ("Reference-1" == value ) {
var $selection2 = $("select[name='from']");
$selection2.find("option[value*='2014-09-01 10:00:00']").prop('disabled',true);
$selection2.find("option[value*='2014-09-08 10:00:00']").prop('disabled',true);
}
...
});
Here is DEMO

How can do select tag as value pair?

I have a pair of values.
I don't want a <key, value> pair.
I want a <value,value> pair.
I have created a select tag. and its options are the pairs.
<option value="value1" >value2</option>
The code below selects the options that have value=i.
options = $("#myselect option[value='"+i+"']");
I want to select the option that value=val1 and text = val2.
Any other idea?
You can use contains to further filter the selection:
options = $("#myselect option[value="+i+"]:contains('value"+j+"')");
You could use jQuery's filter() for this
var i = 1;
var options = $("#myselect option[value='value" + i + "']").filter(function(){
return $(this).text() == 'value'+(i+1)
});
console.log(options);
HTML
<select id="myselect">
<option value="value1">value1</option>
<option value="value1">value2</option>
<option value="value1">value3</option>
</select>
selects <option value="value1">value2</option>

JavaScript to select multiple select list values

I have the following select list from which the user can select multiple values.
<select name="valumethod1[]" id="valumethod1[]" onBlur="validatevalumethod()" size="6">
<option value ="t1">test1</option>
<option value ="t2">test2</option>
<option value ="t3">test3</option>
<option value ="t4">test4</option>
</select>
I want to fetch the selected values in JavaScript, but I don't know how to do this. Please help me.
Try something like this :
var ob = document.getElementById('valumethod1[]');
var selected = new Array();
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[ i ].selected) {
selected.push(ob.options[ i ].value);
}
}
The array selected is then an array of selected options. Working example here
Note: you need to add multiple="multiple" to your select list as an attribute

Categories