Is it possible to collect data on checked or unchecked tick boxes in HTML?
I'm looking at creating a very simple HTML page that contains an HTML form with a series of check boxes and input fields. The page would be roughly like so:
Input Forename ==== Input Surname ==== Input ID =====
Text checkbox1 value1 Text
Text checkbox2 value2 Text
Text checkbox3 value3 Text
Text checkbox4 value4 Text
Output Text value
Output Text value
Output Text value
Output Text value
Depending on which values are ticked (i.e. value 1/2/3/4), the value next to it is then calculated (for arguments sake let's say it's multiplied by 2) and then output below (where it says "Output text" value). Apologies if this doesn't match the "question" but you see what I mean by "collecting" data (i.e. the value next to the checkbox).
My question is thus, is it possible to use JavaScript to say, if tickbox1 is checked, please use "value1"? Once this is all completed the page just needs to have a "print" button (which is fine). There is no back end stuff that needs to happen and no data capture.
Hope this makes sense and thanks in 开发者_运维百科advance
EDIT:Of course if it's a lot easier to do this with something like JQuery I'd be happy to explore this!
This code should help you out!
Questions[] is an array with all the input fields in, getElementsByName goes through all the elements that have the same name (radio boxs for example all have the same name) and then finds out which one is checked, and then uses that value.
Answers[] is the array with the stored values in.
for (var i = 0; i < questions.length; i++) {
//Does the question name have more than one instance? (That would make it a checkbox or radio button...
if (document.getElementsByName(questions[i]).length > 1) {
//Lets loop through all these values and find out which one is selected, and then grab the value from it.
var x = document.getElementsByName(questions[i])
for(var k=0;k<x.length;k++)
if(x[k].checked){ //This is where it loops to find the checked answer
answers[i] = x[k].value;
//alert("radio saved " + answers[i]);
}
}
//Nope, only once, so its a text field or similar
else {
answers[i] = document.getElementById("answer" + questions[i]).value;
//alert("text saved " + answers[i]);
}
}
Hope this helps!
So to use this in your calculations (to say make it double) you could call
var answertoyourquestion = answers[i] + answers[i];
Well, you could try something like this(not tested):
var total = 0;
for (int i = 0;i < 10;i++)
{
var checkbox = document.getElementById("checkbox" + String.ValueOf(i));
if (checkbox.checked)
{
var valuebox = document.getElementById("value" + String.ValueOf(i));
total += (valuebox.value * 2);
}
}
精彩评论