listbox select count not work dont work - javascript

I recently trying to make a form with multiple select box. When someone select the options the number of selected options will be display on another text. I'm a beginner in JavaScript.
The function is called, but it doesn't count the number of the selected options.
<select name="element_17_1[ ]"
size="7" multiple="multiple"
class="element select medium"
id="element_17_1[ ]"
onfocus="selectCount(this.form);"
onClick="selectCount(this.form);"
>
<option value="Opt1">Opt1</option>
<option value="Opt2">Opt2</option>
<option value="Opt3">Opt3</option>
<option value="Opt4">Opt4</option>
<option value="Opt5">Opt5</option>
<option value="Opt6">Opt6</option>
<option value="Opt7">Opt7</option>
</select>
and this is the function I tried in the <head>
function selectCount(f) {
var selObj = myForm.elements['element_17_1[]'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
totalChecked++;
}
}
f.element_9.value = totalChecked;
}

You're trying to get an element named element_17_1[], but your select box is named element_17_1[ ]. JavaScript just sees the name as a bunch of characters, and that space makes a difference.

In your HTML you have:
> <select name="element_17_1[ ]"
> size="7" multiple="multiple"
> class="element select medium"
> id="element_17_1[ ]"
> onfocus="selectCount(this.form);"
> onClick="selectCount(this.form);"
> >
Note that in the listener, this references the element itself, so just pass that:
onfocus="selectCount(this);"
onClick="selectCount(this);"
So a reference to the element is passed directly to the function, which can be:
function selectCount(selObj) {
// The following line isn't needed now
// var selObj = myForm.elements['element_17_1[]'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
totalChecked += selObj.options[i].selected? 1 : 0;
}
// The next line needs the form, so
selObj.form.element_9.value = totalChecked;
}
Now you don't care what the select element is called. :-)
Edit
To click element_9 you might do:
<input name="element_9" onclick="
this.value = selectCount(this.form['element_17_1[ ]']);
">
Then the function is modified to:
function selectCount(selObj) {
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
totalChecked += selObj.options[i].selected? 1 : 0;
}
return totalChecked;
}
Enough homework for now. ;-)

Change your select's name name="element_17_1"and id id="element_17_1" and in also you don't have myForm in your function so var selObj = myForm.elements['element_17_1']; should be var selObj = f.elements['element_17_1']; and also you can use only on event as follows
onChange="selectCount(this.form);"
instead of
onfocus="selectCount(this.form);"
onClick="selectCount(this.form);"
Complete function:
function selectCount(f) {
var selObj = f.elements['element_17_1'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
totalChecked++;
}
}
f.element_9.value = totalChecked;
}
Update:
For your php scriptyou can keep your select's name name="element_17_1[]" and so in the function it should be var selObj = f.elements['element_17_1[]']; but without space like[ ]
DEMO.

Related

Find Options text in Dropdown and set selected and change text

with vanilla javascript I'd like to loop through my dropdown, and change the selected one, and then change the text that is displayed. I have it selecting, but I'm not getting the object name correct to change the optionText? of the item.
var textToFind = 'LdapUsers';
var dd = document.getElementById('membershipProvider');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
i.options.text = "Edgewood Login"; //This is WRONG
break;
}
}
guidance is appreciated.
You can use a querySelector and a selector to access it without a loop.
v = "222";
selProvider = document.querySelector("#membershipProvider option[value='" + v + "']");
if (selProvider) {
selProvider.text = "CHANGED!";
selProvider.selected = true;
}
<select id="membershipProvider">
<option value='111'>AAA</option>
<option value='222'>BBB</option>
</select>
You need to modify the option at that index. Right now you are trying to modify the index itself.
should be:
dd.options[i].text
not
i.options.text
var textToFind = 'LdapUsers';
var dd = document.getElementById('membershipProvider');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
dd.options[i].text = "Edgewood Login"; //This is WRONG
break;
}
}
<select id="membershipProvider">
<option value="cifs">CIFS</option>
<option value="LdapUsers">LdapUsers</option>
<option value="nfs">NFS</option>
<option value="test">Test</option>
</select>
You should use
dd.options[i].text = "Edgewood Login";
just like when checking for its value

Loop through a data array variable and select items from multi-select dropdown

Created a multi-select dropdown, when I click on any of the options I have a input field which stores the values in a textbox. When the page reloads- I want to reselect the values in the multi-select drop down. The text box keeps its values so i was hoping to loop through this if i put it in an array.
E.g. Text contains: "cheese,mozarella"
It is important to only check the items that have the value in the textbox
Jquery:
document.getElementById("txt1").value = "cheese,mozarella";
var data = document.getElementById("txt1").value;
var dataarray = data.split(","); //splits values (,)
console.log(dataarray);
var i;
for (i = 0; i < dataarray.length; i++) {
}
HTML:
<input type="text" runat="server" id="txt1" visible="true" value="0" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="cheese">Cheese</option>
<option value="tomatoes">Tomatoes</option>
<option value="mozarella">Mozzarella</option>
<option value="mushrooms">Mushrooms</option>
<option value="pepperoni">Pepperoni</option>
<option value="onions">Onions</option>
</select>
</div>
I have a codeply to demonstrate: https://www.codeply.com/go/mCcxCM0vHs
My aim is to get some jquery code to loop through a dataarray variable and check the box if the value exists and tick it.
This function receives a select and a value and will cycle through the select's options, compare to the given value and mark matching options as selected.
function prepopulateOptions(selectElement, value) {
var options = selectElement.options;
for (var i = 0, numberOfOptions = options.length; i < numberOfOptions; i++) {
if (options[i].value == value) {
options[i].selected = true;
}
}
}
This function clears all selected options.
function clearSelect(selectElement) {
var options = selectElement.options;
for (var i = 0, numberOfOptions = options.length; i < numberOfOptions; i++) {
options[i].selected = false;
}
}
Then tweak your script:
var data = "cheese,mozarella",
dataarray = data.split(","),
selectElement = document.getElementById('basic');
// clear select first
clearSelect(selectElement);
for (var i = 0; i < dataarray.length; i++) {
prepopulateOptions(selectElement, dataarray[i]);
}
Check the fiddle
With jQuery this could be rewritten even easier:
https://jsfiddle.net/rtm0n53b/
Use the localStorage and jQuery.
<script type="text/javascript">
function fnLoadOptions(text){
//--clear selection
$('#basic option').prop("selected", false);
//--load selection
text = text||'';
var items = text.split(',');
for(var i in items) {
$('#basic option[value="'+items[i]+'"]').prop("selected", true);
}
if($.fn.multiselect!=null) {
$('#basic').multiselect('refresh'); //--if using the bootstrap multiselect plugin, then refresh it.
}
}
var key = 'checkedOptions';
//--load previous selection
var previousSelection = localStorage.getItem(key);
fnLoadOptions(previousSelection);
$("#txt1").val(previousSelection);
//--bind to new selection
$('#basic').change(function () {
var v = $('#basic').val();
$("#txt1").val(v);
localStorage.setItem(key,v);
});
$('#txt1').bind("keyup change",function () {
fnLoadOptions($(this).val());
});
</script>

how to get html select to show selected value with javascript

I have a select dropdownlist with 1 item selected at page load in html.
<select name = "options">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "3">Item3</option>
<option value = "4">Item4</option>
</select>
Now I want to capture new select option when user press shift and select another option such as "Item 3".
I have the following code to find all the selections in the list
var value = "";
for (var intLoop = 0; intLoop < Form.elements[index].length; intLoop++) {
if(Form.elements[index][intLoop].selected )
value = value + Form.elements[index][intLoop].value;
}
I can see the "Item 2" and "Item 3" are selected but i want to get capture "Item 3" only. Is it possible?
Here's code that will tell you what has been selected and what has been deselected http://jsfiddle.net/8dWzB/
It uses Array.prototype.indexOf, and it's not the fastest way to do it. But it should get you going in the right direction.
HTML
<select id="options" multiple="multiple">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "3">Item3</option>
<option value = "4">Item4</option>
</select>
JS
function getSelectedIndexes(select) {
var selected = [];
for (var i = 0; i < select.options.length; i++) {
if(select.options[i].selected ) {
selected.push(i);
}
}
return selected;
}
var select = document.getElementById("options");
var prevSelected = getSelectedIndexes(select);
select.onchange = function(e) {
var currentlySelected = getSelectedIndexes(this);
for (var i =0; i < currentlySelected.length; i++) {
if (prevSelected.indexOf(currentlySelected[i]) == -1) {
console.log("Added to selection ", this.options[currentlySelected[i]].text);
}
}
for (var i =0; i < prevSelected.length; i++) {
if (currentlySelected.indexOf(prevSelected[i]) == -1) {
console.log("Removed from selection ", this.options[prevSelected[i]].text);
}
}
prevSelected = currentlySelected;
};
​
If you really only want to know which item was last clicked, you can use the following code. I'll use jQuery so I can easily set a handler on all the option objects. Remember this won't work if you change the selection with the keyboard
$('option').click(function(e){
var parentNode = this.parentNode;
for (var i=0; i < this.parentNode.options.length; i++) {
if (parentNode.options[i] == this) {
console.log('Clicked item with index', i);
break;
}
}
});
You could check the value of the selected options before a change event (e.g. item 1 and 2 are selected) and then again after the event (e.g. item 1, 2 and 3 are selected), and compare the difference.
Here is an example.
Fiddle here: http://jsfiddle.net/FnAuz/4/
I modified your select to allow multiple selections since I take it that's the crux of the problem.
HTML:
<form id="my-form">
<select name = "options" id="options" multiple>
<option value = "val1">Item1</option>
<option value = "val2">Item2</option>
<option value = "val3">Item3</option>
<option value = "val4">Item4</option>
</select>
</form>​
JS:
var oldValue = "";
document.getElementById('options').onchange = function() {
var myForm = document.getElementById ('my-form');
var value = "";
for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
if(myForm.elements[0][intLoop].selected) {
value = value + myForm.elements[0][intLoop].value;
}
}
for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
var optionVal = myForm.elements[0][intLoop].value;
if(myForm.elements[0][intLoop].selected && value.indexOf(optionVal) !== -1 && oldValue.indexOf(optionVal) === -1) {
console.log('Last clicked was ' + myForm.elements[0][intLoop].value)
}
}
oldValue = value;
};
EDIT: I just noticed that my example works when the user makes command/ctrl selections, but if they make a shift selection then ALL the new values will be counted as the 'last clicked item'. So my code would need some work to account for this scenario. I'm out of time, but hopefully my code is useful in its current state nevertheless!
Try this :
var e = document.getElementById("ID_of_Select_Element");
var _selectedValue= e.options[e.selectedIndex].value;
It started looking messy so I'm posting it as an answer:
<html>
<head>
<script type="text/javascript">
<!--
var value = '0';
document.getElementById('options').onchange = function() {
value = parseInt(value) + parseInt(this.value);
alert(value);
}
-->
</script>
</head>
<body>
<select name="options" id="options">
<option value = "1">Item1</option>
<option value = "2" selected>Item2</option>
<option value = "4">Item3</option>
<option value = "8">Item4</option>
</select>
</body>
</html>
Edition for selecting multiple items:
well, if you want to accumulate items you can assign binary IDs to each product and then you can extract all the selected products from the total. for example, if the total is: 7 you can easily translate it to a binary string "111" which means they selected items 1,2,4. Sounds a bit crazy, I know, just an idea ;)

auto complete to select option in javascript

I am trying to make auto complete to select option according to input from the user
something like
<input type=text onkeyup=findit()>
<select id="sel">
<option value="s0001">Adams</option>
<option value="s0002">Alder</option>
.
.
.
<select>
I found this code 'but it only work on one select in the page( I need multi select)
<html>
<head>
<script type="text/javascript">
//initialize some global variables
var list = null;
function fillit(sel,fld) {
var field = document.getElementById("entry");
var selobj = document.getElementById("sel");
if(!list)
{
var len = selobj.options.length;
field.value = "";
list = new Array();
for(var i = 0;i < len;i++)
{
list[i] = new Object();
list[i]["text"] = selobj.options[i].text;
list[i]["value"] = selobj.options[i].value;
}
}
else
{
var op = document.createElement("option");
var tmp = null;
for(var i = 0;i < list.length;i++)
{
tmp = op.cloneNode(true);
tmp.appendChild(document.createTextNode(list[i]["text"]));
tmp.setAttribute("value",list[i]["value"]);
selobj.appendChild(tmp)/*;*/
}
}
}
function findIt(sel,field)
{
var selobj = document.getElementById("sel");
var d = document.getElementById("display");
var len = list.length;
if(field.value.length > 1)
{
if(!list)
{
fillit(sel,field);
}
var op = document.createElement("option");
selobj.options.length = 1
var reg = new RegExp(field.value,"i");
var tmp = null;
var count = 0;
var msg = "";
for(var i = 0;i < len;i++)
{
if(reg.test(list[i].text))
{
// d.childNodes[0].nodeValue = msg;
tmp = op.cloneNode(true);
tmp.setAttribute("value",list[i].value);
tmp.appendChild(document.createTextNode(list[i].text));
selobj.appendChild(tmp);
}
}
}
else if(list && len > selobj.options.length)
{
selobj.selectedIndex = 0;
fillit(sel,field);
}
}
</script>
</head>
<body onLoad="fillit(sel,entry)">
<div>Enter the first three letters of a street and select a match from the menu.</div>
<form>
Street
<input type="text" name="Street" id="entry" onKeyUp="findIt(sel,this)"><br>
<select id="sel">
<option value="s0001">Adams</option>
<option value="s0002">Alder</option>
<option value="s0003">bol</option>
<option value="s0004">col</option>
<option value="s0005">dol</option>
<option value="s0007">Cooper</option>
<!--and so on and so forth-->
</select>
</form>
</body>
Any Ideas How to make it work on multi select on the page?
Thanks
Baaroz
Not sure if this would work for you, but chosen.js has a really nice autocomple multi select
http://harvesthq.github.com/chosen/
Usually Autocomplete is for single values, but the jQuery UI autocomplete does have a multiple select function. Perhaps try that? Minimum effort coding for you that way.
An odd way to do that is to change the ID in the script and copy it the number of times you want to use this options in the page. so for example:
select id="sel1"
select id="sel2"
select id="sel3"
and then. copy the script and replace every (sel) with sel1 past it again and replace (sel) with sel2 and so on.
not the best solution but it will work.
Good Luck

Forcing SELECT with chosen to refresh after changing option's selected property

On a old project I use jQuery v1.7.1 and Chosen 0.9.8 (updated to 0.9.10 but nothing changes).
I have some SELECT each with 21 options, and I need to select / unselect some options with JavaScript every time the user clicks on a checkbox.
I do it and I see the changes inspecting the page.
I don't see anything changing in the SELECT, like trigger("liszt:updated") does nothing.
Any Idea?
Here is the HTML (simplyfied):
#for (int i = 0; i < Model.SoasEsitiLavori.Count(); i++)
{
SoaModel soa = Model.SoasEsitiLavori[i];
<tr>
<td>
<select id="SoasEsitiLavori[#i]._RegioniEsiti" multiple="multiple"
name="SoasEsitiLavori[#i]._RegioniEsiti"
class="regionilavori chzn-select" >
#foreach (XRegione reg in ViewBag.ElencoRegioni)
{
<option value="#reg.IDRegione">#reg.Regione</option>
}
</select>
</td>
</tr>
}
Here is the Javascript (simplyfied):
function CheckRegioneClick(RegioneCheck) {
var CurrentChecked = RegioneCheck.checked;
var CurrentValue = RegioneCheck.value;
//Extracts a list of "SELECT"
var regioni = document.getElementsByClassName('regionilavori');
for (z = 0; z < regioni.length; z++) {
var r = regioni[z];
var r1 = document.getElementById(r.id);
var ao = r1.getElementsByTagName('option');
for (var i = 0; i < ao.length; i++) {
if (ao[i].value == CurrentValue) {
ao[i].selected = CurrentChecked;
//This SHOULD update the SELECT, but nothing happens
$(r.id).trigger("liszt:updated");
}
}
$(r.id).trigger("liszt:updated");
$(r.id).val(CurrentValue).trigger("liszt:updated");
}
}
}
How can i force the SELECT to refresh?
You can use $('select').trigger('chosen:updated');
for further reference please check
https://harvesthq.github.io/chosen/options.html
Your issue is here:
$(r.id)
The right jQuery selector by ID need a pound prefix, hence:
$('#' + r.id)
$("#RegioniEsiti").chosen();
var regioni = document.getElementsByClassName('regionilavori');
var CurrentChecked = true;
var CurrentValue = '1';
for (z = 0; z < regioni.length; z++) {
var r = regioni[z];
var r1 = document.getElementById(r.id);
var ao = r1.getElementsByTagName('option');
for (var i = 0; i < ao.length; i++) {
if (ao[i].value == CurrentValue) {
ao[i].selected = CurrentChecked;
//This SHOULD update the SELECT, but nothing happens
//$('#' + r.id).trigger("liszt:updated");
}
}
$('#' + r.id).trigger("liszt:updated");
$('#' + r.id).val(CurrentValue).trigger("liszt:updated");
}
.regionilavori {
width: 350px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/0.9.10/chosen.min.css">
<script src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/0.9.10/chosen.jquery.min.js"></script>
<select id="RegioniEsiti" multiple="multiple" name="RegioniEsiti" class="regionilavori chzn-select">
<option value="1">Campania</option>
<option value="2">Lombardia</option>
<option value="3">Toscana</option>
<option value="4">Lazio</option>
</select>
You have select multiple so each time you select option you got array of values as result.
you can check this test for your case.
$("#RegioniEsiti").chosen();
$('body').on('click', '.search-choice-close', function(event) {
var close = $(event.currentTarget)
var option = $("#RegioniEsiti option")
$(option[close.attr('rel')]).removeAttr('selected');
});
$("#RegioniEsiti").on('change',function() {
var $this = $(this);
$($this.val()).each(function(v,val) {
$this.find("option[value="+val+"]").attr("selected","selected");
});
});

Categories