Storing an Array of values in a single checkbox? - html

Is it possible to store multiple values in a single checkbox?
For instance:
<input type="checkbox" value="[0,2]">
<input type="checkbox" value="[3,6]">
<input type="checkbox" value="[7,10]">
...

Without any example code to go off of, I have no idea what your endstate needs to be. Here is an example that will update an array every time you check or uncheck a box, and log the resulting array to the console. N.B...
this uses jQuery to listen for the changes
each array is broken down into its component elements and then stored in a flat array, as opposed to being stored as an array of arrays
there is no sorting of the array elements
elements are stored as text and not numbers
Depending on what you need, this may or may not matter to you.
var arr = [];
$('#check input').change(function() {
var temp = (this.value).split(",");
if (arr.indexOf(temp[0]) == -1) {
arr.push(temp[0],temp[1]);
} else {
var pos = arr.indexOf(temp[0]);
arr.splice(pos, 2);
}
console.log(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="check">
<input type="checkbox" value="0,2">[0,2]<br />
<input type="checkbox" value="3,6">[3,6]<br />
<input type="checkbox" value="7,10">[7,10]
</div>

Related

Is there a way to create an option on an HTML form to allow a user to select exactly 2 of n choices?

I am trying to build an HTML form. For one of the questions, I want the user to be able to select exactly two choices.
I tried building two radio questions (which I understand only accept one choice) with the same 4 options, but I don't want the user to be able to select the same option twice.
<form action = "\new" method = post target="_blank" id="form">
<option>Option 1</option><br>
Question 1:
<input type="radio" name="S1" value = 0 checked>C1<br>
<input type="radio" name="S1" value = 1>C2<br>
<input type="radio" name="S1" value = 2>C3<br>
<input type="radio" name="S1" value = 3>C4<br>
<br>
Question 2:
<input type="radio" name="S2" value = 0 checked>C1<br>
<input type="radio" name="S2" value = 1>C2<br>
<input type="radio" name="S2" value = 2>C3<br>
<input type="radio" name="S2" value = 3>C4<br>
</form>
//I want the form to output (S1,S2), but S1 cannot equal S2
With this code, the user can still choose the same choice for both questions. How do I fix this?
I figured it out. I added this JavaScript at the bottom of the HTML document.
<script>
function validate(){
var C1 = Number($("input[name='S1']:checked").val());
var C2 = Number($("input[name='S2']:checked").val());
if (C1==C2){
return false;
}
return true;
}
function init(){
document.getElementById('form').onsubmit = validate;
}
window.onload = init;
</script>
Hope this helps anyone else who was struggling like me!

Submit form using dynamicallly added fields with the same name in ASP.NET

I have a ASP.net Web page using VB as the language, I have created a form where it asks for 3 different input fields as follows, but the user has the option to add these three fields again for multiple form inputs to make their lives easier and this task faster.
<label>Test Number: <input type="text" id="test_number.1" name="test_number.1" value=""/>
</label>
<label>
Score: <input type="text" name="score.1" id="score.1" placeholder="Required" value="" />
</label>
<label>Comments:<input type="text" name="comments.1" id="comments.1" value="," placeholder="Comments Necessary for future reference" size="70" />
Looking at the submission of the data via firebug this is what it's posting to the serve if you submit only one set of fields.
test_number.1=12555&score.1=75&comments=testing
Looking at the submission of the data via firebug this is what it's posting to the serve if you submit multiple set of fields.
test_number.1=12555&score.1=75&comments=testing&test_number.1=12555&score.1=75&comments=testing&test_number.1=12555&score.1=75&comments=testing
Now I need to insert these values into a database, I know how to do this via PHP utilizing [] and then dealing with it on the backend. But I'm still learning asp.net and seem to be having some major issues on how to get this to work. If anyone can help that would be great.
Solution can be:
1st set of controls:
<input type="text" name="testnumber" />
<input type="text" name="testscore" />
<input type="text" name="testcomments" />
add next set
<input type="text" name="testnumber" />
<input type="text" name="testscore" />
<input type="text" name="testcomments" />
and so one.
On server side:
var testnumbers = Request["testnumbers"];// comma seperated values
var testscores = Request["testnumbers"];// comma seperated values
var testcomments = Request["testcomments"]; // comma seperted values.
split all values by comma. you will get array of values for each
string[] testnoList = testnumbers.split(',');
string[] testscoresList = testscores .split(',');
string[] testcommentsList = testcomments .split(',');
for(int i=0; i<testnoList.Lenght; i++)
{
var testno = testnoList[i];
var score = testscoresList[i];
var comments = testcommentsList[i];
// do whatever you want here
}

Passing data from an HTML form via an array to $_POST

The following is written in ASP.NET Razor.
I have a page that dynamically creates lines in an HTML form based on results from a database query. Each row in the result set corresponds to one row in the form. Each row has two input fields that I need to be able to pass via $_POST.
foreach (var #row in list) {
<li>
<span style="width: 100px; display: inline-block">#row.Name</span>
<input type="text" name="time[]" />minutes on
<input type="text" name="date[]" />
</li>
}
My expectation is that I would then be able to access and iterate over the data like this:
var timeList = Request.Form["time"];
foreach (var time in timeList) {
// Stuff
}
But this isn't working. I keep getting an "Object reference not set to an instance of an object" error for timeList. Is what I'm trying to do even possible? Any idea what's wrong?
Try removing the square brackets from your names:
foreach (var #row in list) {
<li>
<span style="width: 100px; display: inline-block">#row.Name</span>
<input type="text" name="time" />minutes on
<input type="text" name="date" />
</li>
}
The loop will create duplicate names which forms arrays in HTML, so you get what you want. However, I'm not sure if that will work when the list has a single item, so test that.
Client HTML:
<form action="~/Page" method="post">
<input type="hidden" name="product_0_id" value="0" />
<input type="text" name="product_0_name" value="Prod. #1" />
<input type="hidden" name="product_1_id" value="1" />
<input type="text" name="product_1_name" value="Prod. #2" />
</form>
Server:
string youGroupKey = "product";
Dictionary<string, string>[] values = Request.Form
.AllKeys
.Where(k => k.StartsWith(youGroupKey))
.GroupBy(k => k
.Substring(youGroupKey.Length + 1, 1),
(a, b) => {
return b
.ToDictionary(c => c
.Substring(youGroupKey.Length + 3), d => Request.Form[d]);
}
)
.ToArray();

Is there a way to capture multiple checkboxs and select box items?

a I have a very large form with a lot of ckeckbox and a select multiple list.
All this options are like something like this:
<input type="checkbox" name="chk1" id="chk1" />chk1<br />
<input type="checkbox" name="chk2" id="chk2" />chk2<br />
<input type="checkbox" name="chk3" id="chk3" />chk3<br />
<input type="checkbox" name="chk4" id="chk4" />chk4<br />
<input type="checkbox" name="chk1_group2" id="chk1_group2" />A<br />
<input type="checkbox" name="chk2_group2" id="chk2_group2" />B<br />
<input type="checkbox" name="chk3_group2" id="chk3_group2" />C<br />
<input type="checkbox" name="chk4_group2" id="chk4_group2" />D<br />
My idea is to take al the values and save them in one sigle value like this:
String chk = "chk1, chk2, chk3";
String chk_group2 = "A,B,D";
I'm looking for a loop that can take all the vaules from the request and put the values in a sigle string. I'm tried whith List but it's not working.
I'm using JSP and a Oracle 10g DB
THK
I would first give every checkbox a "group" attribute (or something equally distinguishing), to specify what group it should represent, like so :
...
<input type="checkbox" group="group1" name="chk4" id="chk4" />chk4<br />
<input type="checkbox" group="group2" name="chk1_group2" id="chk1_group2" />A<br />
...
then parse them with something like this:
var group1 = [];
var group2 = [];
function parseSelected(){
// maybe a more specific query for this
var checkboxes = document.getElementsByTagName("input");
for (var i=0; i<checkboxes.length; i++) {
var checkbox=checkboxes[i];
// if its not checked, continue...
if(!checkbox.checked) continue;
if(checkbox.getAttribute("group")=="group1"){
group1.push(checkbox.getAttribute("name"));
} else if(checkbox.getAttribute("group")=="group2"){
group2.push(checkbox.getAttribute("name"));
}
}
}
and on some event somewhere (form submit possibly?)
parseSelected();
var strGroup1 = group1.join(', ');
var strGroup2 = group2.join(', ');
Since I stumbled upon this question.. even though it's been posted a long time, others may find it helpful as well.
You can access the checkboxes easily using jquery.each; e.g:
$(document).ready(function () {
$('th input[type=checkbox]').each(function() {
$(this).click(function (e) {
var table = $(e.target).closest('table');
$('td input:checkbox', table).prop('checked', this.checked);
});
});
});

How to find duplicate id's in a form?

I've created a form with about 800 fields in it. Unknowingly I've given same id for few fields in the form. How to trace them?
The http://validator.w3.org/ will be the handy solution. But using jquery you can do something like this:
//See your console for duplicate ids
$('[id]').each(function(){
var id = $('[id="'+this.id+'"]');
if(id.length>1 && id[0]==this) {
console.log('Duplicate id '+this.id);
alert('duplicate found');
}
});
Hope this helps.
This might help you
Source: Finding duplicate ID’s on an HTML page
Finding duplicate ID’s on an HTML page
Written by Eneko Alonso on May 6, 2011
Looks like sometimes we forgot element ID’s
are meant to be unique on a HTML page. Here is a little bit of code I
just wrote to find duplicate ID’s on a page (run the code on your
browser’s javascript console):
var idList = {};
var nodes = document.getElementsByClassName('');
for (var i in nodes) {
if (!isNaN(i) && nodes[i].id) {
idList[nodes[i].id] = idList[nodes[i].id]? idList[nodes[i].id]+1:1;
}
}
for (var id in idList) {
if (idList[id] > 1) console.log("Duplicate id: #" + id);
}
I've created an example for you to have a look at, it finds all of the duplicate IDs within a form/element on a page and prints the duplicates ID names to the console.
The array contains method was taken from this post.
<html>
<body>
<form id="frm">
<input type="text" id="a" />
<input type="text" id="b" />
<input type="text" id="c" />
<input type="text" id="d" />
<input type="text" id="e" />
<input type="text" id="f" />
<input type="text" id="a" />
<input type="text" id="h" />
<input type="text" id="i" />
<input type="text" id="j" />
<input type="text" id="d" />
<input type="text" id="l" />
</form>
</body>
<script type="text/javascript">
Array.prototype.contains = function(obj) { //Add a 'contains' method to arrays
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
frm = document.getElementById('frm'); //Get the form
els = frm.getElementsByTagName('input'); //Get all inputs within the form
ids = new Array(els.length); //Create an array to hold the IDs
for(e = 0; e < els.length; e++) { //Loop through all of the elements
if(ids.contains(els[e].id)) //If teh array already contains the ID we are on
console.log('Duplicate: '+els[e].id); //Print 'Duplicate: {ID}' to the console
ids.push(els[e].id); //Add the ID to the array
}
</script>
</html>
The above code will output the following:
Duplicate: a
Duplicate: d
One-ish liner using just array methods:
[].map.call(document.querySelectorAll("[id]"),
function (e) {
return e.id;
}).filter(function(e,i,a) {
return ((a.lastIndexOf(e) !== i) && !console.log(e));
})
Logs every duplicate and returns an array containing the ids if any were found.
There is a Chrome extension named Dup-ID which if you install, you just need to press the button to check duplicated ids.
Link of install: https://chrome.google.com/webstore/detail/dup-id-scans-html-for-dup/nggpgolddgjmkjioagggmnmddbgedice
By defualt Notepad++ has syntax highlighting that if you double click one word to select it, it will highlight all other occurences of the same word. You are going to have to do some (probably a lot) of manual work renaming things, I mean since fields can't come up with their own unique name.