Extracting values from <select> and putting them into an array - javascript

Surely, this shouldn't be so hard?
I have a <select>, which has, of course, <options>. These options are always in number format, because they are dynamically added to the list by the user.
I then need to get all of these options from the list, put them an array and then perform logic on the array. I've tried searching around, but everything relates to jquery or php - and I'm using plain old HTML and JavaScript.
The select is in a scrolling-box format:
<select id="selectBox" name="select" size="15" style="width:190px;">
<!-- <options> are added via javascript -->
</select>
Currently, I'm using this JavaScript to get the elements, but it's not working:
//Calculate all numbers
var x=[];
function calculate()
{
for (var i = 0; i < 999; i++)
{
x[i]=selectbox.options[i].value;
alert(x[i]);
}
}
Calculate() is called by a button. Something is going terribly wrong, and I can't work it out. selectbox is previously defined as var selectbox = document.getElementById("selectBox"); and I know this works.
The alert is only being called so I can try to debug the thing...
I'm using the figure of 999 because I can't work out how to get a number of how many elements are in the <select> (because it is in scrolling-box format).
The solution must be javascript, and the listbox must be in that scrolling-box format.
Thanks in advance for your help!
Edit -- Okay, more coding to help this.
<form id="aggregateForm">
<input id="inputNum" value="" type="text"><input id="addnum" value="Add" onclick="add();" type="button">
<br>
<select id="selectBox" name="select" size="15" style="width:190px;">
</select>
<br>
<input id="calculate" value="Calculate" onclick="calculate();" type="button"><input id="reset" value="Reset" onclick="reset();" type="button">
</form>
<script type="text/javascript">
var selectbox = document.getElementById("selectBox");
function add()
{
//Function to add a new number to the list of digits
//Parses an integer to ensure everything works okay
if(IsNumeric(document.getElementById("inputNum").value) == true)
{
selectbox.options[selectbox.options.length] = new Option(document.getElementById("inputNum").value, document.getElementById("inputNum").value);
inputNum.focus();
}
else if(IsNumeric(document.getElementById("inputNum").value) == false)
{
alert("I'm sorry, but you have entered an invalid number. Please enter a number into the input box.");
inputNum.focus();
}
}
//Calculate all numbers
var x=[];
function calculate()
{
for (var i = 0; i <selectbox.options.length; i++)
{
x[i]=selectbox.options[i].value;
alert(x[i]);
}
}
//IsNumeric function coding taken from http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric, code by Joel Coehoorn
function IsNumeric(input)
{
return (input - 0) == input && input.length > 0;
}
</script>

The problem is that calculate is the ID of the element too. And oddly enough it believes that calculate is that DOM object not you function: proof. I changed the function name to calculates.
I only found out last week that you can reference your elements with IDs with said IDs.
<div id="really">Yep for some reason</div>
... later in javascript
// no document.getElementById, just
// let me be very clear, THIS IS WRONG TO USE VERY BAD SO EVERYONE CAN KNOW NOT TO USE THIS
// but it does work this way so be aware
really.innerHTML = "I guess he was right.";

check this jsfiddle
var selectbox = document.getElementById("selectBox");
var x = [];
function calculate()
{
for (var i = 0; i <selectbox.options.length; i++)
{
x[i]=selectbox.options[i].value;
alert(x[i]);
}
}
calculate();
This will alert EVERY option element in the select.

Related

Code made elements don't show on onload?

I've been tasked with a demo for a query API our company has. For that, my boss wanted me to create a simple HTML site containing a search feature to use said API. So far, I've managed to create almost everything she wanted, but am now stuck on a rather... Peculiar problem.
I've managed to create a flexible filtering feature, allowing the user to add/remove filters as they see fit. I've done it like this:
window.onload = function init()
{
var filterSet = document.getElementsByTagName("fieldset")[0];
var filterSection = filterSet.getElementsByTagName("section");
var set = filterSection[1];
var elements = set.getElementsByTagName("*");
set.getElementsByTagName("*")[5].addEventListener("click", cloneSection);
if (filterSection.length > 2)
{
elements[6].hidden = false;
elements[6].addEventListener("click", deleteSection);
}
else
{
elements[6].hidden = true;
}
}
function cloneSection(e)
{
var filterSet = document.getElementsByTagName("fieldset")[0];
var filterSection = filterSet.getElementsByTagName("section");
var newId = parseInt(filterSection[filterSection.length - 1].id) + 1;
var set = filterSection[1];
var newSet = set.cloneNode(true);
var elements = newSet.getElementsByTagName("*");
newSet.id = "" + newId;
elements[5].addEventListener("click", cloneSection);
elements[6].hidden = false;
elements[6].addEventListener("click", deleteSection);
filterSet.appendChild(newSet);
}
function deleteSection(e)
{
var target = e.target;
var filterSet = document.getElementsByTagName("fieldset")[1];
var filterSection = target.parentElement;
filterSection.remove();
}
<fieldset>
<section>
<input type="checkbox" id="filter_query" name="feature" value="search" />
</section>
<section id="0">
<input type="text" name="filter_name">
<select id="comperason_type">
<option value="=">Equal to</option>
<option value="!=">Different then</option>
</select>
<input type="text" name="filter_value">
<input type="submit" value="+" id="AddButton">
<input type="submit" value="-" id="RemoveButton" hidden="true">
</section>
</fieldset>
It's rather basic (I'm kinda new to networking and Javascript as a whole, I'll admit), but for the most part it works just fine. Except for one single issue.
I want, when the user adds a new filter, to allow them to remove the default one created by the original markup. The button is there, I just need to set it to hidden = false and that's it. Except... When I try to do that, for some reason, the code doesn't recognize the extra section created into it. For example, if there are 3 sections in the fieldset, one created by my own code, the length count will only return 2.
Does anyone know why? Or what can I do to get it to count properly? I'm sorry if this is a newb question, but like I said, I'm a bit out of my depth here.
EDIT: Made a snippet that works this time. Sorry for making it confusing, but it should be good now.

Multidimensional Array Not Updating (or is it...?)

I have the most peculiar issue I can't seem to solve without writing band-aid code.
FULL SOURCE:
http://sinsysonline.com/tictactoe_test.html
or Fiddle:
http://jsfiddle.net/JsXEP/
I am using a multidimensional array for the JS and a table for the HTML for data and display purposes.
So, our data will look something like this for JS:
var b = [ ["","",""], ["","",""], ["","",""] ];
The table will be a standard table with some CSS tweaks for our HTML:
<table id="board">
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
</table>
So, here is the problem. The input works just fine, resetting the game appears to work fine, but let's make a use-case so I can demonstrate the problem.
If I utilize a grid size of 3 initially, then try to make a game with a grid size of 4 without refreshing the page, the data seems to display at the top right for my array that the code is working as intended.
However, when you console.log(b), it never actually updates b and anything after the first three rows in the table don't respond.
I'm given a console error of:
TypeError: b[row] is undefined
Why isn't b actually updating with the increased value, even though I define it as var b=[]; at the beginning of my click-handler for #go?
And why is my #alert box for debugging filling in the correct b value?
Scratches Head
Any help is appreciated...
HTML:
<div id="dashboard">
<p>How large is your grid? (3-10)</p>
<input type="text" id="size" size="1" />
<p>Which icon would you like?</p>
<select name="mydropdown" id="mark">
<option value="check">Check-Mark</option>
<option value="x">Traditonal X</option>
<option value="o">Traditional O</option>
</select>
<h3 id="title">Troubleshooting Console</h3>
<input type="button" id="go" value="Create Board / Reset" />
<p id="alert">Alerts Live Here</p>
</div>
<table id="board">
</table>
Javascript:
$("#go").click(function () {
var b=[],
s = parseInt($("#size").val()),
v = $("#mark").val();
if (s<3 || s>10) { alert("That is not a valid input. Please select 3-10"); return; }
$('#board tr').remove();
$('#alert').text("Your Turn!");
for (var i = 0; i < s; i++) {
var t = [];
var $tr = $('<tr />').data('index', i + 1);
for (var j = 0; j < s; j++) {
t[j] = "";
$('<td />').data('index', j + 1).appendTo($tr);
}
b.push(t);
$("#board").append($tr);
}
$("#board").on('click', 'td', function () {
var $td = $(this),
td = $td.data('index')-1,
row = $td.parent().data('index')-1;
b[row][td] = "X";
$td.removeClass().addClass(v);
$('#alert').text(b);
});
});
FULL SOURCE:
http://sinsysonline.com/tictactoe_test.html
or Fiddle:
http://jsfiddle.net/JsXEP/
The problem is because of the closure property and multiple definitions of on click function. Updated Fiddle
$("#board").on('click', 'td', function () {
var $td = $(this),
td = $td.data('index')-1,
row = $td.parent().data('index')-1;
b[row][td] = "X";
$td.removeClass().addClass(v);
$('#alert').text(b);
});
This function is registered every time user changes the settings and whenever it is defined, it captures the b. So, first time, lets say, b is [3][3] and the on click function is created with that. Next time, b is [4][4] and a new on click function is created (old one still exists, with b [3][3]). So both of them are fired now onwards. If I select anything outside 3 x 3, the old one fails. That's why you are facing this problem.
So, I just moved the definition of on click function, b and v outside and it works fine now.

How can I count the total number of inputs with values on a page?

I'm hoping for a super simple validation script that matches total inputs on a form to total inputs with values on a form. Can you help explain why the following doesn't work, and suggest a working solution?
Fiddle: http://jsfiddle.net/d7DDu/
Fill out one or more of the inputs and click "submit". I want to see the number of filled out inputs as the result. So far it only shows 0.
HTML:
<input type="text" name="one">
<input type="text" name="two">
<input type="text" name="three">
<textarea name="four"></textarea>
<button id="btn-submit">Submit</button>
<div id="count"></div>
JS:
$('#btn-submit').bind('click', function() {
var filledInputs = $(':input[value]').length;
$('#count').html(filledInputs);
});
[value] refers to the value attribute, which is very different to the value property.
The property is updated as you type, the attribute stays the same. This means you can do elem.value = elem.getAttribute("value") to "reset" a form element, by the way.
Personally, I'd do something like this:
var filledInputs = $(':input').filter(function() {return !!this.value;}).length;
Try this: http://jsfiddle.net/justincook/d7DDu/1/
$('#btn-submit').bind('click', function() {
var x = 0;
$(':input').each(function(){
if(this.value.length > 0){ x++; };
});
$('#count').html(x);
});

Move Options Up / Down List-box JavaScript / ASP

Hi I'm trying to learn javascript and I'm messing around with this example I found:
function moveOptionUp(obj) {
if (!hasOptions(obj)) { return; }
for (i = 0; i < obj.options.length; i++) {
if (obj.options[i].selected) {
if (i != 0 && !obj.options[i - 1].selected) {
swapOptions(obj, i, i - 1);
obj.options[i - 1].selected = true;
}
}
}
}
I have a list box
<input type="button" value="Up" onclick="moveOptionUp(this.form['_lb2'])" />
<asp:ListBox ID="_lb2" name="_lb2" runat="server" Height="400px" Width="170px"/>
However I can't get it to work ... The example uses a html select box. I think the problem is with passing in the control as a parameter. What is the correct way to do this using asp controls.
Ohh BTW .. List box items are added dynamically
To move an option up one, insert it as the previous sibling of the previous option (provided it isn't the top one already):
function moveUp(sel) {
var idx = sel.selectedIndex;
var opt;
// Only move up if not first
if (idx > 0) {
opt = sel.options[idx];
sel.insertBefore(opt, sel.options[--idx]);
}
}
Changed the test to check that idx > 0 since if no option is selected the selectedIndex will be -1. That may happen if there is no defalut selected option and the form is reset.
Edit
Sample HTML:
<form action="">
<select id="_lb2" name="_lb2">
<option>0
<option>1
<option>2
<option>3
</select>
<input type="button" value="Move Up" onclick="
moveUp(this.form['_lb2']);
">
</form>
I think the problem is with passing in the control as a parameter
Indeed...
change
onclick="moveOptionUp(this.form['_lb2'])"
to
onclick="moveOptionUp(document.getElementById('_lb2'))"
btw, (and you may already know this) an id of _lb2 is not considered valid

Select values of checkbox group with jQuery

I'm using Zend_Form to output a set group of checkboxes:
<label style="white-space: nowrap;"><input type="checkbox" name="user_group[]" id="user_group-20" value="20">This Group</label>
With a normal HTTP Post these values are passed as an array, but when I'm somewhat stumped on how to grab all the values using jQuery. I figured I can select the group using:
$("input[#name='user_group[]']").val()
but that just grabs the value of the first checkbox in the list regardless of if it is checked of not. Any ideas?
You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):
$("input[name='user_group[]']:checked")
With those checked items, you can either create a collection of those values or do something to the collection:
var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
values.push($(this).val());
// or you can do something to the actual checked checkboxes by working directly with 'this'
// something like $(this).hide() (only something useful, probably) :P
});
I'm not sure about the "#" used in the selector. At least with the latest jQuery, I had to remove the # to get this to function with two different checkbox arrays, otherwise all checked items were selected for each array:
var items = [];
$("input[name='items[]']:checked").each(function(){items.push($(this).val());});
var about = [];
$("input[name='about[]']:checked").each(function(){about.push($(this).val());});
Now both, items and about work.
Use .map() (adapted from the example at http://api.jquery.com/map/):
var values = $("input[name='user_group[]']:checked").map(function(index,domElement) {
return $(domElement).val();
});
With map in instead of each it is possible to avoid the array creation step:
var checkedCheckboxesValues =
$('input:checkbox[name="groupName"]:checked')
.map(function() {
return $(this).val();
}).get();
From the map() page of the docs:
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values
get() turns those values into an array.
mhata dzenyu mese. its actually
var selectedGroups = new Array();
$(".user_group[checked]").each(function() {
selectedGroups.push($(this).val());
});
I just shortened the answer I selected a bit:
var selectedGroups = new Array();
$("input[#name='user_group[]']:checked").each(function() {
selectedGroups.push($(this).val());
});
and it works like a charm, thanks!
I'm not 100% entirely sure how you want to "grab" the values. But if you want to iterate over the checkboxes you can use .each like so:
("input[#name='user_group[]']").each( function() {
alert($(this).val());
});
Of course a better selector is available:
$(':checkbox')
var values = $("input[name='user_group']:checked").map(function(){
return $(this).val();
}).get();
This will give you all the values of the checked boxed in an array.
You can have a javascript variable which stores the number of checkboxes that are emitted, i.e in the <head> of the page:
<script type="text/javascript">
var num_cboxes=<?php echo $number_of_checkboxes;?>;
</script>
So if there are 10 checkboxes, starting from user_group-1 to user_group-10, in the javascript code you would get their value in this way:
var values=new Array();
for (x=1; x<=num_cboxes; x++)
{
values[x]=$("#user_group-" + x).val();
}
$(document).ready(function(){
$('#btnskillgroup').click(function(){
getCheckedGroups('skills');
});
$('#btncitiesgroup').click(function(){
getCheckedGroups('cities');
});
var getCheckedGroups = function(groupname){
var result = $('input[name="'+groupname+'"]:checked');
if (result.length > 0) {
var resultstring = result.length +"checkboxes checked <br>";
result.each(function(){
resultstring += $(this).val()+" <br>"; //append value to exsiting var
});
$('#div'+groupname).html(resultstring);
}else{
$('#div'+groupname).html(" No checkbox is Checked");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Skills:<input type="checkbox" name="skill" value="Java"> Java
<input type="checkbox" name="skill" value="Jquery"> Jquery
<input type="checkbox" name="skill" value="PHP"> PHP
<br>
<input type="checkbox" name="cities" value="Pune"> Pune
<input type="checkbox" name="cities" value="Baramati"> Baramati
<input type="checkbox" name="cities" value="London"> London
<input type="submit" id="btnskillgroup" value="Get Checked Skill group">
<input type="submit" id="btncitiesgroup" value="Get cities checked group">
<div id="divskills"></div>
<div id="divcities"></div>

Categories

Resources