Display count of Selected items in a <select multiple> - javascript

Tried all the answers on this q, but just can't get the count to display (or maybe the js to run?)
Here's my code .. I want the current count of selected items to update each time I select another
Any advice appreciated .. learning every day
<html>
<head>
<script type="text/Javascript">
function count_cars() {
var options = document.getElementById("cars").options, count = 0 ;
for (var i=0; i < options.length; i++) {
if (options[i].selected) count++;
} // end of for loop
// now put the current count in the element with id='car_count'
document.getElementById("car_count").innerHTML = count ;
} // end of function
</script>
</head>
<body>
<form name="test1" method="GET" action="test2.html">
How many cars have you got?
<table>
<tr><td>
<select multiple name="cars[]" value="" onchange="count_cars">
<option value="ford" >Ford </option>
<option value="saab" >Saab </option>
<option value="merc" >Merc </option>
<option value="audi" >Audi </option>
</select>
</td><td>Total : <div id="car_count"></div></td></tr>
<tr><td><input type="submit"></td></tr>
</table>
</form>
</body>
</html>

You were trying to access the select list option by id - but the select did not have an id. Also - its better to indent your code in a more readable fashion.
function count_cars() {
var options = document.getElementById("cars").options, count = 0 ;
for (var i=0; i < options.length; i++) {
if (options[i].selected) count++;
} // end of for loop
document.getElementById("car_count").innerHTML = count ;
} // end of function
<form name="test1" method="GET" action="test2.html">
How many cars have you got?
<table>
<tr>
<td>
<select multiple id="cars" name="cars[]" value="" onchange="count_cars()">
<option value="ford" >Ford </option>
<option value="saab" >Saab </option>
<option value="merc" >Merc </option>
<option value="audi" >Audi </option>
</select>
</td>
<td>
Total : <div id="car_count"></div>
</td>
</tr>
<tr>
<td>
<input type="submit">
</td>
</tr>
</table>
</form>

You can use the filter feature.
const options = document.getElementById("cars").options;
const count = [...options].filter(option => option.selected).length;
Don't forget to set an the cars id to your select.

You can use selectedOptions.
It contains a list of the elements contained within the element that are currently selected.
It is an HTMLCollection object with one entry per currently selected option
var count = document.getElementById("cars").selectedOptions.length;
and display it using
document.getElementById("car_count").innerHTML = count ;

Related

JavaScript - how to remove `options` by its `value`

I have a dropdown menu with products similiar like this
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananes</option>
<option value="3" >Apples</option>
</select>
I need to remove options by its value. How to do that ?
Pure JavaScript please.
EDIT : I know that I need to use element.removeChild(child) method. But how to reference child by its value. Thats my point.
EDIT 2 : I use the script of zdrohn below and it works. Because I have several fruits dropdowns with the same collection I need to iterate trough all dropdowns and delete it from all dropdowns. This is my code now :
<script type='text/javascript'>
var id = 3;
var el= document.getElementsByClassName("fruits");
for (i=0;i<el.length;i++) {
for(var n = 0; n < el[i].length; n++) {
if(el[i][n].value == id) {
el[i][n].remove();
}
}
</script>
Though it works I wonder about that I do not need to use the parent.removeChild() method. How comes ?
P.S. I wonder that peole vote this question down. As the response shows their are several solutions. Though not all are sufficiantly explained.
Here is a snippet to play with.
The code removes the option with value = 3
window.onload = function() {
var optionToDelete = document.querySelector("select.fruits > option[value='3']");
optionToDelete.parentNode.removeChild(optionToDelete);
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
EDIT: Based on the updated question - I have several fruits drop-downs.
We could make use of querySelectorAll to select all matching elements and forEach to apply the desired logic on each element in the selected list.
window.onload = function() {
var optionsToDelete = document.querySelectorAll("select.fruits > option[value='3']");
optionsToDelete.forEach(function(element, index, array) {
element.parentNode.removeChild(element);
});
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
<select class="fruits">
<option value="1">Seville oranges</option>
<option value="2">Burro Bananes</option>
<option value="3">Baldwin Apples</option>
</select>
<select class="fruits">
<option value="1">Bergamot oranges</option>
<option value="2">Red Bananes</option>
<option value="3">Gravenstein Apples</option>
</select>
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananas</option>
<option value="3" >Apples</option>
</select>
<script type='text/javascript'>
var valueToRemove = 1;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
</script>
Edit:
<select class="fruits" >
<option value="1">Oranges</option>
<option value="2">Bananas</option>
<option value="3">Apples</option>
</select>
<br>
<label>Input value to delete</label><input type='text' id='delete_value'>
<button onclick='remove(document.getElementById("delete_value").value)'>Delete</button>
<script type='text/javascript'>
function remove(item) {
var valueToRemove = item;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
}
</script>
You can select the desired option by using document.querySelector() and a selector of this form
A more complete list of selectors can be found here
Example
var element = document.evaluate( '//option[#value="1"]' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
element.parentNode.removeChild(element)

time tracker with jquery

What I have so far is a table where a user can input their hours,minutes,activity name, and the category of that activity. A user can add/delete rows as they see fit.
What I need to accomplish is, when the user clicks the "Calculate" button it will add the hours/minutes and then store the input value in "activity" and "category".
Here is a Fiddle of what I have so far. http://jsfiddle.net/os214gru/
<!DOCTYPE html><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>English Styles Test</title>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.17.2/build/cssreset/cssreset-min.css">
<link href="http://explore.hawkeslearning.com/portal/content/css/learn_content_styles.css" rel="stylesheet">
<link href="css/form-styles.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
// if Google is down, it looks to local file...
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='js/jquery-1.11.2.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
<script type="text/javascript" src="js/clone-form-td.js"></script>
</head>
<body>
<!-- https://jqueryui.com/dialog/
http://www.jacklmoore.com/notes/jquery-modal-tutorial/ -->
<div id="screenContainer">
<div id="screenContainerEng">
<div class='budgetForm-ENG'>
<form action="#" method="post" id="BudgetFormEng">
<table>
<thead>
<tr>
<th colspan='4'>Time Budget Calculator</th>
</tr>
<tr>
<th id='hourLabel'>Hour</th>
<th id='minuteLabel'>Minutes</th>
<th id='activityLabel'>Activity</th>
<th id='categoryLabel'>Category</th>
</tr>
</thead>
<tbody>
<tr id="CloneRow">
<td>
<input class="input_hr" type="number" value="0" name="ID_hour" id="ID_hour" aria-labeledby="hourLabel" min="0">
</td>
<td>
<input class="input_min" type="number" value="0" name="ID_min" id="ID_min" min="0" max="59" aria-labeledby="minuteLabel">
</td>
<td>
<input type="text" name="ID_act" id="ID_act" aria-labeledby="activityLabel">
</td>
<td>
<select class="input_cat" name="ID_cat" id="ID_cat" aria-labeledby="cateogryLabel">
<option value="" selected="selected" disabled="disbled">
Select Category
</option>
<option value="Class">
Class
</option>
<option value="Entertainment">
Entertainment
</option>
<option value="Exercise">
Exercise
</option>
<option value="Extracurricular">
Extracurricular
</option>
<option value="Family">
Family
</option>
<option value="Meal">
Meal
</option>
<option value="Other">
Other
</option>
<option value="Personal">
Personal
</option>
<option value="Sleep">
Sleep
</option>
<option value="Social">
Social
</option>
<option value="Study">
Study
</option>
<option value="Work">
Work
</option>
</select>
</td>
</tr>
<tr id="CloneRow0">
<td>
<input class="input_hr" type="number" value="0" name="ID0_hour" id="ID0_hour" aria-labeledby="hourLabel" min="0">
</td>
<td>
<input class="input_min" type="number" value="0" name="ID0_min" id="ID0_min" min="0" max="59" aria-labeledby="minuteLabel">
</td>
<td>
<input type="text" name="ID0_act" id="ID0_act" aria-labeledby="activityLabel">
</td>
<td>
<select class="input_cat" name="ID0_cat" id="ID0_cat" aria-labeledby="cateogryLabel">
<option value="" selected="selected" disabled="disbled">
Select Category
</option>
<option value="Class">
Class
</option>
<option value="Entertainment">
Entertainment
</option>
<option value="Exercise">
Exercise
</option>
<option value="Extracurricular">
Extracurricular
</option>
<option value="Family">
Family
</option>
<option value="Meal">
Meal
</option>
<option value="Other">
Other
</option>
<option value="Personal">
Personal
</option>
<option value="Sleep">
Sleep
</option>
<option value="Social">
Social
</option>
<option value="Study">
Study
</option>
<option value="Work">
Work
</option>
</select>
</td>
</tr>
<tr id="CloneRow1" class='clonedInput'>
<td>
<input class="input_hr" type="number" value="0" name="ID1_hour" id="ID1_hour" aria-labeledby="hourLabel" min="0">
</td>
<td>
<input class="input_min" type="number" value="0" name="ID1_min" id="ID1_min" min="0" max="59" aria-labeledby="minuteLabel">
</td>
<td>
<input class="input_act" type="text" name="ID1_act" id="ID1_act" aria-labeledby="activityLabel">
</td>
<td>
<select class="input_cat" name="ID1_cat" id="ID1_cat" aria-labeledby="cateogryLabel">
<option value="" selected="selected" disabled="disbled">
Select Category
</option>
<option value="Class">
Class
</option>
<option value="Entertainment">
Entertainment
</option>
<option value="Exercise">
Exercise
</option>
<option value="Extracurricular">
Extracurricular
</option>
<option value="Family">
Family
</option>
<option value="Meal">
Meal
</option>
<option value="Other">
Other
</option>
<option value="Personal">
Personal
</option>
<option value="Sleep">
Sleep
</option>
<option value="Social">
Social
</option>
<option value="Study">
Study
</option>
<option value="Work">
Work
</option>
</select>
</td>
</tr>
<tr class='output'>
<th>Total:</th>
<td id='output' colspan='3'></td>
</tr>
</tbody>
</table>
<div id="addDelButtons">
<input type="button" id="btnAdd" value="add section" class='fontawesome-plus' aria-label="Add Row">
<input type="button" id="btnDel" value="remove section above" class='fontawesome-minus' aria-label="Remove Last Row">
<input type="button" id="btnRes" value="Reset form" aria-label="Reset Form">
<input type="button" id="btnCalc" value="Calculate" aria-label="Reset Form">
</div>
</form>
</div>
<p id='demo'></p>
</div>
</div>
</body>
</html>
This is the JS
$(function () {
$('#btnAdd').click(function () {
var num = $('.clonedInput').length, // Checks to see how many "duplicatable" input fields we currently have
newNum = new Number(num + 1), // The numeric ID of the new input field being added, increasing by 1 each time
newElem = $('#CloneRow' + num).clone().attr({'id': 'CloneRow' + newNum}).addClass('addedRow').fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value
/* This is where we manipulate the name/id values of the input inside the new, cloned element
Below are examples of what forms elements you can clone, but not the only ones.
There are 2 basic structures below: one for an H2, and one for form elements.
To make more, you can copy the one for form elements and simply update the classes for its label and input.
Keep in mind that the .val() method is what clears the element when it gets cloned. Radio and checkboxes need .val([]) instead of .val('').
*/
// Title - select
newElem.find('.input_hr').attr('id', 'ID' + newNum + '_hour').attr('name', 'ID' + newNum + '_hour').val('0');
// First name - text
newElem.find('.input_min').attr('id', 'ID' + newNum + '_min').attr('name', 'ID' + newNum + '_min').val('0');
// Last name - text
newElem.find('.input_act').attr('id', 'ID' + newNum + '_act').attr('name', 'ID' + newNum + '_act').val('');
// Color - checkbox
newElem.find('.input_cat').attr('id', 'ID' + newNum + '_cat').attr('name', 'ID' + newNum + '_cat').val('');
// Insert the new element after the last "duplicatable" input field
$('#CloneRow' + num).after(newElem);
$('#ID' + newNum + '_title').focus();
// Enable the "remove" button. This only shows once you have a duplicated section.
$('#btnDel').attr('disabled', false);
// Right now you can only add 13 sections, for a total of 15. Change '13' below to the max number of sections you want to allow.
if (newNum == 13)
$('#btnAdd').attr('disabled', true).prop('value', "That's all, folks!"); // value here updates the text in the 'add' button when the limit is reached
});
$('#btnDel').click(function () {
// Confirmation dialog box. Works on all desktop browsers and iPhone.
if (confirm("Are you sure you wish to remove this section? This cannot be undone."))
{
var num = $('.clonedInput').length;
// how many "duplicatable" input fields we currently have
$('#CloneRow' + num).slideUp('slow', function () {$(this).remove();
// if only one element remains, disable the "remove" button
if (num -1 === 1)
$('#btnDel').attr('disabled', true);
// enable the "add" button
$('#btnAdd').attr('disabled', false).prop('value', "add section");});
}
return false; // Removes the last section you added
});
// Enable the "add" button
$('#btnAdd').attr('disabled', false);
// Disable the "remove" button
$('#btnDel').attr('disabled', true);
// Reset the entire form
$('#btnRes').click( function () {
{
// Confirmation dialog box. Works on all desktop browsers and iPhone.
if (confirm("Do you really want to reset the form? All data will be lost."))
{
document.getElementById("BudgetFormEng").reset();
$('.addedRow').remove();
$('#output').empty();
};
return false;
};});
$('#btnCalc').click(function() {
var hours = $(".input_hr").serializeArray();
var minutes = $(".input_min").serializeArray();
var categories = $(".input_cat").serializeArray();
var blargh = [];
for(var i=0;i<categories.length;i++){
blargh.push({cat:categories[i].value,hour:hours[i].value,minute:minutes[i].value});//add object literal
}
/* jQuery.each(blargh, function (i, cat) {
console.log(i.value)
});
/* var totalHours = 0;
var totalMins = 0;
jQuery.each(hours, function( i, hours) {
totalHours += parseInt(hours.value) * 60
});
jQuery.each(minutes, function( i, minutes) {
totalMins += parseInt(minutes.value)
});
var totalTime = totalHours + totalMins;
var realMin = totalTime % 60;
var realHour = Math.floor(totalTime / 60);
$('#output').empty();
$('#output').append(realHour + ' hours, ' + realMin + ' minutes');*/
})
});
First: You'll save yourself MUCH time and work, if you use classes instead of id for your elements.
This solution works only, if you give your TR a class of trclass, your activity a class of "input_act" and the category a class of "input_cat"
I output the categories and activities on the console only, decide yourself what to do with it.
the actual calculating is rather easy:
$(function() {
$("#btnCalc").click(function(e) {
e.preventDefault();
calcIt();
});
}
function calcIt() {
var hours = 0;
var minutes = 0;
var activities = "";
var cats = "";
$(".trclass").each(function(index) {
hours += parseInt($(this).children("td").children(".input_hr").val());
minutes += parseInt($(this).children("td").children(".input_min").val());
activities += $(this).children("td").children(".input_act").val();
cats += $(this).children("td").children(".input_cat").val();
});
$("#output").html(hours+":"+minutes);
console.log(activities);
console.log(cats);
}
DEMO

How do I have my drop down selections submit in the HTML form?

I have these conditional drop lists behaving on screen as expected, but I cannot get the selected values from the drop downs to output in the HTML form (I can if I don't include the javascript). Only the text inputs are outputing as per the xml result below (Company & Add1). I want the xml to contain the Location from the first drop down, and the selected city from the conditional 2nd drop down.
<body>
<form action="http://TESTPLANETPRESS:8080/ObtainQuote" method="GET" >
<fieldset>
<legend>Location</legend>
<select id="country" class="source" onchange="updateSelectTarget()">
<option value="England">England</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
</select>
<select id="England">
<option value="Birmingham">Birmingham</option>
<option value="Liverpool">Liverpool</option>
<option value="London">London</option>
</select>
<select id="France" class="hidden">
<option value="Lyon">Lyon</option>
<option value="Marseille">Marseille</option>
<option value="Paris">Paris</option>
</select>
<select id="Germany" class="hidden">
<option value="Berlin">Berlin</option>
<option value="Hamburg">Hamburg</option>
<option value="Munich">Munich</option>
</select>
<label for="Company">Company:</label><input type="text" name="Company" value="Google">
<label for="Add1">Add1:</label><input type="text" name="Add1" value="1 Nowhere Street">
</fieldset>
<input type="submit" value="Submit">
</form>
<script>
function updateSelectTarget () {
var id = this.options[this.selectedIndex].value;
var targets = this.parentNode.getElementsByTagName("select");
var len = targets.length;
for (var i = len - 1; i > 0; --i) {
if (targets[i].id == id) {
targets[i].style.display = "block";
}
else {
targets[i].style.display = "none";
}
}
}
function initChangeHandler () {
var el = document.getElementById("country");
el.onchange = updateSelectTarget;
el.onchange();
}
window.onload = initChangeHandler;
</script>
</body>
Current XML result, (Does not include the results from the two drop downs).
<?xml version="1.0"?>
-<request type="GET">
<paths count="0"/>
-<values count="2">
<Company>Google</Company>
<Add1>1 Nowhere Street</Add1>
</values>
Do you want the value attribute or the text? Based on Get selected value in dropdown list using JavaScript? (similar to the first part), .value should work for the value attribute and .text for the text that is selected.
Also, please make two different questions instead of one question with 2 questions nested inside.

Submit form after selecting items from multiple dropdown lists - JavaScript

Here is my HTML
<form action="processForm.html" method="post">
<label for="InputOne">Input One</label>
<select id="InputOne">
<option val="1">Item</option>
<option val="2">Item</option>
<option val="3">Item</option>
<option val="4">Item</option>
</select>
<label for="InputTwo">Input Two</label>
<select id="InputTwo">
<option val="1">Item</option>
<option val="2">Item</option>
<option val="3">Item</option>
<option val="4">Item</option>
</select>
<input type="submit" value="Submit">
</form>
How do I enable the user to select from multiple dropdown lists and then hit a Submit button? I found this answer How to submit form on change of dropdown list?. It's close, but I don't think it's what I want. This will submit after a single dropdown list.
The short answer
<form id="my-form" method="post">
<select name="first-list" multiple="multiple" size="10">
<option value="0"></option>
<option value="1">first</option>
<option value="2">second</option>
<option value="3">third</option>
</select>
<select name="second-list" multiple="multiple" size="10">
<option value="0"></option>
<option value="1">first</option>
<option value="2">second</option>
<option value="3">third</option>
</select>
<!-- use this for client-side processing -->
<input type="button" name="button" value="submit" />
<!-- use this for server-side processing -->
<input type="submit" name="submit" value="submit" />
</form>
EDIT
//
// Collecting selected items from one or more multiple select-lists
//
window.onload = function(){
document.getElementById("button").onclick = function(){
var lists = document.getElementsByTagName('SELECT'), chosen = [], temp = [], list = {}, i, j;
for(i = 0; i < lists.length; i++) {
list = lists[i];
temp = [];
for(j = 0; j < list.length; j++) {
if(list[j].selected) temp.push(list[j].value);
}
chosen.push(temp);
}
console.log(JSON.stringify(chosen));
// you will have JSON like this [["1","4","5"],["6","7"]]
};
Now, you have a JSON object ready to send on your server. If you have any doubts how to do it, check my previous answer on topic how to send and receive JSON data with JavaScript using POST and GET method.
And check the working fiddle.
If I understand correctly. You're having trouble submitting the data from both select dropdown.
I was facing the same problem, but adding enctype='multipart/form-data' to the form class solved it

synchronize two scrolling bars in multiple selection box

hi i am newbie to javascript....
i want to synchronize scrolling of two select boxes, so that when i scroll down the first select box the scroll bar of another select box also scrolls....
$(document).ready(function(){
$('#one').scroll(function(){
var length = $(this).scrollTop();
$('#two').scrollTop(length);
});
});
JS Bin Demo
in plain javascript the you would create an event handler for the scroll event that reads the scrollTop value from the relevant element and sets the same value on the second element.
var s1 = document.getElementById('Select1');
var s2 = document.getElementById('Select2');
function select_scroll(e) {
s2.scrollTop = s1.scrollTop;
}
s1.addEventListener('scroll', select_scroll, false);
The following is very simple, and I just confirmed it works in FF 3.6
<form id=puser name=puser>
<select name=user_select1 onclick="document.puser.user_select2.selectedIndex = this.selectedIndex">
<select name=user_select2 onclick="document.puser.user_select1.selectedIndex = this.selectedIndex">
the issue i am facing is....
i have two select boxes with multiple selection enabled.When i select an element from first select box it scrolls into view the corrosponding element from the second list.The single selection goes fine in all browsers explorer,firefox,chrome.
now, if i select the first,last element from the first selection box the second select box does not scrolls into view the last selected element in chrome browser.although , it works fine in internet explorer and firefox but not in google chrome browser.please tell me where i am wrong or is it there a better way to do the same.
<html>
<head>
<script language="javascript">
function SyncListsL(){
for (var i = 0; i <= [document.puser.user_select.length]-1; i++) {
if(document.puser.user_select.options[i].selected == true)
{
document.puser.user_select2.options[i].selected=true; document.puser.user_select.options[i].selected=true;
}
else{
document.puser.user_select2.options[i].selected = false;
document.puser.user_select.options[i].selected=false;
}
}
}
function SyncListsR(){
for (i = 0; i <= [document.puser.user_select2.length]-1; i++) {
if(document.puser.user_select2.options[i].selected == true)
{
document.puser.user_select.options[i].selected=true; document.puser.user_select2.options[i].selected=true;
}
else{
document.puser.user_select.options[i].selected = false;
document.puser.user_select2.options[i].selected=false;
}
}
}
</script>
<title>scrollintoview</title>
</head>
<body bgcolor="e2dbc5">
<form name="puser" >
<table align="center">
<tr>
<td align="right" bgcolor="#eeeadd"> <font size=2>
<select name="user_select2" multiple size="5" onChange="SyncListsR()" style="width:35mm">
<option value="a1" title="a1">a1</option>
<option value="a2" title="a2">a2</option>
<option value="ab" title="ab">ab</option>
<option value="abc" title="abc">abc</option>
<option value="e1" title="e1">e1</option>
<option value="e2" title="e2">e2</option>
<option value="new" title="new">new</option>
</select>
</font></td>
<td align="left" bgcolor="#eeeadd"> <font size=2>
<select name="user_select" multiple size="5" onChange="SyncListsL()" style="width:50mm">
<option value="first" title="first">first</option>
<option value="last" title="last">last</option>
<option value="ghi" title="ghi">ghi</option>
<option value="User" title="User">User</option>
<option value="ed" title="ed">ed</option>
<option value="edit" title="edit">edit</option>
<option value="second" title="second">second</option>
</select>
</font></td>
</tr>
</table>
</form>
</body>
</html>

Categories

Resources