Modify code to check for duplicate entries in select box - javascript

I have the below, it dynamically adds a new value option into a selectbox. The problem i have is that it does not check for duplicate entries before adding new options into the select box.
Is there a way i can make a change to my code so it will alert the user that a duplicate entry is found and to stop adding the same option value?
function refadd() {
var val = document.getElementById('docsref').value
if (val != "") {
var select = document.getElementById('docsref_list');
var option = document.createElement('option');
option.text = value
select.add(option,select.option)
select.selectedIndex = select.options.length - 1;
}
}

Best is to loop through all existing options and check if you had a match.
The loop would be added so it appears BEFORE your IF condition.
If a match is found you could notify the user (e.g. alert ) and then execute a "return" statement.
Something like the below:
function refadd()
{
var value = document.getElementById('docsref').value
if (value != "")
{
var select = document.getElementById('docsref_list');
var option = document.createElement('option');
var flag = 0;
for(var i = 0; i < select.length; i++)
{
if(select[i].value == value)
{
flag = 1;
}
}
if(flag == 1)
{
alert('Value is duplicate.');
}
else
{
option.text = value;
select.add(option,select.option);
select.selectedIndex = select.options.length - 1;
}
}
}
If your HTML is like:
<div>
<input type = "text" name = "docsref" id = "docsref" style = "width:100px;"/>
<input type = "button" name = "addValues" id = "addValues" value = "AddValues" onClick = "refadd();"/>
</br>
<select id = "docsref_list">
<option value = "1">1</option>
<option value = "2">2</option>
</select>
</div>
Hope that helps

using jQuery...
function refadd() {
var val = $("#docsref").val();
if (val != "") {
for(var i = 0; i < select.length; i++)
{
if(select[i].value == value)
{
alert("can't add.");
return false;
}
}
var ob = new Option("option text", "value");
$(ob).html("option text");
$("#selectList").append(ob);
}
}

Related

How to update options of select but keep previously selected one as selected?

Here's my try on implementing this:
var select = document.getElementById(key);
var temp = select.value;
select.options.length = 0; // clear out existing items
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data.Value, data.Key))
}
select.value = temp;
In case of there is no such value anymore I would like to set some default values for selcted option.
This is a simple function called init_select
It clear the selection tag
-remembers the option that was previously selected
if the item that was previously selected item is not in the list of new options..it will select the option that you want (this is the default_opt) parameter
-if the previously item is IN the list it will ignore the default_opt paramater and use the previously selected item.
demo here (previously selected item NOT in list but default_opt is IN list)
function init_select(id,data,default_opt) {
var select = document.getElementById(id);
var temp = select.value;
select.innerHTML="";
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data[i]))
}
if (data.indexOf(temp) < 0 && data.indexOf(default_opt)>=0 ) {
select.value = default_opt;
console.log('this is select',select.value,default_opt,select);
} else if (data.indexOf(temp) >= 0){
//select.options.add(new Option(temp));
select.value = temp;
console.log(select.value,data.indexOf(temp));
}
}
init_select('key',["New Value", "New Value2", "New Value3", "New Value4"],"New Value2")
<select id="key">
<option>year1</option>
<option>year2</option>
<option>year3</option>
</select>
demo here (previously selected item IN list and default_opt is IN list, default options is ignored and the previously selected item is selected)
function init_select(id,data,default_opt) {
var select = document.getElementById(id);
var temp = select.value;
select.innerHTML="";
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data[i]))
}
if (data.indexOf(temp) < 0 && data.indexOf(default_opt)>=0 ) {
select.value = default_opt;
console.log('this is select',select.value,default_opt,select);
} else if (data.indexOf(temp) >= 0){
//select.options.add(new Option(temp));
select.value = temp;
console.log(select.value,data.indexOf(temp));
}
}
init_select('key',["New Value", "New Value2", "New Value3", "New Value4","year1"],"New Value2")
<select id="key">
<option>year1</option>
<option>year2</option>
<option>year3</option>
</select>
Your idea of getting the value of select and resetting it was right. You can achieve your wanted result with jQuery like this.
Note that if the old value is not available, select's value will be set to null.
$("button").on("click", function() {
var def = "4. Option";
var temp = $("select").val();
var select = $("select");
select.empty();
for (i = 2; i <= 10; i++) {
$("<option>").text(i + ". Option").appendTo(select);
}
select.val(temp);
if (select.val() == null)
select.val(def);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>1. Option</option>
<option>2. Option</option>
<option>3. Option</option>
<option>4. Option</option>
<option>5. Option</option>
</select>
<button>Clear and Fill Select</button>

How to display JSON objects as options of a dropdown in HTML, using a common JavaScript funciton for all objects

I have two sets of data in a JSON file (ACodes and BCodes), which I want to read and display as the options of two different dropdowns in an HTML file. I want to have one common JavaScript function that I can use to get along with the same (shown below) but I am not getting the desired output.
Help about where I am going wrong is much appreciated!
HTML
<script>
var select, option, arr, i;
function loadJSON(var x){
if(x.match == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x.match == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload="loadJSON('A');laodJSON('B')">
<select id="dd1"></select>
<select id="dd2"></select>
</body>
JSON
ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
remove var at loadJSON(var x) => loadJSON(x)
remove .match at x.match == "A", you seems to want to compare x with specific value, not testing it as regexp, so change to x === "A"
laodJSON('B'); at body onload is typo.
There's some reusable codes, you can attract the value depends on x and make the code shorter. This step is not a must do, as it won't cause your origin code unable to work.
<body onload=" loadJSON('A');loadJSON('B');">
<select id="dd1"></select>
<select id="dd2"></select>
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
var array, select, target;
if (x === 'A') {
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
target = 'Code';
} else if (x === 'B') {
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
target = 'Curr';
}
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i][target];
select.add(option);
}
}
</script>
</body>
Edit: to create it more dynamically, you can make the function accept more params, so you can have more control over it. Demo is on jsfiddle.
// Append options to exist select
function loadJSON(jsonObj, key, selectId) {
var arr = JSON.parse(jsonObj);
// Get by Id
var select = document.querySelector('select#' + selectId);
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
}
// Append select with id to target.
function loadJSON2(jsonObj, key, selectId, appendTarget) {
// Get the target to append
appendTarget = appendTarget ? document.querySelector(appendTarget) : document.body;
var arr = JSON.parse(jsonObj);
// Create select and set id.
var select = document.createElement('select');
if (selectId != null) {
select.id = selectId;
}
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
appendTarget.appendChild(select);
}
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
if(x == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload='loadJSON("A");loadJSON("B")'>
<select id="dd1"></select>
<select id="dd2"></select>
</body>
Now this code will work.
The match() method searches a string for a match against a regular expression. So match() function will not work here. You have to use equal operator for get this done.
I hope, This will help you.
You were well on your way, you just need to make it more dynamic :)
function loadOptions(json) {
json = JSON.parse(json);
var select = document.createElement('select'), option;
for (var i = 0; i < json.length; i++) {
for (var u in json[i]) {
if (json[i].hasOwnProperty(u)) {
option = document.createElement('option');
option.text = json[i][u];
select.add(option);
break;
}
}
}
return select;
}
And to use it:
document.body.appendChild(loadOptions(ACodes));
document.body.appendChild(loadOptions(BCodes));
FIDDLE
http://jsfiddle.net/owgt1v2w/
The answers above will help you, but im strongly recommend you to check some javascript's frameworks that can help you with that kind of situation.. The one im using is knockout.js (http://knockoutjs.com/)
Take a look in the documentation, also there a lot of topics related in stackoverflow http://knockoutjs.com/documentation/options-binding.html
Regards!

Change variable value when option is selected, return previous value when not selected anymore

I need to update the value of a variable (which I called "tot" in the example) according to what option of a dropdown menu is selected. If I select option 1 or 2 tot must be increased of 10, if I select option 3 variable "tot" must NOT be increased. If i select option 1, and then I change my mind and select option 3 the value of Tot must be restored.
Here's the html of the select
<select name='hello' id='hello'>
<option>Select an option...</option>
<option id='one'>One</option>
<option id='two'>Two</option>
<option id='three'>Three</option>
</select>
And here's the jquery script I wrote. I guess I didn't understand the functioning of .change function, because it doesn't work as I expected.
var extra = 0;
var tot = 0;
$(document).ready(function () {
$('#hello').change(function(){
if($('#one').is(':selected')) {
extra = 10;
}
else if($('#two').is(':selected')) {
extra = 10;
}
else if($('#three').is(':selected')) {
extra = 0;
}
tot = tot + extra;
});
});
Or (if I've understood what you're after correctly)....
var tot = 120; //some number picked at random
var helloed = false; // flag for whether incremented
$(document).ready(function(){
$("#hello").change(function(){
var sel = $(this).find(":selected").attr("id")
if (sel == "one" || sel =="two" ) {
if (!helloed) {
tot += 10;
helloed = true;
}
} else { // 'three' selected
if (helloed) {
tot -= 10;
helloed = false;
}
}
alert ("Tot is now " + tot);
});
});
If there were more options I'd go for a switch rather than an IF but that will do for this example
var extra = 0;
var tot = 0;
var initialTot = tot;
$(document).ready(function () {
var previous = 0;
var selected = 0;
$('#hello').change(function(){
if($('#one').is(':selected')) {
previous = selected;
selected = 1;
extra = 10;
}
else if($('#two').is(':selected')) {
previous = selected;
selected = 2;
extra = 10;
}
else if($('#three').is(':selected')) {
previous = selected;
selected = 3;
extra = 0;
}
tot = tot + extra;
if(previous === 1 && selected === 3) {
tot = initialTot;
}
});
});

How to retain a selected value in dynamically generated dropdown box to the next jsp page?

I have a drop down box where the options are coming from the configured properties file.The options are generated on load of the page.I have used the following code.
In JSP
<select name="IDNo" id="IDNo">
</select>
function loading()
{
var d = document.getElementById("system");
var df=document.getElementById("IDNo");
var i = 0;
var disp = document.getElementById("Range");
var numberOfOptions = df.options.length;
for (i = 0; i < numberOfOptions; i++) {
df.remove(0);
}
if (d.value == "Apple") {
df.options[df.options.length] = new Option("ALL","");
for(i=1;i<=disp.value;i++)
{
var option = document.createElement("option");
option.text=i;
option.value=i;
df.add(option, df.options[null]);
}
}
Add something like the following at the end of the code:
<c:if test="${!empty param.IDNo}">
for (var i = 0; i < df.options.length; i++) {
if (df.options[i].value == '${param.IDNo}') {
df.selectedIndex = i;
break;
}
}
</c:if>
Use the simple java script function to set selected value of combo or drop down box in the other page
function setSelected()
{
var Num = "<%=NumID%>";
if(Num != null && Num !='' )
{
var secondCombo = document.getElementById("combo_id");
secondCombo.value = Num;
}
}

Setting One Drop Down after Selecting from Another

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;
}
}

Categories