Dynamically added options to selectbox do not delete - javascript

I can't seem to quite figure this out.
My functions work as they should however, there is one discrepancy, when the option values are added dynamically from the input box, and I hit the delete key in the [list1] , they do not get removed. However, if the option values are added statically, then they delete just fine as they should. Any ideas?
I am really scratching my head with this one.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function add_refdoc() {
var x = document.getElementById("list1");
var option = document.createElement("option");
var input = document.getElementById('refdocs_input')
option.text = input.value
x.add(option,x.option)
x.selectedIndex = x.options.length - 1;
}
function del_refdoc(e) {
var evt = e ? e : event;
var sel = evt.target ? evt.target : evt.srcElement;
if(evt.keyCode && evt.keyCode == 46 || evt.which == 46) {
var val = sel.value;
var opts = sel.getElementsByTagName("option");
if(val != "") {
for(var i=0; i<opts.length; i++) {
if(val == opts[i].value)
sel.removeChild(opts[i]);
}
}
}
}
</script>
</head>
<body>
<input id="refdocs_input" type="text"/>
<input value="add" type="button" onclick="add_refdoc()"/>
<br>
<select onkeydown="del_refdoc(event)" style="width: 250px;" id="list1"></select>
<br><br>
<select onkeydown="del_refdoc(event)" style="width: 250px;" id="list2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</body>
</html>

It looks like it was the way the options values were being added
So I changed this code and it worked.
function add_refdoc() {
var s = document.getElementById('list1')
var t = document.getElementById('input1').value
s.options[s.options.length] = new Option(t, t)
}

Related

How to remove duplicate values coming from option tag

I have an Select tag with multiple options.On button click every selected option creates an li with innerText set to text value of the option. How would i make a function that i cant add the same element twice?
$(".btn").on("click", function () {
let selectedItems = $("#node-input-options option:selected");
selectedItems.each(function (i, el) {
// console.log(el, i);
let text = $(el).text();
let val = $(el).val();
var li = $("<li>").text(text).val(val).attr("title", val);
list.append(li);
li.on("dblclick", function () {
li.remove();
});
});
This is my code in jquery.
This is and example on fiddle => https://jsfiddle.net/nah062ck/11/
> You can use Jquery contains selector to check if a selected item already exists in the list.
$("#b1").on("click", function() {
var selectedItems = $("#cars option:selected");
let list = $(".list");
selectedItems.each(function(i,el) {
var text = $(el).text();
var val = $(el).val();
var li = $("<li>").text(text).val(val).attr('title', val).attr("size",10);
li.size = 10;
var exists=$('.list li:contains('+text+')');
if(exists.length > 0){
alert('The Selected Word already exists');
return
}
list.append(li);
});
});
$("#b1").on("click", function() {
var selectedItems = $("#cars option:selected");
let list = $(".list");
selectedItems.each(function(i, el) {
var text = $(el).text();
var val = $(el).val();
var li = $("<li>").text(text).val(val).attr('title', val).attr("size", 10);
li.size = 10
let c = 0
if ($(".list li").length === 0) {
list.append(li)
// if list is empty fill it
} else {
$(".list li").each(function(i, el2) {
$(el2).text() == text ? c = "x" : null
// if not empty, check if text exists in list under each li
})
}
c === 0 ? list.append(li) : console.log(false)
// do according
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="7" name="cars" id="cars" multiple>
<option value="cup">Cupcake</option>
<option value="cupas">Cunut</option>
<option value="cup124">Eclair</option>
<option value="cup2512">Froyo</option>
<option>Gingerbread</option>
</select>
<button id="b1">Click me</button>
<ul class="list"></ul>
After you append to list you can disable and unselect using .prop({'disabled': true, selected:false})
Then in your remove process look for that same option and enable it again.
$("#b1").on("click", function() {
var selectedItems = $("#cars option:selected");
let list = $(".list");
selectedItems.each(function(i, el) {
var text = $(el).text();
var val = $(el).val();
var li = $("<li>").text(text).attr('title', val);
list.append(li);
}).prop({disabled: true, selected: false});
});
$('.list').on('dblclick', 'li', function() {
const $li = $(this),
title = $li.attr('title');
$("#cars option[value='" + title + "']").prop('disabled', false)
$li.remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="7" name="cars" id="cars" multiple>
<option value="cup">Cupcake</option>
<option value="cupas">Cunut</option>
<option value="cup124">Eclair</option>
<option value="cup2512">Froyo</option>
<option>Gingerbread</option>
</select>
<button id="b1">Click me</button>
<ul class="list"></ul>
let addEl = document.getElementById("add-country");
let containerList = document.getElementById("country-list");
let countries = [];
addEl.onclick = function(e) {
e.preventDefault();
let selectEl = document.getElementById("country").value;
if (!(countries.includes(selectEl))) {
countries.push(selectEl);
let createElLi = document.createElement("LI");
createElLi.innerHTML = selectEl;
containerList.appendChild(createElLi);
}
}
<form method="get" accept-charset="utf-8">
<select name="country" id="country">
<option>Japan</option>
<option>USA</option>
<option>India</option>
<option>Bangladesh</option>
<option>Canada</option>
<option>Pakistan</option>
</select>
<input type="submit" value="Add" id="add-country">
</form>
<ul id="country-list"></ul>
Code :
<html>
<head>
<title>Remove Duplicate Options</title>
</head>
<body>
<select id='mylist'>
<option value='php'>PHP</option>
<option value='css'>CSS</option>
<option value='php'>PHP</option>
<option value='sql'>SQL</option>
<option value='js'>JS</option>
<option value='css'>CSS</option>
<option value='js'>JS</option>
</select>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>
<script>
function removeduplicate()
{
var mycode = {};
$("select[id='mylist'] > option").each(function () {
if(mycode[this.text]) {
$(this).remove();
} else {
mycode[this.text] = this.value;
}
});
}
</script>
<button onClick='removeduplicate()'>Remove Duplicate</button>
</body>
</html
Reference : Narendra Dwivedi - Remove Duplicate DropDown Option

get multiple var in a function by find()

I am trying to create a calculation with two selected option and input. Like when you select 'a' and 'd' then input=1 it give result 75. I wrote a jquery code but it doesn't work . I can't find any error on console .Please check it below :
$(window).load(function(){
function doStuff() {
var uone= $("#ud").children(":selected").attr("id") == 'a';
var utwo= $("#ud").children(":selected").attr("id") == 'b';
var uthree= $("#ud").children(":selected").attr("id") == 'c';
var bone= $("#bt").children(":selected").attr("id") == 'd';
var btwo= $("#bt").children(":selected").attr("id") == 'e';
var getvalue;
if ($(uone).find(bone)) {
getvalue = 75;
}
if ($(uone).find(btwo)) {
getvalue = 70;
}
if ($(utwo).find(bone)) {
getvalue = 81;
}
if ($(uthree).find(bone)) {
getvalue = 79;
}
var shw = $('#inputamount').val();
var total = getvalue * shw ;
$("#totalop").html(total);
}
$("#inputamount").on('keyup', doStuff);
$("#ud").on('change', doStuff);
$("#bt").on('change', doStuff);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<select name="sucompn" id="ud">
<option id="a">a</option>
<option id="b">b</option>
<option id="c">c</option>
</select>
<select name="ducompn" id="bt">
<option id="d">d</option>
<option id="e">e</option>
</select>
<input autocomplete="off" name="inputamount" id="inputamount" value="" type="text">
<span id="totalop"></span>
don't use id use value for the options
<select name="sucompn" id="ud">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<select name="ducompn" id="bt">
<option value="d">d</option>
<option value="e">e</option>
</select>
then you can get the values like
var selectedUd = $("#ud").val();
var selectedBt = $("#bt").val();
then you can do:
var uone = selectedUd== 'a';
var utwo = selectedUd == 'b';
var uthree = selectedUd == 'c';
var bone =selectedBt == 'd';
var btwo =selectedBt== 'e';
then (I don't really know what you wanted to do here ) but you could do things like
var getValue;
if(uone && bone) getvALUE =75;
else if(uone && btwo) getValue = 70;
else if(utwo && bone) getValue = 81;
...here rthe rest of posibilities
var shw = $('#inputamount').val();
var total = getvalue * shw;
$("#totalop").html(total);
Here is the Plunker - Sample
You have defined var getValue;, but use in code another variable getvalue = 75;(getValue and getvalue are not the same). Probably you have undefined variable and this problem usually yields no console info.

Change visibility of div when option is changed inside dropbox

I got codes like this inside my php:
<section id="placeOrder">
<h2>Place order</h2>
Your details
Customer Type:
<select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
and these are the divs of which visibility has to be changed according to the selected option:
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename" id="forename" />
Surname <input type="text" name="surname" id="surname" />
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName" id="companyName" />
</div>
I tried this javascript:
<script>
document.getElementsByName("customerType").onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
};
</script>
But div tradecustdetails" does not appear and div retCustDetails is still on there.
Can anyone help?
getElementsByName() returns a collection of all elements in the document with the specified name. Hence you have to loop through them like this:
var x = document.getElementsByName("customerType");
for (var i = 0; i < x.length; i++) {
// do something with x[i]
}
If you are using only one select element, then it is better to use getElementById() like this:
HTML
<select id="customerType" name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
Script
document.getElementById("customerType").onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
};
Updated your script, this should work.
<script>
function jsFunction() {
var val = document.getElementById("dropSelect").options[document.getElementById("dropSelect").selectedIndex].value;
document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
}
</script>
Update your dropdown HTML as well.
<select id="dropSelect" name="customerType" onchange="jsFunction()">
EDIT #1: using getElementsByName()
function jsFunction() {
var val = document.getElementsByName("customerType")[0];
val = val.options[val.selectedIndex].value;
document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
}

Creating multiple Select options from an Object

Im stack on creating multiple select options
I have an Object with multi objects inside and want create select options in condition of the previous select option , i provide js fiddle for better understanding .
my objectif is
first select category ----(then)---> select sex -----(then)---> select kind---(then)-->then select size
by this order from that Object.
i could do the select sex and it works but not kind and size.
this is my html
<form name="myform">
<div>
<select name="category_group" id="category_group" >
<option value="0">choose category</option>
<option value='401' > clothes </option>
<option value='403' > shoes </option>
</select>
</div>
<br>
<div>
<select id="clothing_sex" name="clothing_sex" onChange="showclothesKind(this.value,this.form.clothing_kind)">
<option value="0">choose Type»</option>
</select>
<select id="clothing_kind" name="clothing_kind">
<option value="0">choose clothes</option>
</select>
<select id="clothing_size" name="clothing_size">
<option value="0">choose size</option>
</select>
</div>
</form>
and js in the fiddle.
much appreciate your help.
This was kind of fun to play around with. Thanks for posting. I used the following:
var optionTemplate = "<option class='newOption'>sampleText</option>";
$(document).ready(function() {
var removeFromNextSelects = function(firstSelector) {
var selNum = sels.indexOf(firstSelector);
for (var i = selNum; i < sels.length; i++)
{
$(sels[i]).find('.option').remove();
}
};
var populateNextSelect = function(neededObject, targetSelector) {
removeFromNextSelects(targetSelector);
for (var key in neededObject)
{
var name;
neededObject[key].name ? name = neededObject[key].name : name = neededObject[key];
$(targetSelector).append(optionTemplate);
$('.newOption').val(key).html(name).removeClass('newOption').addClass('option');
}
};
var obj1 = {}, obj2 = {}, obj3 = {};
var sels = ["#clothing_sex", "#clothing_kind", "#clothing_size"];
$('#category_group').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[0]);
return;
}
obj1 = {};
var selection = $(this).val();
obj1 = clothes[selection];
populateNextSelect(obj1, sels[0]);
});
$('#clothing_sex').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[1]);
return;
}
obj2 = {};
var selection = $(this).val();
obj2 = obj1[selection].types;
populateNextSelect(obj2, sels[1]);
});
$('#clothing_kind').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[2]);
return;
}
obj3 = {};
var selection = $(this).val();
var arr = obj2[selection].sizes;
for (var i = 0; i < arr.length; i++)
{
obj3[Object.keys(arr[i])[0]] = arr[i][Object.keys(arr[i])[0]];
}
populateNextSelect(obj3, sels[2]);
});
});
Here's the fiddle

Filtering through multiple times in javascript

So, I have an object named products that has 3 attributes:
var products = [
{"name":"product1","size":"large","color":"blue","gender":"male"},
{"name":"product2","size":"small","color":"pink","gender":"female"},
{"name":"product3","size":"large","color":"green","gender":"male"},
{"name":"product4","size":"large","color":"yellow","gender":"female"},
{"name":"product5","size":"medium","color":"blue","gender":"female"},
{"name":"product6","size":"large","color":"green","gender":"male"},
{"name":"product7","size":"small","color":"yellow","gender":"male"},
{"name":"product8","size":"medium","color":"red","gender":"female"},
{"name":"product9","size":"large","color":"blue","gender":"male"},
{"name":"product10","size":"small","color":"red","gender":"female"}
];
So, if I have 3 select boxes for size, color, and gender, how would I filter these 3 to get the product name?
I'm trying to use .filter in javascript. I know how to use it in non-associative arrays. But, what about associative arrays? how do you use them?
var color = document.getElementById("color").value;
var gender = document.getElementById("gender").value;
var size = document.getElementById("size").value;
var matched = products.filter(function(e) {
return (e.color == color && e.gender == gender && e.size == size);
}).map(function(e) { return e.name; });
I wrote a JSfiddle to go with this answer. Check it out here: http://jsfiddle.net/THEtheChad/XjGPt/
JQuery
$('input').change(function(){
var names = filter();
});
function filter(){
var selected = {
size: $('#size') .val(),
color: $('#color') .val(),
gender: $('#gender').val()
};
var matches = products.filter(function(product){
return product.size == selected.size &&
product.color == selected.color &&
product.gender == selected.gender;
});
return matches.map(function(product){ return product.name });
}
Vanilla JS
var d = document;
var inputs = d.getElementsByTagName('input');
// Convert to array
inputs = Array.prototype.slice.call(inputs);
inputs.forEach(function(input){
input.addEventListener('change', function(e){
var names = filter();
});
});
function filter(){
var selected = {
size: d.getElementById('size') .value,
color: d.getElementById('color') .value,
gender: d.getElementById('gender').value
};
var matches = products.filter(function(product){
return product.size == selected.size &&
product.color == selected.color &&
product.gender == selected.gender;
});
return matches.map(function(product){ return product.name });
}
Not as elegant as Barmar's code, I implemented 2 out of the 3 dropboxes and left a bit of work for you as well ;)
<html>
<head>
<script>
var products = [
{"name":"product1","size":"large","color":"blue","gender":"male"},
{"name":"product2","size":"small","color":"pink","gender":"female"},
{"name":"product3","size":"large","color":"green","gender":"male"},
{"name":"product4","size":"large","color":"yellow","gender":"female"},
{"name":"product5","size":"medium","color":"blue","gender":"female"},
{"name":"product6","size":"large","color":"green","gender":"male"},
{"name":"product7","size":"small","color":"yellow","gender":"male"},
{"name":"product8","size":"medium","color":"red","gender":"female"},
{"name":"product9","size":"large","color":"blue","gender":"male"},
{"name":"product10","size":"small","color":"red","gender":"female"}
];
function checkValidOption(){
var color_chosen = document.getElementById("color").value;
var size_chosen = document.getElementById("size").value;
var result = "";
//only if both options were chosen
if (color_chosen !== "empty" && size_chosen != "empty"){
for(var i=0; i<products.length; i++){
if(products[i].size == size_chosen && products[i].color == color_chosen){
result = products[i].name;
break;
}
}
document.getElementById('result').innerHTML = result;
}
}
</script>
</head>
<body>
<div id="wrapper">
<select id="size" name="size" onchange="checkValidOption();">
<option value="empty"/>
<option value="small">small</option>
<option value="medium">medium</option>
<option value="large">large</option>
</select>
<select id="color" name="color" onchange="checkValidOption();">
<option value="empty"/>
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<option value="green">green</option>
<option value="pink">pink</option>
</select>
</div><!--wrapper-->
<div id="result"></div>
</body>
</html>

Categories

Resources