I am having some problems with finding out if the value is missing or not.
I have the following select box on my screen:
<select id="user_list" onclick="load_user(this)" name="user_list" size="21" style="width:200px;">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="4">Item4</option>
</select>
I am using the following JavaScript:
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;
}
else
{
alert((userList.options.length+1)+" is missing");
break;
}
}
The problem I am facing is that if option values 1,2,3,4 are there is replys back with 5 (as that is the next number) which is fine as that is what I want.
If I remove option 3 (like in my select box above) it keeps replying with 4 is missing when it should say 3 is missing.
If i remove the following code:
else
{
alert((userList.options.length+1)+" is missing");
break;
}
it does what I want it to do, but it doesn't get the next value number after checking all values (so it stops after reading the last option in the list).
What it should do is go though all the options in the select box and if one of the values is missing it should alart the one that is missing. If all value numbers are there then it should alart the next available option that is missing.
Can anyone see what I am doing wrong?
It keeps telling you that 4 is missing because you are running the else code in every iteration of the loop (until it finds one that is missing). The code in your else should only be ran once. You can use a flag variable to set if one is missing and check after the loop. Try changing the js code to
var allFound = true;
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");
allFound = false;
break;
}
}
if(allFound)
alert((userList.options.length+1)+" is missing");
This works on Jfiddle http://jsfiddle.net/Vt2DJ/
var userList = document.getElementById("user_list");
var whileindex = 0; //keeps track of the number of options checked
var i = 0; //values that should be available for the options
while ( whileindex < userList.options.length )
{
if (userList.options[i].value != (i+1)) {
alert((i+1)+" is missing");
i++; //this because otherwise we have a wrong offset for the check
}
else
{
whileindex++; //option exists
}
i++; //go on to the next value
}
Related
I have 3 columns of HTML selection fields which need to load otions dependent on the previous selection fields.
Selection in column 2 values will be dependant on selected value in column 1 selection. I have this raw JavaScript below which add 2 selection options to a an HTML select filed and then removes 2 based on the select value in selection 1.
My problem is that the part that removes the 2 selection field options is not removing both options but instead removes 1 of them.
Demo: http://jsfiddle.net/jasondavis/croh2nj8/3/
I realize some of this uses jQuery but the goal is to use raw JS without jQuery for this part in question....
$(document).ready(function() {
$("#action").change(function() {
var el = $(this) ;
var selectAttributeEl = document.getElementById('action-attribute');
if(el.val() === "form" ) {
var option = document.createElement('option');
option.text = 'Name';
var option2 = document.createElement('option');
option2.text = 'ActionURL';
selectAttributeEl.add(option);
selectAttributeEl.add(option2);
}else if(el.val() === "link" ) {
for (var i=0; i<selectAttributeEl.length; i++){
if (selectAttributeEl.options[i].value == 'Name'){
selectAttributeEl.remove(i);
}else if(selectAttributeEl.options[i].value == 'ActionURL'){
selectAttributeEl.remove(i);
}
}
}
});
});
The problem is in the for loop where you loop through the selectobject.options. When the first if condition is true, you mutate selectobject.options by removing the Name option. On the next iteration of the loop selectobject.options[i] now returns undefined.
Let's walk through the for loop to demonstrate:
i is 0, corresponding to option ID, nothing happens.
i is 1, corresponding to option Class, nothing happens.
i is 2, corresponding to option Name, the if statement is valid and it removes the Name option. Now selectobject.options has length of 3.
i is 3, which corresponds to undefined. That is, selectobject.options[3] is undefined since the previous iteration of the loop removed an item from selectobject.options.
One possible solution, in the if and else statements you could reset i back one, with i--. Here's an updated jsFiddle. Another option is too loop through selectobject.options backwards, as mutating the latter items won't effect the counter as it moves to the former items.
There are other ways to correct this as well, like creating a new options array based on the values you want to keep in the options, then loading it the new options into the select.
As I stated, you're getting the issue, very simply, because the for loop is started from index 0 and working your way up. When you remove an element, you remove it from the NodeList of options. Easiest way I know of is to start from the end of the node list and work your way to node number 0.
$(document).ready(function() {
$("#action").change(function() {
var el = $(this);
if (el.val() === "form") {
//$("#action-attribute").append(' <option value="Name">Name</option>');
//$("#action-attribute").append(' <option value="ActionURL">ActionURL</option>');
var x = document.getElementById('action-attribute');
var option = document.createElement('option');
option.text = 'Name';
var option2 = document.createElement('option');
option2.text = 'ActionURL';
x.add(option);
x.add(option2);
} else if (el.val() === "link") {
//$("#action-attribute option:last-child").remove() ;
var selectobject = document.getElementById("action-attribute");
var remove_array = ['Name', 'ActionURL'];
for (var i = selectobject.options.length - 1; i >= 0; i--) {
if (remove_array.indexOf(selectobject.options[i].value) != -1) {
selectobject.removeChild(selectobject.options[i]);
}
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
When :
<select id="action" name="action">
<option value="link">Link Clicked</option>
<option value="form">Form Submitted</option>
</select>
with:
<select id="action-attribute" name="action-attribute">
<option>ID</option>
<option>Class</option>
</select>
May I propose a different approach? Instead of maintaining the state of the menu by removing elements that shouldn't be there, blow away the menu option tags entirely and replace.
$(document).ready(function() {
var options = {
link: ['ID', 'Class']
},
dependentMenu = document.getElementById('action-attribute');
options.form = options.link.concat(['Name', 'ActionURL']);
$("#action").change(function() {
var el = $(this);
while (dependentMenu.firstChild) {
dependentMenu.removeChild(dependentMenu.firstChild);
}
options[el.val()].forEach(function(value) {
var option = document.createElement('option');
option.text = value;
dependentMenu.add(option);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
When :
<select id="action" name="action">
<option value="link">Link Clicked</option>
<option value="form">Form Submitted</option>
</select>
with:
<select id="action-attribute" name="action-attribute">
<option>ID</option>
<option>Class</option>
</select>
Complete JS novice. I want a "Request A Quote" button to auto-populate a dropdown menu on a new page based on the product and url. Each product quote button links to the same form but with a different hash value in the url which matches an option in the dropdown menu.
Example:
User clicks "Request A Quote" for 'Product A'
User is sent to www.example.com/request-a-quote/#Product A
Product dropdown menu (id=product-select) on form already reads "Product A"
This code works on Chrome, but not for anything else. What am I doing wrong?
//Get select object
var objSelect = document.getElementById("product-select");
var val = window.location.hash.substr(1);
//Set selected
setSelectedValue(objSelect, val)
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
I found that applying decodeURIComponent() cleaned up my val variable.
Also, building links as www.example.com/request-a-quote/#Product A is important. If the forward slash is not before the hash, mobile Safari will ignore everything after the hash and it won't work.
Below is my final solution:
//Get select object
var objSelect = document.getElementById("product-select");
var val = decodeURIComponent(window.location.hash.substr(1));
//Set selected
setSelectedValue(objSelect, val)
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
Without seeing more code.... The option tag officially supports the value attribute vs text which is the user readable name. We use value as an identifier:
selectObj.options[i].value == valueToSelect;
You will also need to change the select.options markup to use the value attribute rather then text.
UPDATE more info as requested:
The purpose of text is to provide a user readable option. We use value to identify the selection to the server and in your case the URL hash. By using the value attribute, you can use URL safe values and user readable text.
The fix you posted in your answer is really bad practice and will become problematic as the complexity of your code increases.
This example will work in all browsers and is the proper way to implement.
//Simulate hash
window.location.hash = '2'
var val = window.location.hash.substr(1);
var selectEle = document.getElementById('select')
setSelectedValue(selectEle, val)
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
var selection = selectObj.options[i]
if (selection.value == valueToSet) {
selection.selected = true;
}
}
}
<select name="selections" id="select">
<option value="1">Product A</option>
<option value="2">Product B</option>
<option value="3">Product C</option>
</select>
I am using following html for dropdown
<select class="form-control" id="iddeStatus" name="iddeStatus">
<option value="">--Select ID De-dup Status--</option>
<option value="PASSED">Passed</option>
<option value="FAILED">Failed</option>
</select>
And below is my jquery code to get dropdown value
var iddeStatus = $("#iddeStatus").val();
if((iddeStatus!=null)||(iddeStatus!="")){
...
}else{
...
}
Problem is, even if i dont select the value, control goes inside the if statement.
Reason for behaviour:
That is because you have or statement in if between if conditions. You need to use && condition instead of ||
if((iddeStatus!=null) && (iddeStatus!="")){
...
}
Solution:
You can narrow down the if condition to simply:
if(iddeStatus!="")){
...
}
You can check for truthyness of the value
var iddeStatus = $("#iddeStatus").val();
if (!iddeStatus) {
//not selected
} else {//no need to have the else block if you don't have anything to do here
//selected
}
or the opposite
var iddeStatus = $("#iddeStatus").val();
if (iddeStatus) {
//selected
} else {
//not selected
}
Please use below code to get unselected value in dropdown jquery.
var iddeStatus = $("#iddeStatus").val();
if((iddeStatus!=null)||(iddeStatus!="")){
var unSelected = $("#iddeStatus").find('option').not(':selected');
for (var i = 0; i < unSelected.length; i++) {
alert(unSelected[i].text)
}
}else{
alert('else part')
}
I have this code:
function SelectReferralFromQueryString() {
var queryStringName = GetParameterValues('Referral');
if (queryStringName != undefined || queryStringName != null) {
queryStringName = decodeURIComponent(queryStringName);
var exists = false;
$('#refDropDown option').each(function () {
if (this.value == queryStringName) {
exists = true;
var option = $(this);
$(this).remove();
$('#refDropDown option').prepend(option);
return false;
}
});
if (exists == true){
DropDownReferral.value = queryStringName;
$("#refDropDown").prop("disabled", true);
}
}
}
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
else
return false;
}
}
And this HTML:
<select name="refDropDown" id="refDropDown" class="items" data-hidden-field="DropDownReferral">
<option value="">Please Select</option>
<option value="Albert">Al</option>
<option value="Steve T">Steve</option>
</select>
So, the logic is:
If 'Referral' which is a query string, gets passed, then I am checking the value in my select option and moving it on top and disabling the dropdown. NOT WORKING! See the picture below.
If the dropdown doesnt have the query string value then disable the dropdown and store it in the hidden field. (WORKING!)
What I am missing here?
If I am passing ?Referral=Albert, then it should show me 'Al' on top. If I am passing ?Referral=Steve, then is show 'Steve' on top and disable the dropdown.
You can use the val() function of jQuery to select the option:
$("#refDropDown").val(queryStringName);
If you can count on the referral being a valid value you can try this (untested):
$('#refDropDown').val(queryStringName).prop('disabled', true);
Otherwise check for whether or not the value exists first by doing something like this:
if($('#refDropDown option[value="' + queryStringName + '"]').length != 0){
//code above here
}
Then get rid of that loop over the options and that if that is setting the select box to disabled.
Also as a side note, a disabled select box won't submit a value when you submit the form, so you will need to use the referral parameter, or a hidden field.
I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});