how to use javascript to handle a large html checkbox? - javascript

So I have something like this inside a form
<input type="checkbox" name="arr" value="A" />A
<input type="checkbox" name="arr" value="B" />B
<input type="checkbox" name="arr" value="C" />C
<input type="checkbox" name="arr" value="D" />D
<input type="checkbox" name="arr" value="E" />E
...
<more checkboxes here>
...
In my Javascript I want to create an array that consists the values of boxes that are checked. So if B and D are checked it should be [B, D].
thanks
EDIT: My bad for not including a jQuery tag, but the guy who deleted his answer gave me a nice and short working solution using jQuery:
var valueArray = $('input[type="checkbox"][name="arr"]:checked').map(function() {
return this.value;
}).get();

Depending on what you're using it for, it may be enough to just use name="arr[]". When the form is submitted, the server-side will automatically convert the selected checkbox values to an array.
However, if you're trying to get this array purely in the client-side JavaScript, it's a little more involved. Try this:
function getCheckedBoxes(name) {
if( document.querySelectorAll) {
var qsa = document.querySelectorAll("input[type=checkbox][name='"+name+"']"),
l = qsa.length, i, out = [];
for( i=0; i<l; i++) if( qsa[i].checked) out.push(qsa[i].value);
}
else {
var qsa = document.getElementsByTagName('input'), l = qsa.length, i, out = [];
for( i=0; i<l; i++) {
if( qsa[i].type == 'checkbox' && qsa[i].name == name && qsa[i].checked)
out.push(qsa[i].value);
}
}
return out;
};

you could use jquery like this:
$("input[type=checkbox][name=arr][checked]").each(
function() {
// collect the values
}
);

Related

How to get the selected radio buttons value?

i am trying to get the value of selected radio buttons so i can submit my form using Ajax i searched here for some help but i couldn't find any useful solution
<input type="radio" id="answer" name="answer<?php echo $function::escape_string($question_row->question_id); ?>"
value="<?php echo $function::escape_string($answer_row>answer_id); ?>"/>
-HTML Output
<input type="radio" id="answer" name="answer16" value="107"/>
<input type="radio" id="answer" name="answer17" value="109"/>
<input type="radio" id="answer" name="answer15" value="104"/>
i found this function here
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert("Size is " + sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
var radioinputs = findSelection("answer");
But I do not know what to change so I can make it work with me properly
You can structure like this:
function findSelection(field) {
var test = document.getElementsByClassName(field);
var sizes = test.length;
//alert("Size is " + sizes);
result = [];
// result[16]=107;
// result[17]=109;
// result[15]=104;
for (i=0; i < sizes; i++) {
var index = test[i].dataset.index;
if(test[i].checked == true){
result[index] = test[i].value;
}else{
result[index] = undefined; // for a answer doesn't have a value
}
}
return result;
}
function checkfunction(){
var radioinputs = findSelection("radioanswer");
console.log(radioinputs);
console.log(radioinputs[15]);
};
<form id="form1">
<input type="radio" class="radioanswer" name="answer16" data-index="16" value="107"/>
<input type="radio" class="radioanswer" name="answer17" data-index="17" value="109"/>
<input type="radio" class="radioanswer" name="answer15" data-index="15" value="104"/>
<button type="button" onclick="checkfunction();"> Check </button>
</form>
A class can has multiple instances, but id has only one! And you can see document about data attributes here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
From the looks of it you have a dynamic name field, i.e. name="answer2", name="answer3", etc. Because of that your query document.getElementByName(field) will not find a field matching "answer".
To remedy this either get rid of the dynamic name or if you really need it then I would say add a class to all those radio buttons and use document.getElemenetsByClassName.

Looping through checkboxes with javascript

I have a number of checkboxes which I am wanting to check if they are checked (1) or not checked (0). I want to place the results in an array so that I can send them to the server to saved in a table. I have tried the below code:
<input class="publish" id="chkBox1" type="checkbox" checked>
<input class="publish" id="chkBox2" type="checkbox" checked>
<input class="publish" id="chkBox3" type="checkbox" checked>
<input class="publish" id="chkBox4" type="checkbox" checked>
<input class="publish" id="chkBox5" type="checkbox" checked>
<script>
$('#save-btn').click(function(evt){
evt.preventDefault();
var numberOfChBox = $('.publish').length;
var checkArray = new Array();
for(i = 1; i <= numberOfChBox; i++) {
if($('#chkBox' + i).is(':checked')) {
checkArray[i] = 1;
} else {
checkArray[i] = 0;
}
}
alert(checkArray);
});
</script>
but the alert outputs this:
,1,0,1,0,1,1
The values are correct except the first index in undefined. There are only a total of 5 checkboxes and yet the array is 6 indexes long. Why is this?
Try this efficient way bruvo :) http://jsfiddle.net/v4dxu/ with proper end tag in html: http://jsfiddle.net/L4p5r/
Pretty good link: https://learn.jquery.com/javascript-101/arrays/
Also in your html end your tag /> i.e.
<input class="publish" id="chkBox4" type="checkbox" checked>
rest should help :)
Code
var checkArray = new Array();
$('input[type=checkbox]').each(function () {
this.checked ? checkArray.push("1") : checkArray.push("0");
});
alert(checkArray);
As mentioned in the answers above the problem is with the index(i). But if you want to simplify the code further, How about the following code?
var checkArray = [];
$('input.publish').each(function () {
checkArray.push($(this).is(':checked'));
});
alert(checkArray);
Take into account that the first element you write is checkArray[1], as i starts with 1, instead of checkArray[0].
Replace checkArray[i] with checkArray[i-1] inside the for bucle

Tricky javascript logic

I wanna ask about little tricky javascript, this is about if/else if/else question.
I want make question about 'YES' or 'NO', this is the logic : If question1 is 'yes' and question2 is 'yes' and question3 is 'NO' the result is 'good', and if question1 is 'yes' and question2 is 'no' and question3 is 'yes'the result is 'not good'. I was make the code for this case but not working properly, this is my codes, i use checkbox in html for choice answers :
javascript
<script type="text/javascript">
var question1 = document.getElementById("a");
question2 = document.getElementById("b");
question3 = document.getElementById("c");
answer1 = document.getElementById("d");
answer2 = document.getElementById("e");
answer3 = document.getElementById("f");
answer4 = document.getElementById("g");
answer5 = document.getElementById("h");
answer6 = document.getElementById("i");
function TheResult(form){
if(question1 == answer1 && question2 == answer3 && question3 == answer6 ){
document.write('good');
}else if(question1 == answer1 && question2 == answer4 && question3 == answer5 ){
document.write('not good');
}else {
document.write('ERROR');
}
}
html
<form>
<p id = "a"><b>Question1</b></p>
<input type="checkbox" name="a1" value="YES" id = "d">YES
<input type="checkbox" name="a1" value="NO" id = "e">NO<br><br>
<p id = "b"><b>Question2</b></p>
<input type="checkbox" name="a2" value="YES" id = "f" >YES
<input type="checkbox" name="a2" value="NO" id = "g" >NO<br><br>
<p id = "c"><b>Question3</b></p>
<input type="checkbox" name="a3" value="YES" id = "h">YES
<input type="checkbox" name="a3" value="NO" id = "i">NO<br><br>
<input type="button" name="Submit" value="Result" style="margin-left:100px;" onClick="TheResult(this.form)" >
</form>
my codes always print out 'good' in every situation, please help.
I'm actually pretty confused by the logic that you're presenting. As many have pointed out, you're trying to compare elements against each other. This won't give you the result that you want. You'll want to use .innerHTML or .value depending on the element type.
The next problem that I see is that your HTML structure, the Questions & Answers aren't associated with each other in any way.
Another problem I see comes when you are declaring your JS variables. You're trying to chain your declarations, which is fine. Although you need to be using , instead of ;. The ; should only be on the last one to be declared.
I assume most of these problems just came from you giving us some sample code. I expect your real code doesn't look like this, or you'd be having other problems noted in your question.
Regardless, I have a solution for you. I rewrote it in a way that makes more sense to me:
View Demo Here - JSFiddle
HTML:
<form>
<label for="a1" id="a">Question 1</label>
<input type="radio" name="a1" value="YES" id="d">YES
<input type="radio" name="a1" value="NO" id="e">NO
<br>
<br>
<label for="a2" id="b">Question 2</label>
<input type="radio" name="a2" value="YES" id="f">YES
<input type="radio" name="a2" value="NO" id="g">NO
<br>
<br>
<label for="a3" id="c">Question 3</label>
<input type="radio" name="a3" value="YES" id="h">YES
<input type="radio" name="a3" value="NO" id="i">NO
<br>
<br>
<input type="button" name="Submit" value="Result" style="margin-left:100px;" onClick="theResult()">
</form>
I made 2 changes. I got rid of the <p> elements in favor of <label>. And then I changed the checkboxes to radio buttons.
The JS
function theResult(){
var inputs = document.getElementsByTagName('input');
var question = [ {selected: '', expected: 'YES'},
{selected: '', expected: 'YES'},
{selected: '', expected: 'NO'}
];
var tmpSelected = [];
for(var i = 0; i < inputs.length; i++){
var tmp = inputs[i];
if(tmp.type == 'radio' && tmp.checked){
tmpSelected.push(tmp.value);
}
}
for(var i = 0; i < tmpSelected.length; i++){
question[i].selected = tmpSelected[i];
}
validateResults(question);
};
function validateResults(results){
var status = '';
for(var i = 0; i < results.length; i++){
if(results[i].selected != results[i].expected){
status = 'Not Good'
break;
} else {
status = 'Good';
}
}
console.log(status);
return status;
}
As you can see, I've made a lot of changes to this one. I wanted to make a better mapping between selected answer & the expected.
We then go through and grab all the inputs on the page. In the first loop, we make sure that we're only accepting radio buttons & only looking at the ones that have been checked or selected. We stuff those off into an array tmpSelected for a bit.
Then we assign the values of tmpSelected to our question object, specifically to .selected. This will make it easy to compare against the expected answer.
Then we'll make a call to a different function to validate the results (this logic could've been kept in the previous function, I just like splitting things up a bit to make them more modular).
the validateResults() simple compares .selected with .expected. If they don't match, we break our loop and return the status of 'Not Good'. Otherwise we keep evaluating. I did it this way because it seemed like your code was just returning a success/failure type message, and not necessarily saying which answers were incorrect.
The results are correctly logged to the console. So you'd just need to change that back to your document.write().
Try using this in each case:
var question1 = document.getElementById("a").innerHTML;
var answer1 = document.getElementById("d").innerHTML;
if(question1 == answer1 ){
document.write('good');
}
Start simple and build up.

How to retrieve the value from a radio button in javascript?

Ok, I've checked a lot of other answers but the solutions posted there are beyond the scope of the class I am taking. IE we haven't discussed how to do it that way.
Anyways, I'm simply trying to get the value from a radio button here is my html code and my javascript.
<script type="text/javascript">
function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
</script>
and the actual button looks like this in my html code.
Milwaukee: ($20) <input type="radio" name="radCity" value="20" />
When I alert(arrivalcity); all I get is NaN. I don't understand why, shouldn't it return the string 20??
Allow me to clarify. I have 3 different city choices. I have edited it to show exactly what I have when I begin my form.
<form name="reservations">
<p>First Name: <input type="text" name="txtFirstName" />
Last Name: <input type="text" name="txtLastName" /></p>
<span style="font-weight:bold;">Arrival City:</span><br />
Milwaukee: ($20) <input type="radio" name="radCity" value="20" /><br />
Detriot: ($35) <input type="radio" name="radCity" value="35" /><br />
St. Louis: ($40) <input type="radio" name="radCity" value="40" />
I need to get the value from whatever one is selected. I can't hardcode it into my script.
This function will do what you want, through the querySelector method:
function selectedRadio(){
var selValue = document.querySelector('input[name="radCity"]:checked').value;
alert(selValue);
}
JSFiddle
Reference
Do you have a form named reservation in your body?
It will work like this:
<form name="reservations">
<input type="radio" name="radCity" value="20" />
</form>
​function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
See it running here: http://jsfiddle.net/eBhEm/
​
However, I would prefer this instead:
<input type="radio" id="radCity" value="20" />
And then use getElementById
function bookTrip()
{
var arrivalcity;
arrivalcity = document.getElementById("radCity").value;
alert(arrivalcity);
}
See this running on jsfiddle.
function bookTrip() {
var arrivalcity= document.reservations.radCity;
for (var i = 0, iLen = arrivalcity.length; i < iLen; i++) {
if (arrivalcity[i].checked) {
alert(arrivalcity[i].value);
}
}
}
i believe this should help.
see it working here
http://jsfiddle.net/eBhEm/24/
You can use querySelector in browsers that support it, but not all browsers in use do. The old fashioned (reliable, robust, works every where) method is to loop over the collection to find the one that is checked:
function getValue() {
var buttonGroup = document.forms['reservations'].elements['radCity'];
// or
// var buttonGroup = document.reservations.radCity;
// Check for single element or collection, collections don't have
// a tagName property
if (typeof buttonGroup.tagName == 'string' && buttonGroup.checked) {
return buttonGroup.value;
} else {
// Otherwise, it's a collection
for (var i=0, iLen=buttonGroup.length; i<iLen; i++) {
if (buttonGroup[i].checked) {
return buttonGroup[i].value;
}
}
}
}
Note that the test between an HTMLCollection and DOM element uses a property that DOM elements must have but an HTMLCollection should not have, unless a member of the collection has a name of "tagName".

How do I validate a group of textboxes using javascript?

I have group of check-boxes and corresponding text-boxes with them. I can get each checkbox one by one, but how do I get the group of textboxes so I can validate them?
Here is my javascript code below:
function validate_orderform(proform)
{
var flag=0;
for (var i = 0; i < proform.chk.length; i++) {
if (proform.chk[i].checked && proform.quant[i].value=="") {
flag=1;
}
}
if(flag==1){
return false;
}
return true;
}
and my html code:
<td><input type="checkbox" id="chk1" name="chk"></td>
<td><input type="text" size="10" id="quant1" name="quant1"></td>...and so on
If name of textboxes are different then you can access all textboxes by
var txtObjList = document.getElementsByTagName("input");
for(var i=0; i < txtObjList.length; i++){
if(txtObjList[i].getAttribute("type") == "text" && this.value != ""){
// success for i+1 textbox
}
}
Or you can give common class name to all textboxes and then can access by
var txtObjList = document.getElementsByClassName("classname");
for(var i=0; i < txtObjList.length; i++){
if(this.value != ""){
// success for i+1 textbox
}
}
Remember by using javascript library such as jquery, prototype your work will be simpler.
There are a couple of methods you could use, you could use document.getElementsByTagName to retrieve all of the input elements, check their type etc... It works but it's slow and potentially expensive depending on how complex your form is.
If you have a group of checkboxes and each one has it's own text box then you could group them, so add a common name to each type, e.g.
Entry 1:
<input type="checkbox" id="chk1" name="chk"/>
<input type="text" id="quant1" name="quant"/>
Entry 2:
<input type="checkbox" id="chk2" name="chk"/>
<input type="text" id="quant2" name="quant"/>
Then you can use the document.getElementsByName method, so in this instance the following would retrieve a collection of 2 objects for you're text boxes:
var myTextBoxes = document.getElementsByName("quant");

Categories

Resources