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
Related
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>
<select id="gameid">
//<option is a number 1-999>
</select>
<select id="netid">
//<option is a number 1-999>
</select>
<select id="camp_id">
<script>
var a = $("#gameid").val();
var b = $("#netid").val();
var c = a+b;
for (var i = 1; i<=999; i++)
{
document.write("<option value='"+c+i+"'>"+c+i+"</option>");
}
</script>
</select>
The code above is to generate some options into selection.
What I want to do there is, if the val in the #gameid is changed, the option list will change too, and so does for the #netid.
However, the option doesn't change. It stay in the default value of the #gameid and #netid.
I don't know what I am missing here. I need a help, please.
[UPDATE]
This code almost work. However, when I do the second change on the #cameid after all I have been select, it doesn't change the #campid selection anymore. It will do change it again if I do the change too on the #netid.
$("#gameid" && "#netid").on('change', function(){
a = $("#gameid").val(),
b = $("#netid").val(),
c = a+b;
$("#camp_id").empty();
for (var i = 1; i<=999; i++){
$("#camp_id").append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
});
Use something like this:
var options = '';
for (var i = 1; i<=999; i++)
{
options += "<option value='"+c+i+"'>"+c+i+"</option>";
}
document.getElementById('camp_id').innerHTML = options;
Use similar to insert options to other select boxes if needed
Don't forget to add Jquery library,
<select id="gameid" onchange="generateOptions();">
<!-- Your Options -->
</select>
<select id="netid" onchange="generateOptions();">
<!-- Your Options -->
</select>
<select id="camp_id">
</select>
<script type="text/javascript">
var a,b,c,str="";
function generateOptions()
{
a = $("#gameid").val();
b = $("#netid").val();
c = a+b;
for (var i = 1; i<=999; i++)
{
str= str + "<option value='"+c+i+"'>"+c+i+"</option>";
}
$('#camp_id').html(str);
}
</script>
var a = $("#gameid").val(),
b = $("#netid").val(),
c;
$("#gameid").change(function(){
a = $(this).val();
c = parseInt(a)+parseInt(b);
$("#camp_id").empty();
for (var i = 1; i<=999; i++){
$("#camp_id").append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
});
https://jsfiddle.net/partypete25/j9toh39c/
Use change event
$('#gameid,#netid').on('change',function (){
var a = $("#gameid").val();
var b = $("#netid").val();
alert($(this).attr('id'));
var c = parseInt(a)+parseInt(b);
if ( $(this).attr('id') == 'gameid') {
$el = $("#netid");} else {$el = $("#gameid")};
$el.text('');
for (var i = 1; i<=999; i++)
{
$el.append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
});
note: I used jquery, jsfiddle: https://jsfiddle.net/1zgre9pw/4/
As you want to add options to HTML select dynamically. I have tried to achieve the same using jquery i.e. to be call on $('#gameid').populate();.
Firstly, Add jquery library in <head> of page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>`
WORKING DEMO
$.fn.populate = function () {
var $this = $(this);
for (var i = 1; i<=999; i++){
$this.append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
}
$('#gameid').populate();
You can add same for second select(drop-down) as well.
I want to restrict to add the same item more than once to the second listbox, i think i am very close to it . please help
<script type="text/javascript">
function CopyFile() {
var firstListBox = document.getElementById('<%= lstFirstBox.ClientID %>');
var secondListBox = document.getElementById('<%= lstTarget.ClientID %>');
for (var i = 0; i < firstListBox.options.length; i++) {
if (firstListBox.options[i].selected) {
for (var j = 0; j < secondListBox.options.length; j++) {
if (firstListBox.options[i].selected == secondListBox.options[j]) {
alert("Multiple selection will not allow");
}
else {
var newOption = document.createElement("option");
newOption.text = firstListBox.options[i].text;
newOption.value = firstListBox.options[i].value;
secondListBox.options[secondListBox.options.length] = newOption;
firstListBox.options[i].selected = false;
}
}
}
}
return false;
}
</script>
I wrote you an example. Following html page has two selects and one button. If you select an option in the first select and press the button, the option will be copied to the second select, unless it's already there. In the last case, it will alert a message. to try it, copy paste it in a file (for example "test.htm") and open it in a browser.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function tryToCopy() {
var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");
var optionToBeCopied = select1.options[select1.selectedIndex];
var contains = false;
for(var i = 0, ceiling = select2.options.length; i < ceiling; i++) {
if(select2.options[i].value == optionToBeCopied.value) {
contains = true;
break;
}
}
if(contains) {
alert("duplicate options are not allowed.");
} else {
var option = document.createElement("option");
select2.appendChild(option);
option.value = optionToBeCopied.value;
option.text = optionToBeCopied.text;
}
}
</script>
</head>
<body>
<select id="select1">
<option value="" selected="true"></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="select2">
</select>
<input type="button" value="tryToCopy" onclick="tryToCopy()"/>
</body>
</html>
I recently trying to make a form with multiple select box. When someone select the options the number of selected options will be display on another text. I'm a beginner in JavaScript.
The function is called, but it doesn't count the number of the selected options.
<select name="element_17_1[ ]"
size="7" multiple="multiple"
class="element select medium"
id="element_17_1[ ]"
onfocus="selectCount(this.form);"
onClick="selectCount(this.form);"
>
<option value="Opt1">Opt1</option>
<option value="Opt2">Opt2</option>
<option value="Opt3">Opt3</option>
<option value="Opt4">Opt4</option>
<option value="Opt5">Opt5</option>
<option value="Opt6">Opt6</option>
<option value="Opt7">Opt7</option>
</select>
and this is the function I tried in the <head>
function selectCount(f) {
var selObj = myForm.elements['element_17_1[]'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
totalChecked++;
}
}
f.element_9.value = totalChecked;
}
You're trying to get an element named element_17_1[], but your select box is named element_17_1[ ]. JavaScript just sees the name as a bunch of characters, and that space makes a difference.
In your HTML you have:
> <select name="element_17_1[ ]"
> size="7" multiple="multiple"
> class="element select medium"
> id="element_17_1[ ]"
> onfocus="selectCount(this.form);"
> onClick="selectCount(this.form);"
> >
Note that in the listener, this references the element itself, so just pass that:
onfocus="selectCount(this);"
onClick="selectCount(this);"
So a reference to the element is passed directly to the function, which can be:
function selectCount(selObj) {
// The following line isn't needed now
// var selObj = myForm.elements['element_17_1[]'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
totalChecked += selObj.options[i].selected? 1 : 0;
}
// The next line needs the form, so
selObj.form.element_9.value = totalChecked;
}
Now you don't care what the select element is called. :-)
Edit
To click element_9 you might do:
<input name="element_9" onclick="
this.value = selectCount(this.form['element_17_1[ ]']);
">
Then the function is modified to:
function selectCount(selObj) {
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
totalChecked += selObj.options[i].selected? 1 : 0;
}
return totalChecked;
}
Enough homework for now. ;-)
Change your select's name name="element_17_1"and id id="element_17_1" and in also you don't have myForm in your function so var selObj = myForm.elements['element_17_1']; should be var selObj = f.elements['element_17_1']; and also you can use only on event as follows
onChange="selectCount(this.form);"
instead of
onfocus="selectCount(this.form);"
onClick="selectCount(this.form);"
Complete function:
function selectCount(f) {
var selObj = f.elements['element_17_1'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
totalChecked++;
}
}
f.element_9.value = totalChecked;
}
Update:
For your php scriptyou can keep your select's name name="element_17_1[]" and so in the function it should be var selObj = f.elements['element_17_1[]']; but without space like[ ]
DEMO.
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;
}
}