Javascript find missing select value - javascript

I have the following JavaScript:
var next_user = "1";
i=0;
for (i=0;i<=10;i++)
{
var el = document.getElementById("user_list");
var val = el[i].value;
if (val <= next_user)
{
next_user = i;
}
if (val >= next_user)
{
next_user = i;
}
alert(next_user);
}
and I have following Select box on the screen:
<select id="user_list" onclick="load_user(this)" name="user_list" size="21" style="width:200px;">
<option value="1">Bob</option>
<option value="2">john</option>
<option value="3">Frank</option>
<option value="5">tom</option>
</select>
I can't seem to get it working the way I want it to.
The select box could have 10 users in the list and each of the (options) values are unique (1-10).
as you can see in my select box I am missing value 4. My Javascript code from above is meant to go though the select box and find the first value that is missing. (in my above example, it should reply back with 4 as that is missing) but If Bob is missing then it should reply back with 1.
Well that's what my JavaScript code above should be doing but I can't seem to work out what I am doing wrong. (well I hope I am doing it correct)
does anyone know what I am doing wrong?
(I am not plaining to use any jQuery at this stage)

You should use options property of that select element you extracted.
Example:
<script>
var userList = document.getElementById("user_list");
for (var i=0;i<userList.options.length; i++) {
if (userList.options[i].value != (i+1)) {
alert((i+1)+" is missing");
break;
}
}
</script>

You can use the following code to alert the missing Option
var next_user = 1;
var el = document.getElementById("user_list");
for (i = 0; i < 10; i++) {
var val = parseInt(el[i].value);
if (val > next_user) {
alert(next_user);
break;
} else {
next_user++;
}
}​
Demo: http://jsfiddle.net/joycse06/75kM7/

Related

How do I get the id of a element in a form?

I need to get the id of an element within a form so I can tag the element as "false" or "true". Or, alternately, I need a way to associate a name with an element that can I pull in javascipt so I can change the associated value.
var form = document.getElementById("myForm");
form.elements[i].value
Those lines of code is what I tried but it doesn't seem to work.
Edit:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm").elements;
for(var i = 0; i < 1 ; i++){
var id = form.elements[i].id;
sessionStorage.setItem(id,"false");
}
localStorage.setItem("run", true);
}
}
So basically when I run the page, I want a localStorage item attached to all the buttons on the screen. I want this to run once so I can set all the items to false. Problem is I don't know how to get the ids so I have a value to attach to the button. Any idea of how to accomplish a task like this.
Edit2:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm");
var tot = document.getElementById("myForm").length;
for(var i = 0; i < tot ; i++){
sessionStorage.setItem(form.elements[i].id,"false");
}
localStorage.setItem("run", true);
}
}
This is the new code. It mostly seems to work but for some reason only the first value is getting set to false. Or maybe it has to do with this function, I'm not sure.
function loader(){
var form = document.getElementById("myForm");
var tot = 5;
for(var i = 0; i < 5 ; i++){
if(sessionStorage.getItem(form.elements[i].id) === "true"){
document.getElementById(form.elements[i].id).style.backgroundColor = "green";
return ;
}else{
document.getElementById(form.elements[i].id).style.backgroundColor = "red";
return false;
}
}
}
Anyways, I'm running both of these at the same time when the page is executed so they are all set to false and turn red. But when a button is properly completed, the color of the button turns green.
It's available via the id property on the element:
var id = form.elements[i].id;
More on MDN and in the spec.
Live Example:
var form = document.getElementById("myForm");
console.log("The id is: " + form.elements[0].id);
<form id="myForm">
<input type="text" id="theText">
</form>
You're already storing all the elements in the form so it must be :
var form = document.getElementById("myForm").elements;
var id = form[i].id;
Or remove the elements part from the form variable like :
var form = document.getElementById("myForm");
var id = form.elements[i].id;

How to handle multiple select tags using jQuery?

I have 4 drop down options that are select tag. When I select an option from the first drop down menu, some divs will hide. The problem is that if I select an option from the second drop down, other divs will hide based only on the second rule. But I also want to respect the first rule.
For example. I have a repetitive div for each project in my DB. First drop down has 3 option for severity. Minor, medium and major. If I choose Major, right now only the Major projects are shown and others are hidden. The second select tag filters the type of project. If I leave the first filter with Major, when I select an option for the second select, the divs will show/hide respecting only the second rule. But I want to combine the rules of the selects.
<select id="chooseSeverity">
<option>Choose Severity</option>
<%
for (int i = 0; i < countBySeverity.size(); i++) {
%>
<option value="<%=countBySeverityColumn.get(i)%>"><%=countBySeverityColumn.get(i)%></option>
<%
}
%>
</select> <select id="chooseType">
<option>Choose Type</option>
<%
for (int i = 0; i < countByType.size(); i++) {
%>
<option value="<%=countByTypeColumn.get(i)%>"><%=countByTypeColumn.get(i)%></option>
<%
}
%>
</select>
These are two of my four selects. And these are my jQuery rules.
$("#chooseSeverity").change(function(){
$(this).find("option:selected").each(function(){
var optionValue = $(this).attr("value");
if(optionValue){
var val = optionValue;
$(".status").each(function() {
var parent = $(this).parents('.style2'),
length = $(this).text().length > 0;
if (length && $(this).text().search(new RegExp(val, "i")) < 0) {
parent.fadeOut("slow");
} else {
parent.show();
}
});
}
else{
$(".status").each(function() {
var parent = $(this).parents('.style2');
parent.fadeIn("slow");
});
}
});
});
$("#chooseType").change(function(){
$(this).find("option:selected").each(function(){
var optionValue = $(this).attr("value");
if(optionValue){
var val = optionValue;
$(".savingType").each(function() {
var parent = $(this).parents('.style2'),
length = $(this).text().length > 0;
if (length && $(this).text().search(new RegExp(val, "i")) < 0) {
parent.fadeOut("slow");
} else {
parent.show();
}
});
}
else{
$(".savingType").each(function() {
var parent = $(this).parents('.style2');
parent.fadeIn("slow");
});
}
});
});
How to combine all the rules?
Thanks.
PS: Here is the minimal fiddle: https://jsfiddle.net/zjho75jp/1/
Getting Select List Values
var foo = [];
$('#multiple :selected').each(function(i, selected){
foo[i] = $(selected).text();
});

How do I set dropdown option selected by looking at MVC URL

Hello and thank you for making stackoverflow such a great resource for learning programmers like me. I've been reading lots of answers on here to help with my first MVC project, this is my first time asking.
Here is my dropdown HTML
<div class="dropdown">
<select id="assetSelect" onchange="location = this.options[this.selectedIndex].value;">
<option value="/History/Index/All">All Assets</option>
#foreach (var item in Model.NodeInfo)
{
<option value="/History/Index/#item.node.name">#item.node.name</option>
}
</select>
</div>
Once an item is selected from the dropdown, the url will look like this
http://web.site/History/Index/G0000106
Now I'm trying to grab that last part of the URL (in this case G0000106) and set the corresponding dropdown option to selected. Here is the javascript I have pieced together so far but it's not working.
$('#assetSelect').find('option').each(function () {
function getCurrentPageId() {
var params = window.location.href.split('/');
var i = params.length;
var pageId = params[i];
return pageId;
}
var currentPageId = getCurrentPageId();
var $this = $(this);
if ($this.text() == currentPageId) {
$this.attr('selected', 'selected');
return false;
}
});
Will this function work with the one that populates the dropdown list? Is this the best way or is there an HTML helper that can do it? Any help is appreciated, thanks!
Option 1. You can simplify your code significantly:
function getCurrentPageId() {
var params = window.location.href.split('/');
return params[params.length - 1];
}
var pageId = getCurrentPageId();
$('#assetSelect').find('option:contains(' + pageId + ')').prop('selected', true);
Anyway, your problem was in this line:
var i = params.length;
var pageId = params[i];
It should be params[i - 1], since you want to get the last array element.
Option 2. An even simpler approach which should also work for you is to use location.pathname:
$('#assetSelect').val(window.location.pathname);

How can I generate a list of links based on dropdown menu choices?

So I've got a bunch of information for a bunch of different countries, and I'm trying to get it sorted like so:
Dropdown menu to choose a country -> Dropdown menu to choose information type -> here's a link to that information
I'm not so great with javascript, but I found this solution that allows me to change the content of the second dropdown based on the selection chosen from the first dropdown:
<script type="text/javascript">
function configureDropDownLists(ddl1, ddl2) {
var albania = new Array('History', 'Legal Guides');
var andorra = new Array('Country Overview', 'Demographics', 'Legal Guides');
switch (ddl1.value) {
case 'Albania':
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < albania.length; i++) {
createOption(document.getElementById(ddl2), albania[i], albania[i]);
}
break;
case 'Andorra':
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < andorra.length; i++) {
createOption(document.getElementById(ddl2), andorra[i], andorra[i]);
}
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
</script>
And then the dropdown boxes, in the HTML:
<select id="ddl" onchange="configureDropDownLists(this,'ddl2')">
<option value=""></option>
<option value="Albania">Albania</option>
<option value="Andorra">Andorra</option>
</select>
<select id="ddl2">
</select>
So now I'm wondering how I can take that secondary choice and use it to generate a list of links for someone to choose from--say, within a new paragraph of text or something.
First time asking a question here, sorry if confusing.
First add somewhere this link list could go.
I'd put it in a unordered list (<ul></ul>). But you could just as well put it in a paragraph or a div.
I assume you know about objects and the for / in loop.
If not, this should help you get it:
https://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/
Here is the code I made for you. I have commented it along the way.
Just ask if something is unclear :)
Albania
Andorra
<select id="ddl2" onchange="configureDropDownLists('ddl2')">
</select>
<ul id='linkList'></ul>
<script type="text/javascript">
function configureDropDownLists(ddlBeingChanged) {
var ddl = document.getElementById('ddlBeingChanged');
var ddl1ChosenValue=document.getElementById('ddl1').value;
var linkLists = {
albania: {
"history": ['http://albania.example.com/history', 'http://albania.example.com/historyTwo'],
"legal guides": ['http://albania.example.com/guide', 'http://albania.example.com/guideTwo'],
},
andorra: {
"country overview": ['http://andorra.example.com/country', 'http://andorra.example.com/overview'],
"demographics": ['http://andorra.example.com/demographics', 'http://andorra.example.com/demographicsTwo'],
"legal guides": ['http://andorra.example.com/guide', 'http://andorra.example.com/guideTwo'],
}
};
if (ddlBeingChanged == "ddl1") {
console.log(ddl1ChosenValue);
for (var ddl2 in linkLists[ddl1ChosenValue]){
console.log(ddl2);
// Here the ddl2 variable will contain the first level of the object 'linkLists'. I.E. the country names.
createOption(document.getElementById('ddl2'), ddl2, ddl2);
}
} else if (ddlBeingChanged == "ddl2") {
var ddl2ChosenValue=document.getElementById('ddl2').value;
var linkArray=linkLists[ddl1ChosenValue][ddl2ChosenValue];
// The linkArray:
// Let's say someone chose andorra and demographics
// then linkLists[ddl1ChosenValue][ddl2ChosenValue] would be equivalent to linkLists.andorra.demographics
var linkListHTML="";
for (var i in linkArray){
var URL=linkArray[i];
linkListHTML+="<li><a href='"+URL+"'>"+URL+"</a></li>";
}
document.getElementById('linkList').innerHTML=linkListHTML;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
</script>
Edit: Fixed code bugs

Improve Dynamic Dropdown Solution

I've created a dynamic dropdown list with jQuery and JavaScript. I'm hoping someone can take a look and let me know if this is an appropriate way to handle this type of task. I'm specifically curious to know if this code is scalable, and will it perform well? Next, would it be suggested to use a switch statement instead of several if statements in the JavaScript I have below? If so, why? I'd like to store this to be reused anytime I implement a solution like this, but as I'm new to JavaScript I don't completely trust my work yet.
JSFIDDLE: http://jsfiddle.net/6vrpF/
HTML:
<select id='parent'>
<option value='test'>test</option>
<option value='sure'>sure</option>
<option value='cool'>cool</option>
<option value='best'>best</option>
</select>
<select id='child'>
</select>
JavaScript:
function newDropdown()
{
var html = ""
for(i=0; i<arguments.length; i++)
{
html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val()
if(selection == 'test') {newDropdown('a','b','c')}
if(selection == 'sure') {newDropdown('d','e','f')}
if(selection == 'cool') {newDropdown('g','h','i')}
if(selection == 'best') {newDropdown('j','k','l')}
});
updated the fiddle
http://jsfiddle.net/6vrpF/4/
var parentChild = {
"test" :['a','b','c'],
"sure" :['d','e','f'],
"cool" :['g','h','i'],
"best" :['j','k','l']
};
function newDropdown()
{
var html = ""
for(i=0; i<arguments.length; i++)
{
html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val();
newDropdown( parentChild[selection].join(",") );
});
You need to get your data in the JSON format as mentioned/defined above
Edit: this is the updated fiddle which will give options one by one
http://jsfiddle.net/6vrpF/6/
var parentChild = {
"test" :['a','b','c'],
"sure" :['d','e','f'],
"cool" :['g','h','i'],
"best" :['j','k','l']
};
function newDropdown()
{
var array = arguments[0];
var html = ""
for(i=0; i<array.length; i++)
{
html += "<option value='"+array[i]+"'>"+array[i]+"</option>"
}
$("#child").append(html)
}
$("#parent").on("change",function(){
$('#child').text("")
var selection = $("#parent").val();
newDropdown( parentChild[selection] );
});

Categories

Resources