Checking for duplicate entries in select box - javascript

The following function, will dynamically add a new option value into a selectbox. Great feature, but it does not account and check for duplicate entries before adding new options into the select box. How can the code be modified such that it will alert the user that a duplicate entry has been found and to abort adding the same option value:
function addref() {
var value = document.getElementById('refdocs').value
if (value != "") {
var select = document.getElementById('refdocs_list');
var option = document.createElement('option');
option.text = value
select.add(option,select.option)
select.selectedIndex = select.options.length - 1;
}//end of if
}//end of function

DEMO: http://jsfiddle.net/abc123/rcwgk/2/
this will work this adds to both values and options you likely want to do something differently.
<html>
<head>
<script type="text/javascript">
var values = new Array();
var options = new Array();
if(!Array.prototype.indexOf) {
Array.prototype.indexOf = function(needle) {
for(var i = 0; i < this.length; i++) {
if(this[i] === needle) {
return i;
}
}
return -1;
};
}
function getOptions() {
var selectobject=document.getElementById("refdocs_list");
for (var i=0; i<selectobject.length; i++){
values.push(selectobject.options[i].value);
options.push(selectobject.options[i].text);
}
}
function addref() {
var value = document.getElementById('refdocs').value
if (value != "" && values.indexOf(value) == -1 && options.indexOf(value) == -1 ) {
values.push(value);
options.push(value);
var select = document.getElementById('refdocs_list');
var option = document.createElement('option');
option.text = value
select.add(option,select.option)
select.selectedIndex = select.options.length - 1;
}//end of if
}//end of function
</script>
</head>
<body onload="getOptions()">
<select id="refdocs_list">
<option value="1">test</option>
</select>
<input type="text" id="refdocs"/>
<input type="button" value="add" onclick="javascript:addref()" />
</body>
</html>

Related

How to Randomly Choose Selected Item in Select Dropdown that wasn't chosen before in JavaScript?

On a button click, I want to run a function that will each time randomly select an option from a select dropdown that wasn't chosen before. And if all options were chosen, I want to reset the used options and start from the beginning.
I have a function that chooses an element that wasn't chosen before randomly from an array (credit to #Rajesh)
function randomize(arr) {
let data = [...arr];
let chosenItems = [];
function getRandomValue() {
if (data.length === 0) {
data = chosenItems;
chosenItems = [];
}
const index = Math.floor(Math.random() * data.length);
const choice = data.splice(index, 1)[0];
chosenItems.push(choice);
return choice;
}
return {
randomItem: getRandomValue
}
}
const dummyData = [ 1,2,3,4,5 ];
const randomizeData = randomize(dummyData);
for (let i = 0; i< 10; i++) {
console.log(randomizeData.randomItem())
}
I have already created a script that randomly chooses an element from a select2 dropdown but it selects the same element very often.
var optionsArray = new Array();
var first = $('select option')[0];
$('select option').each(function () { optionsArray.push(this) });
if (optionsArray.length > 1) {
$('select').html('');
var i = 0;
var random
while (i < optionsArray.length) {
random = Math.floor(Math.random() * optionsArray.length)
//if element hasn't been marked as "selected"
if (optionsArray[random] != "selected") {
$("select").append(optionsArray[random]);
//mark element as selected
optionsArray[random] = "selected"
i++
}
}
var newSelectedOption = $('select option')[0];
$('select').val($(newSelectedOption).val()).trigger('change');
<html>
<body>
<select id="dropdown">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button id="btn">
Generate
</button>
</body>
<script>
let dropdown = document.getElementById('dropdown');
var options = [];
var chosenItems = [];
function setOptions(){
for(var i = 0; i < dropdown.options.length; i++)
options.push(dropdown.options[i].value);
}
document.getElementById('btn').addEventListener("click", function(){
options = options.filter( function( el ) {
return chosenItems.indexOf( el ) < 0;
});
if(options.length == 0){
console.log("reset data")
setOptions();
chosenItems = [];
}
var unSelectedRandom = options[Math.floor(Math.random() * options.length)]
for(var i = 0; i < dropdown.options.length; i++){
var current = dropdown.options[i]
if ( current.value == unSelectedRandom ) {
dropdown.selectedIndex = i;
chosenItems.push(current.value);
console.log("chosen: "+chosenItems)
}
}
});
</script>
</html>

Prevent duplicate values being added from a text box to a list box

I have a textbox where a user scans a barcode then selects an 'add to list' button which adds them to a listbox. I'm trying to modify it to prevent duplicates being added but can't seem to find a way that works.
function addToList(barcode) {
var barcode = document.getElementById("barcode").value.toUpperCase();
var opt = document.createElement("option");
document.getElementById("lstBox1").options.add(opt);
opt.text = barcode;
opt.value = barcode;
//$('barcode').val('');
document.getElementById("barcode").value='';
return false;
}
What would be the best way?
One possible solution is to keep track of the values entered in an Array
Then by checking if the value exists in the array or not, you can add the value to the dropdown
var allValues = [];
function addToList(){
var barcodeInput = document.getElementById("barcode");
var barcode = barcodeInput.value.toUpperCase();
barcodeInput.value='';
//if this value is already in the array, do nothing
if( -1 !== allValues.indexOf(barcode) ){
return;
}
allValues.push(barcode);
var opt = document.createElement("option");
document.getElementById("lstBox1").options.add(opt);
opt.text = barcode;
opt.value = barcode;
return false;
}
select{
min-width:100px;
}
<input id="barcode" />
<br/>
<select id="lstBox1"></select>
<br/>
<button onclick="addToList()">Add</button>
Check the value is not exist in the list before adding into the list.
You can try this
var listbox=document.getElementById("lstBox1")
for(var i; i<listbox.options.length; i++)
{
if(listbox.options[i].value!=barcode)
{
var opt = document.createElement("option");
opt.text = barcode;
opt.value = barcode;
listbox.options.add(opt);
}
}
Check whether inputted value already exist in the optionlist. If not present then add the value, else do nothing.
let found;
const submitBtn = document.querySelector('button');
submitBtn.addEventListener('click', function(e) {
e.preventDefault();
const val = document.querySelector('input').value.toLowerCase();
if(val.length > 0) {
const optionsArr = document.querySelectorAll('select > option');
found = [...optionsArr].filter((option) => option.value.toLowerCase() === val);
if(found.length == 0) {
addToList(val);
}
}
});
function addToList(val) {
const option = document.createElement('option');
option.value = val;
option.textContent = val;
document.querySelector('select').appendChild(option);
}
<input type="text">
<button>Add</button>
<select name="" id="">
<option value="usa">USA</option>
<option value="Japan">Japan </option>
</select>
This is an example you can use keeping some of the elements in memory and using Array.filter as validation strategy. Also you can seen for the filter I am showing an example of Arrow Functions to filter the duplicates.
let list = document.getElementById('lstBox1');
let input = document.getElementById('barcode');
let button = document.getElementById('addOption');
function addToList() {
let currentOptions = Array.from(list.options);
let barcode = input.value.toUpperCase();
let filter = currentOptions.filter(option => option.value == barcode);
if (filter.length == 0) {
let opt = document.createElement("option");
opt.text = barcode;
opt.value = barcode;
list.options.add(opt);
input.value = '';
} else {
alert('The value is duplicated');
}
};
button.addEventListener('click', addToList);
<input type="text" id="barcode">
<select name="" id="lstBox1">
<option value="TEST">TEST</option>
</select>
<button id="addOption">Add Option</button>
This is kind of bruteforce method but it will work. Using jQuery it
will be much simple.
1.This function will get all the list text
function getOptTxt() {
var x = document.getElementById("lstBox1").options.length;
var txt = [];
var i;
for (i = 0; i < x; i++) {
txt[i] += x.options[i].text;
}
}
2. You can check the barcode value ,If it is present in txt array or not if the value is not present in txt array then u can actually add the new option element
var flag =0
for (x in txt){
if(barcode == x.toUpperCase()){
flag =1
break;
}
}
if(flag == 0){
var opt = document.createElement("option");
document.getElementById("lstBox1").options.add(opt);
}

Replace dropdown options with only those that match values in an array

Hi I am struggling with doing this in raw JavaScript. Currently I have two dropdowns a parent and a child like so:
<select id="state" title="" name="state">
<option selected="selected" value="Open" label="Open">Open</option>
<option value="Closed" label="Closed">Closed</option>
</select>
<select id="status" title="" name="status">
<option value="Open_New" label="New">New</option>
<option value="Open_Assigned" label="Assigned">Assigned</option>
<option value="Closed_Closed" label="Closed">Closed</option>
<option value="Open_Pending Input" label="Pending External Input">Pending External Input</option>
<option value="Open_Pending" label="Pending Internal Input">Pending Internal Input</option>
<option value="Closed_Duplicate" label="Duplicate">Duplicate</option>
<option value="Open_CARD" label="CARD">CARD</option>
<option value="Open_Open" label="Open">Open</option>
<option value="Open_DAD" label="DAD">DAD</option>
<option value="Closed_Rejected" label="Rejected">Rejected</option>
</select>
And the child dropdown values are selected based on the parent dropdown values name with and an underscore:
function updateDynamicEnum(field, subfield){
if(document.getElementById(subfield) != null){
var selector = document.getElementById(subfield);
var de_key = document.getElementById(field).value;
var current = [];
for (var i = 0; i < selector.length; i++) {
if (selector.options[i].selected) current.push(selector.options[i].value);
}
if(de_entries[subfield] == null){
de_entries[subfield] = new Array;
for (var i=0; i<selector.options.length; i++){
de_entries[subfield][selector.options[i].value] = selector.options[i].text;
}
}
document.getElementById(subfield).innerHTML = '';
for (var key in de_entries[subfield]) {
if(key.indexOf(de_key+'_') == 0){
selector.options[selector.options.length] = new Option(de_entries[subfield][key], key);
}
}
for (var key in current) {
for (var i = 0; i < selector.length; i++) {
if(selector.options[i].value == current[key])
selector[i].selected = true;
}
}
}
What I need to do is change this code so that child dropdown values are not selected based on the key name with an underscore but selected when they are part of an array that is passed in. The array is called child_strings and looks like this:
'open' => array(
'Open_New',
'Open_Assigned',
'Open_Pending Input',
'Open_Pending',
'Open_CARD',
'Open_Open',
'Open_DAD'
),
'closed' => array(
'Open_Assigned',
'Closed_Closed',
'Closed_Duplicate',
'Closed_Rejected',
),
my new code looks like this:
function updateDynamicEnum(field, subfield, child_strings){
//console.log(child_strings);
if(document.getElementById(subfield) != null){
var de_key = document.getElementById(field).value;
var child = document.getElementById(subfield);
var current = [];
for (var i = 0; i < child.length; i++) {
if (child.options[i].selected) current.push(child.options[i].value);
}
if(de_entries[subfield] == null){
de_entries[subfield] = new Array;
for (var i=0; i<child.options.length; i++){
de_entries[subfield][child.options[i].value] = child.options[i].text;
}
}
document.getElementById(subfield).innerHTML = '';
//this part needs changes
for (var key in de_entries[subfield]) {
if(key.indexOf(de_key+'_') == 0){
child.options[child.options.length] = new Option(de_entries[subfield][key], key);
}
}
But struggling to see how to check child_strings and determine if the vales is in that array etc..
I figured the answer out for myself but if somebody can post a better one please go ahead.
function updateDynamicEnum(field, subfield, child_strings){
if(document.getElementById(subfield) != null){
var de_key = document.getElementById(field).value;
var child = document.getElementById(subfield);
var current = [];
for (var i = 0; i < child.length; i++) {
if (child.options[i].selected) current.push(child.options[i].value);
}
if(de_entries[subfield] == null){
de_entries[subfield] = new Array;
for (var i=0; i<child.options.length; i++){
de_entries[subfield][child.options[i].value] = child.options[i].text;
}
}
document.getElementById(subfield).innerHTML = '';
var arg = child_strings[de_key];
for (var key in de_entries[subfield]) {
if(isInArray(key,arg)){
child.options[child.options.length] = new Option(de_entries[subfield][key], key);
}
}
for (var key in current) {
for (var i = 0; i < child.length; i++) {
if(child.options[i].value == current[key])
child[i].selected = true;
}
}
}
/*Checks if value is in an array*/
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
}

Add item to dropdown list in HTML using JavaScript

I have this JavaScript+HTML to populate a dropdown menu but it is not working, am i doing anything wrong? Note I want the drop down menu to be filled on page Load
<!DOCTYPE html>
<html>
<head>
<script>
function addList(){
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
}
</script>
</head>
<body>
<select id="year" name="year"></select>
</body>
</html>
Since your script is in <head>, you need to wrap it in window.onload:
window.onload = function () {
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
};
You can also do it in this way
<body onload="addList()">
For higher performance, I recommend this:
var select = document.getElementById("year");
var options = [];
var option = document.createElement('option');
//for (var i = 2011; i >= 1900; --i)
for (var i = 1900; i < 2012; ++i)
{
//var data = '<option value="' + escapeHTML(i) +'">" + escapeHTML(i) + "</option>';
option.text = option.value = i;
options.push(option.outerHTML);
}
select.insertAdjacentHTML('beforeEnd', options.join('\n'));
This avoids a redraw after each appendChild, which speeds up the process considerably, especially for a larger number of options.
Optional for generating the string by hand:
function escapeHTML(str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
However, I would not use these kind of methods at all.
It seems crude. You best do this with a documentFragment:
var docfrag = document.createDocumentFragment();
for (var i = 1900; i < 2012; ++i)
{
docfrag.appendChild(new Option(i, i));
}
var select = document.getElementById("year");
select.appendChild(docfrag);
Try this
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = "New Value";
opt.value = "New Value";
// Add an Option object to Drop Down List Box
document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
}
<script />
The Value will append to the drop down list.
Try to use appendChild method:
select.appendChild(option);
i think you have only defined the function. you are not triggering it anywhere.
please do
window.onload = addList();
or trigger it on some other event
after its definition
see this fiddle

how to store value of multiselect listbox in javascript

I have one multiselect listbox in my HTMl.
I want to get values of selected items of listbox in javascript
My html code:
<select id="schools" size="5" multiple="multiple">
<option value="352">Byskovskolen</option>
<option value="355">Heldagsskolen Specialtilbud</option>
<option value="372">Plejecenter Solbakken</option>
</select>
My Javascript code:
function getData()
{
var allSchools = [];
var s = document.getElementById("schools");
alert("schools lenght " + s.options.length);
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var schoolid = s.options[i].value;
alert(s.options[i].value);
allSchools.push(schoolid);
}
}
}
Values can be seen alerted with alert box but not getting stored in variable.
How can I store it in variable.
It works fine if you comment/uncomment the right lines. Try this:
function getData() {
var allSchools = [];
var s = document.getElementById("schools");
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var schoolid = s.options[i].value;
allSchools.push(schoolid);
}
}
console.log(allSchools);
}
DEMO: http://jsfiddle.net/4qYht/1/
Uncommented one line (var schoolid) and added a print out for the allSchools variable.
function getData()
{
var allSchools = [];
var s = document.getElementById("schools");
alert("schools lenght " + s.options.length);
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var schoolid = s.options[i].value;
allSchools.push(schoolid);
}
}
console.log(allSchools);
}
uncomment the schoolid assignment line
var schoolid = s.options[i].value;
allSchools.push(schoolid);
or
use allSchools.push(s.options[i].value); instead of allSchools.push(schoolid);
You have commented out the main line ,which would store the value in a variable.
// var schoolid = s.options[i].value;
apart from that rest of your code is perfect.
here is the corrected code :
function getData()
{
var allSchools = [];
var s = document.getElementById("schools");
alert("schools lenght " + s.options.length);
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
// var schoolid = s.options[i].value;
alert(s.options[i].value);
allSchools.push(schoolid);
}
}
}
Happy coding:)

Categories

Resources