<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 = ''">
Related
with vanilla javascript I'd like to loop through my dropdown, and change the selected one, and then change the text that is displayed. I have it selecting, but I'm not getting the object name correct to change the optionText? of the item.
var textToFind = 'LdapUsers';
var dd = document.getElementById('membershipProvider');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
i.options.text = "Edgewood Login"; //This is WRONG
break;
}
}
guidance is appreciated.
You can use a querySelector and a selector to access it without a loop.
v = "222";
selProvider = document.querySelector("#membershipProvider option[value='" + v + "']");
if (selProvider) {
selProvider.text = "CHANGED!";
selProvider.selected = true;
}
<select id="membershipProvider">
<option value='111'>AAA</option>
<option value='222'>BBB</option>
</select>
You need to modify the option at that index. Right now you are trying to modify the index itself.
should be:
dd.options[i].text
not
i.options.text
var textToFind = 'LdapUsers';
var dd = document.getElementById('membershipProvider');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
dd.options[i].text = "Edgewood Login"; //This is WRONG
break;
}
}
<select id="membershipProvider">
<option value="cifs">CIFS</option>
<option value="LdapUsers">LdapUsers</option>
<option value="nfs">NFS</option>
<option value="test">Test</option>
</select>
You should use
dd.options[i].text = "Edgewood Login";
just like when checking for its value
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>
I have a select dropdownlist with 1 item selected at page load in html.
<select name = "options">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "3">Item3</option>
<option value = "4">Item4</option>
</select>
Now I want to capture new select option when user press shift and select another option such as "Item 3".
I have the following code to find all the selections in the list
var value = "";
for (var intLoop = 0; intLoop < Form.elements[index].length; intLoop++) {
if(Form.elements[index][intLoop].selected )
value = value + Form.elements[index][intLoop].value;
}
I can see the "Item 2" and "Item 3" are selected but i want to get capture "Item 3" only. Is it possible?
Here's code that will tell you what has been selected and what has been deselected http://jsfiddle.net/8dWzB/
It uses Array.prototype.indexOf, and it's not the fastest way to do it. But it should get you going in the right direction.
HTML
<select id="options" multiple="multiple">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "3">Item3</option>
<option value = "4">Item4</option>
</select>
JS
function getSelectedIndexes(select) {
var selected = [];
for (var i = 0; i < select.options.length; i++) {
if(select.options[i].selected ) {
selected.push(i);
}
}
return selected;
}
var select = document.getElementById("options");
var prevSelected = getSelectedIndexes(select);
select.onchange = function(e) {
var currentlySelected = getSelectedIndexes(this);
for (var i =0; i < currentlySelected.length; i++) {
if (prevSelected.indexOf(currentlySelected[i]) == -1) {
console.log("Added to selection ", this.options[currentlySelected[i]].text);
}
}
for (var i =0; i < prevSelected.length; i++) {
if (currentlySelected.indexOf(prevSelected[i]) == -1) {
console.log("Removed from selection ", this.options[prevSelected[i]].text);
}
}
prevSelected = currentlySelected;
};
If you really only want to know which item was last clicked, you can use the following code. I'll use jQuery so I can easily set a handler on all the option objects. Remember this won't work if you change the selection with the keyboard
$('option').click(function(e){
var parentNode = this.parentNode;
for (var i=0; i < this.parentNode.options.length; i++) {
if (parentNode.options[i] == this) {
console.log('Clicked item with index', i);
break;
}
}
});
You could check the value of the selected options before a change event (e.g. item 1 and 2 are selected) and then again after the event (e.g. item 1, 2 and 3 are selected), and compare the difference.
Here is an example.
Fiddle here: http://jsfiddle.net/FnAuz/4/
I modified your select to allow multiple selections since I take it that's the crux of the problem.
HTML:
<form id="my-form">
<select name = "options" id="options" multiple>
<option value = "val1">Item1</option>
<option value = "val2">Item2</option>
<option value = "val3">Item3</option>
<option value = "val4">Item4</option>
</select>
</form>
JS:
var oldValue = "";
document.getElementById('options').onchange = function() {
var myForm = document.getElementById ('my-form');
var value = "";
for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
if(myForm.elements[0][intLoop].selected) {
value = value + myForm.elements[0][intLoop].value;
}
}
for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
var optionVal = myForm.elements[0][intLoop].value;
if(myForm.elements[0][intLoop].selected && value.indexOf(optionVal) !== -1 && oldValue.indexOf(optionVal) === -1) {
console.log('Last clicked was ' + myForm.elements[0][intLoop].value)
}
}
oldValue = value;
};
EDIT: I just noticed that my example works when the user makes command/ctrl selections, but if they make a shift selection then ALL the new values will be counted as the 'last clicked item'. So my code would need some work to account for this scenario. I'm out of time, but hopefully my code is useful in its current state nevertheless!
Try this :
var e = document.getElementById("ID_of_Select_Element");
var _selectedValue= e.options[e.selectedIndex].value;
It started looking messy so I'm posting it as an answer:
<html>
<head>
<script type="text/javascript">
<!--
var value = '0';
document.getElementById('options').onchange = function() {
value = parseInt(value) + parseInt(this.value);
alert(value);
}
-->
</script>
</head>
<body>
<select name="options" id="options">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "4">Item3</option>
<option value = "8">Item4</option>
</select>
</body>
</html>
Edition for selecting multiple items:
well, if you want to accumulate items you can assign binary IDs to each product and then you can extract all the selected products from the total. for example, if the total is: 7 you can easily translate it to a binary string "111" which means they selected items 1,2,4. Sounds a bit crazy, I know, just an idea ;)
I am trying to make auto complete to select option according to input from the user
something like
<input type=text onkeyup=findit()>
<select id="sel">
<option value="s0001">Adams</option>
<option value="s0002">Alder</option>
.
.
.
<select>
I found this code 'but it only work on one select in the page( I need multi select)
<html>
<head>
<script type="text/javascript">
//initialize some global variables
var list = null;
function fillit(sel,fld) {
var field = document.getElementById("entry");
var selobj = document.getElementById("sel");
if(!list)
{
var len = selobj.options.length;
field.value = "";
list = new Array();
for(var i = 0;i < len;i++)
{
list[i] = new Object();
list[i]["text"] = selobj.options[i].text;
list[i]["value"] = selobj.options[i].value;
}
}
else
{
var op = document.createElement("option");
var tmp = null;
for(var i = 0;i < list.length;i++)
{
tmp = op.cloneNode(true);
tmp.appendChild(document.createTextNode(list[i]["text"]));
tmp.setAttribute("value",list[i]["value"]);
selobj.appendChild(tmp)/*;*/
}
}
}
function findIt(sel,field)
{
var selobj = document.getElementById("sel");
var d = document.getElementById("display");
var len = list.length;
if(field.value.length > 1)
{
if(!list)
{
fillit(sel,field);
}
var op = document.createElement("option");
selobj.options.length = 1
var reg = new RegExp(field.value,"i");
var tmp = null;
var count = 0;
var msg = "";
for(var i = 0;i < len;i++)
{
if(reg.test(list[i].text))
{
// d.childNodes[0].nodeValue = msg;
tmp = op.cloneNode(true);
tmp.setAttribute("value",list[i].value);
tmp.appendChild(document.createTextNode(list[i].text));
selobj.appendChild(tmp);
}
}
}
else if(list && len > selobj.options.length)
{
selobj.selectedIndex = 0;
fillit(sel,field);
}
}
</script>
</head>
<body onLoad="fillit(sel,entry)">
<div>Enter the first three letters of a street and select a match from the menu.</div>
<form>
Street
<input type="text" name="Street" id="entry" onKeyUp="findIt(sel,this)"><br>
<select id="sel">
<option value="s0001">Adams</option>
<option value="s0002">Alder</option>
<option value="s0003">bol</option>
<option value="s0004">col</option>
<option value="s0005">dol</option>
<option value="s0007">Cooper</option>
<!--and so on and so forth-->
</select>
</form>
</body>
Any Ideas How to make it work on multi select on the page?
Thanks
Baaroz
Not sure if this would work for you, but chosen.js has a really nice autocomple multi select
http://harvesthq.github.com/chosen/
Usually Autocomplete is for single values, but the jQuery UI autocomplete does have a multiple select function. Perhaps try that? Minimum effort coding for you that way.
An odd way to do that is to change the ID in the script and copy it the number of times you want to use this options in the page. so for example:
select id="sel1"
select id="sel2"
select id="sel3"
and then. copy the script and replace every (sel) with sel1 past it again and replace (sel) with sel2 and so on.
not the best solution but it will work.
Good Luck
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;
}
}