How to select all from a dropdown using ASP/JavaScript/HTML - javascript

I have a piece of software that I am working on that allows you to select locations and this shows on a map. I want to add functionality to select all the locations with a button and show the information on the map.
I'm new to coding and therefore haven't really written any code. I have been searching the web but to no avail which is why I came to ask you lovely people on here.
Any advice or links you provide will be greatly appreciated.
function checkAddAllName(mode){
var Name = document.getElementById('select_'+mode+'_ID').options[document.getElementById('select_'+mode+'_ID').selectedIndex].text;
var Name = document.getElementById('select_'+mode+'_ID').options[document.getElementById('select_'+mode+'_ID').selectedIndex].value;
var errorCount = 0;
var Name = 0;
var allStations = document.getElementsByTagName('input');
for (var i=0; i<allNames.length; i++){
if (allNames[i].id.substring(0,10) == 'StationNo_'){
var splitID = allNames[i].id.split("_");
if (splitID[1] == mode){
if (allNames[i].value == addedNameNo){
errorCount = 1;
}
}
}
}
if (errorCount == 0){
addNAme(mode);
} else {
alert(addedName+' has already been added!');
}
}

You are better off doing this using a library like jQuery. It'll take you some time in the beginning to learn, but it'll pay off for the rest of your web programming days.
Assuming your locations are an unordered list of checkboxes like:
<ul id='listId'>
<li><input type="checkbox value="London">London</li>
<li><input type="checkbox value="Paris">Paris</li>
<li><input type="checkbox value="Buenos Aires">Buenos Aires</li>
</ul>
<button id="selectAll">Select all</button>
In jQuery you'd do something like:
$('button#selectAll').on("click",function(){
$('ul#listId > li > input').prop('checked',true);
});

Assuming you mean ordinary single selection drop down like this:
<select id="ddlSelectCountry" onchange="SelectCountry(this);">
<option value="">Please select..</option>
<option value="USA">USA</option>
<option value="France">France</option>
<option value="Spain">Spain</option>
</select>
You can have such button to auto select all non empty items:
<button type="button" onclick="SelectAll('ddlSelectCountry');">Select All</button>​
And the JavaScript for that would be:
function SelectAll(strDropDownId) {
var oDDL = document.getElementById(strDropDownId);
if (!oDDL) {
alert("No such element: " + strDropDownId);
return;
}
for (var i = 0; i < oDDL.options.length; i++) {
if (oDDL.options[i].value.length > 0) {
oDDL.selectedIndex = i;
if (oDDL.change)
oDDL.change();
else if (oDDL.onchange)
oDDL.onchange();
}
}
}
Using jQuery the code can be greatly reduced in length and made more elegant, but that's your choice.
Live test case.

Related

Explanation for a piece of javascript code

I am a beginner in javascript and I am looking at the following piece of code.
var type_select = '<select id="type_select" style="margin-bottom:0px;">';
var i;
var customer_group = <?php echo json_encode($customer_group);?>;
for (i = 0; i < customer_group.length; ++i) {
//console.log(customer_group[i].group_id);
if (customer_group[i].group_name == table_column_1){
type_select = type_select+'<option value='+customer_group[i].group_id+' selected>'+customer_group[i].group_name+'</option>';
}else{
type_select = type_select+'<option value='+customer_group[i].group_id+'>'+customer_group[i].group_name+'</option>';
}
}
type_select = type_select+'</select>';
//not allow to click header
if ( col == 0 ) {
return;
}
Please help to give me some idea of what it might be doing. Maybe some direction. I am not sure if this code is enough,Please try your best to help me and explain to me as much as possible. Your help will be very much appreciated.
It's building a select dropdown box with some options
<select id="type_select" style="margin-bottom:0px;">
<option value="some-value">Some text</option>
<option value="some-other-value">Some other text</option>
<option value="yet-another-value" selected>More text this one is selected on load</option>
</select>
Looking at the snippet of code you posted, it then does absolutely nothing with it
Hope that helps
var type_select = '<select id="type_select" style="margin-bottom:0px;">';
var i;
// this part of code will be interpreted by PHP Engine, on client side you will find an JSON representation of
// "Customer_group", probably gotten from database, or file
var customer_group = <?php echo json_encode($customer_group);?>;
for (i = 0; i < customer_group.length; ++i) {
// here, you are building a HTML string, this will be attached to DOM using
// ex : document.getElementById('YOUR_DOM_ID').innerHTML = type_select;
if (customer_group[i].group_name == table_column_1){
type_select = type_select+'<option value='+customer_group[i].group_id+' selected>'+customer_group[i].group_name+'</option>';
}else{
type_select = type_select+'<option value='+customer_group[i].group_id+'>'+customer_group[i].group_name+'</option>';
}
}
type_select = type_select+'</select>';
//not allow to click header
if ( col == 0 ) {
return;
}

How do I get javascript to see updated select value?

I have a page with about 100 dropdown menus that I need to pass to another. So, I've put everything in an array that I'm sending via javascript. However, I'm not sure how to get the javascript to see the changed values of the dropdowns before sending. I mocked up some code to give you an idea of the problem. It only sends the value of the dropdown box at the time the page is initialized. Any help would be appreciated.
<select id="mydropdown">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
<script>
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
</script>
<form name="data" method="POST" action="passdata1b.php">
<input type="hidden" name="data">
</form>
<script>
function sendData()
{
// Initialize packed or we get the word 'undefined'
var packed = "";
for (i = 0; (i < data.length); i++) {
if (i > 0) {
packed += ",";
}
packed += escape(data[i]);
}
document.data.data.value = packed;
document.data.submit();
}
</script>
<h1>This is what the array contains:</h1>
<ul>
<script>
for (i = 0; (i < data.length); i++) {
document.write("<li>" + data[i] + "</li>\n");
}
</script>
</ul>
Go to passdata1b.php
Sam's answer was good, except..
data[0] = document.getElementById("mydropdown").value;
..that won't work since it's a dropdown menu. Instead get the value of the selected option. Use this instead:
var zeData = document.getElementById("mydropdown");
data[0] = zeData.options[zeData.selectedIndex].value;
Why can't you put this logic:
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
In your sendData() function?
Comment if you need an example, but this should be a pretty easy fix. That way, when you click the link and run sendData(), it will parse the mydropdown value..instead of doing it on page load.

How to change options of a select using JavaScript

I have an HTML page in which I have 2 selects.
<select id="field" name="field" onchange="checkValidOption();">
<option />
<option value="Plugin ID">Plugin ID</option>
<option value="Name">Name</option>
</select>
<select id="operator" name="operator" onchange="checkValidOption();">
<option />
<option value="EQUALS">EQUALS</option>
<option value="CONTAINS">CONTAINS</option>
<option value="NOT CONTAINS">NOT CONTAINS</option>
<option value="REGEX">REGEX</option>
</select>
What I'd like to happen is that checkValidOption() could make it so that if "Plugin ID" is selected in field that the only option is EQUALS (and it's selected) and otherwise all the other options are available. Any idea on how to approach this?
I tried changing the innerHTML of the operator select in JS:
document.getElementById("operator").innerHTML =
"<option value='EQUALS'>EQUALS</option>";
However this results in an empty select (this would also include manually setting the many options for going back to having all the ones listed above).
I can't think of another solution, any help would be greatly appreciated.
Try this:
Demo here
var field = document.getElementById('field');
var operator = document.getElementById('operator');
field.onchange = function () { fieldcheck(); }
operator.onchange = function () { fieldcheck(); }
fieldcheck();
function fieldcheck() {
if (field.value == 'Plugin ID') {
for (i = 0; i < operator.options.length; ++i) {
if (operator.options[i].value != 'EQUALS') {
operator.options[i].disabled = true;
}
};
operator.value = 'EQUALS';
} else {
for (i = 0; i < operator.options.length; ++i) {
operator.options[i].disabled = false;
};
}
}
To manipulate options when Plugin ID was selected:
function checkValidOption(){
var x=document.getElementById("field");
var y=document.getElementById("operator");
if (x.options[1].selected === true){
document.getElementById("operator").options[1].selected = true;
for(var i=0; i<y.length; i++){
if (i !== 1){
//disabling the other options
document.getElementById("operator").options[i].disabled = true;
}
}
}
else{
for(var i=0; i<y.length; i++){
//enabling the other options
document.getElementById("operator").options[i].disabled = false;
}
}
}
Here's a link to fiddle
A select field doesn't use the innerHTML method, you need to use value.
document.getElementById("operator").value = "...";
heres a jquery solution.
every time the first select changes, it produces new options from an array for the 2nd select. issue here is i had to change the option values of the first select to 0 and 1 to select which value in the array, you can manipulate those later if you are storing this info somewhere
http://jsfiddle.net/2TZJh/
$(document).ready(function() {
$("#field").change(function() {
var val = $(this).val();
$("#operator").html(options[val]);
});
var options = [
'<option value="EQUALS">EQUALS</option>',
'<option></option><option value="EQUALS">EQUALS</option><option value="CONTAINS">CONTAINS</option> <option value="NOT CONTAINS">NOT CONTAINS</option> <option value="REGEX">REGEX</option>'
];
});

How to set selectedIndex of select element using display text?

How to set selectedIndex of select element using display text as reference?
Example:
<input id="AnimalToFind" type="text" />
<select id="Animals">
<option value="0">Chicken</option>
<option value="1">Crocodile</option>
<option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />
<script type="text/javascript">
function SelectAnimal()
{
//Set selected option of Animals based on AnimalToFind value...
}
</script>
Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...
Try this:
function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML === val) {
sel.selectedIndex = i;
break;
}
}
}
<script type="text/javascript">
function SelectAnimal(){
//Set selected option of Animals based on AnimalToFind value...
var animalTofind = document.getElementById('AnimalToFind');
var selection = document.getElementById('Animals');
// select element
for(var i=0;i<selection.options.length;i++){
if (selection.options[i].innerHTML == animalTofind.value) {
selection.selectedIndex = i;
break;
}
}
}
</script>
setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces
selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
or using .match(/regular expression/)
If you want this without loops or jquery you could use the following
This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.
// Please note that querySelectorAll will return a match for
// for the term...if there is more than one then you will
// have to loop through the returned object
var selectAnimal = function() {
var animals = document.getElementById('animal');
if (animals) {
var x = animals.querySelectorAll('option[value="frog"]');
if (x.length === 1) {
console.log(x[0].index);
animals.selectedIndex = x[0].index;
}
}
}
<html>
<head>
<title>Test without loop or jquery</title>
</head>
<body>
<label>Animal to select
<select id='animal'>
<option value='nothing'></option>
<option value='dog'>dog</option>
<option value='cat'>cat</option>
<option value='mouse'>mouse</option>
<option value='rat'>rat</option>
<option value='frog'>frog</option>
<option value='horse'>horse</option>
</select>
</label>
<button onclick="selectAnimal()">Click to select animal</button>
</body>
</html>
document.getElementById('Animal').querySelectorAll('option[value="searchterm"]');
in the index object you can now do the following:
x[0].index
Try this:
function SelectAnimal()
{
var animals = document.getElementById('Animals');
var animalsToFind = document.getElementById('AnimalToFind');
// get the options length
var len = animals.options.length;
for(i = 0; i < len; i++)
{
// check the current option's text if it's the same with the input box
if (animals.options[i].innerHTML == animalsToFind.value)
{
animals.selectedIndex = i;
break;
}
}
}
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..
Add name attribute to your option:
<option value="0" name="Chicken">Chicken</option>
With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.
You can use the HTMLOptionsCollection.namedItem()
That means that you have to define your select options to have a name attribute and have the value of the displayed text.
e.g
California

Search a dropdown

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

Categories