I am new to Javascript so I'm not sure if my code is working as I'm not sure how to test or run it. What I want my code to do is display the JSON created from gathering all the checked boxes. I haven't added a console.log anywhere because I'm not sure where it would be appropriate. I feel as though I have all the pieces but I am not sure how to put everything together.
The expected output should be:
{
"testpages" : [...data...],
"configs" : [...data...]
}
My code
<script type="text/javascript">
function grabSelected() {
var configs = [];
var testPages = [];
var selectedConfigs = document.getElementByClassName('.testpages').value;
var selectedTestPages = document.getElementByClassName('.configs').value;
for (var i = 0; i < selectedConfigs.length; i++) {
if (selectedConfigs[i].checked) {
configs.push(selectedConfigs[i])
}
}
for (var i = 0; i < selectedTestPages.length; i++) {
if (selectedTestPages[i].checked) {
testPages.push(selectedTestPages[i])
}
}
var jsonString = {"testpages" : testpages, "configs" : configs};
var testJson = JSON.stringify(jsonString);
}
</script>
<body class="wrap">
<form action="POST" >
<div class="testpages" id="left_col">
<input id="tp1" type="checkbox" value="1">Test Page 1<br>
...
...
<input id="tp30" type="checkbox" value="30">Test Page 30<br>
</div>
<div class="configs" id="right_col">
<input id="config_0" type="checkbox" value="Windows XP internet explorer 8">Windows XP
...
...
<input id="config_59" type="checkbox" value="OS X 10.9 Safari 7">OS X 10.9 Safari 7<br>
</div>
</form>
<input id="" type="submit" value="Submit" onclick="grabSelected();" />
</body>
<html>
Some of the (trivial) mistakes found in your original code:
Used getElementByClassName instead of getElementsByClassName
Used testpages instead of testPages in jsonString formation
Used the classnames testpages and configs for parent div instead of
input elements.
Here's the one you can use:
<html>
<script type="text/javascript">
function grabSelected() {
var configs = [];
var testPages = [];
var selectedConfigs = document.getElementsByClassName('testpages');
var selectedTestPages = document.getElementsByClassName('configs');
for (var i = 0; i < selectedConfigs.length; i++) {
if (selectedConfigs[i].checked) {
configs.push(selectedConfigs[i].value)
}
}
for (var i = 0; i < selectedTestPages.length; i++) {
if (selectedTestPages[i].checked) {
testPages.push(selectedTestPages[i].value)
}
}
var jsonString = {"testpages" : testPages, "configs" : configs};
var testJson = JSON.stringify(jsonString);
}
</script>
<body class="wrap">
<form action="POST" >
<div id="left_col">
<input class="testpages" id="tp1" type="checkbox" value="1">Test Page 1<br>
<input class="testpages" id="tp30" type="checkbox" value="30">Test Page 30<br>
</div>
<div id="right_col">
<input class="configs" id="config_0" type="checkbox" value="Windows XP internet explorer 8">Windows XP
<input class="configs" id="config_59" type="checkbox" value="OS X 10.9 Safari 7">OS X 10.9 Safari 7<br>
</div>
</form>
<input id="" type="submit" value="Submit" onclick="grabSelected();" />
</body>
<html>
I believe the problem is that you're trying to return the value of the class instead of checking to see if is checked. Instead of getElementByClassName().value, try getElementByClassName(id).getElementsByTag('input'). This will return an array that you can loop through and return the values for.
Apologies for answer formatting, typed from SO app.
Related
I am having a problem with the array of an array. I need the function clickMe() to allow me to output an array such as [[1,1,1,1,1],[2,2,2,2,2],etc].
My problem is that right now the values come up as [1,1,1,1,1,2,2,2,2,2,etc]. I know a for loop inside a for loop would be the best way for this, but how would I get the inputs in sections of five?
Once I can figure this out, I should be able to pull from those arrays without any issues. I would prefer to keep this completely in Javascript.
var qNumber;
function onEnter() {
var qNumber = document.getElementsByName("numberBox")[0].value;
if(event.keyCode == 13) {
if (typeof(Storage) !== "undefined") {
localStorage.setItem("qNumber", qNumber);
console.log(qNumber + " stored successfully");
} else {
console.log("Sorry, your browser does not support Web Storage...");
}
var qID = document.getElementById("numBox");
var submitBtn = document.getElementById("submitButton");
var a = qNumber - 1;
var b = 0;
while (b < a) {
var formClone = document.getElementsByClassName("formBox")[0];
var listClone = formClone.cloneNode(true);
var text =b+2;
document.getElementById("forms").append(listClone);
b++;
}
return qID.parentNode.removeChild(qID);
}
return qNumber;
}
function clickMe() {
var q = localStorage.getItem("qNumber");
console.log(q);
var inputNow = [];
var allInputs = [];
var eachArray = [];
var inputNow = document.getElementsByTagName("input");
for(x=0; x < inputNow.length; x++) {
allInputs.push(inputNow[x].value);
console.log(allInputs);
}
localStorage.clear();
}
input{
display: block;
}
<div id="forms">
<span id="numBox">
<label for="numberBox">Number of Forms</label>
<input type="number" name="numberBox" onkeydown="onEnter()" />
</span>
<form id="formBox" name="formBox" action="#" onsubmit="return false;">
<label for="info1">Input 1:</label>
<input type="text" name="info1" />
<label for="info2">Input 2:
</label>
<input type="text" name="info2" />
<label for="info3">Input 3:
</label>
<input type="text" name="info3" />
<label for="info4">Input 4:
</label>
<input type="text" name="info4" />
<label for="info5">Input 5:
</label>
<input type="text" name="info5" />
</form>
</div>
<input type="submit" value="Submit" id="submitButton" onclick="clickMe()" />
<div id="content">
<span id="info1">input1</span>
<br/>
<span id="info2">input2</span>
<br/>
<span id="info3">input3</span>
<br/>
<span id="info4">input4</span>
<br/>
<span id="info5">input5</span>
</div>
You can always do something like:
var allInputs = [];
var groupInputs = [];
for (x=0; x < inputNow.length; x++) {
groupInputs.push(inputNow[x].value);
if (groupInputs.length === 5 || x === inputNow.length - 1) {
allInputs.push(groupInputs);
groupInputs = [];
}
}
The document added another 3 link given in such a way that three links define three fruit and the fourth to erase selections
How do I do that?
<html>
<head>
<script language="javascript">
<!--
function FruitBox() {
window.document.myform.fruit[].checked = true;
}
function clearall() {
for (var p = 1; p < 3; p++) {
var x = window.document.myform.fruit("value");
for (var i = 0; i < 4; i++)
x[i].checked = false;
}
}
//-->
</script>
</head>
<body>
<from name="myform">
<input type="radio" name="fruit" onclick="window.document.myform.fruit.value='oranges'">oranges & Tangerines <br>
<input type="radio" name="fruit" onclick="window.document.myform.fruit.value='bananas'">bananas <br>
<input type="radio" name="fruit" onclick="window.document.myform.fruit.value='peaches'">peaches,Nectarines & Palmus <br> To select Oranges click here
<input type="reset" Value="Sterge" onClick=" clearall()" />
</from>
</body>
</html>
You misspelled tag form
you need to pass something to the function
you need to access that something
the reset will reset the form. No need to call a function
since you use form access there is no need to address the form from the top of the document but there is ALSO no need to set the value of the fruit on click
if you give each radio an ID, you can have a <label for="oranges">Click here to select oranges</label> instead of a link
<html>
<head>
<script language="javascript">
function FruitBox(idx) {
window.document.myform.fruit[idx].checked = true;
return false; // cancel the link - preventDefault can be used too
}
/* NOT needed
function clearall() {
for (var p = 1; p < 3; p++) {
var x = window.document.myform.fruit("value");
for (var i = 0; i < 4; i++)
x[i].checked = false;
}
}
*/
</script>
</head>
<body>
<form name="myform">
<input type="radio" name="fruit">oranges & Tangerines <br>
<input type="radio" name="fruit">bananas <br>
<input type="radio" name="fruit">peaches,Nectarines & Palmus <br>
To select Oranges click here
<input type="reset" Value="Sterge" />
</from>
</body>
</html>
Why I'm getting undefined error in Firefox and IE. This code works well in Google Chrome. Here is the full code http://liveweave.com/fUhpiI
this is my html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="css/hpstyles.css" rel="stylesheet">
<script src="js/hpjs.js"></script>
</head>
<body>
<form id="hp">
<div>
<h2>1. Which one do you prefer?</h2>
<div>
<input type="radio" name="q1" id="radio1" class="radio" value="9"/>
<label for="radio1">Tea</label>
</div>
<div>
<input type="radio" name="q1" id="radio2" class="radio" value="4"/>
<label for="radio2">Coffee</label>
</div>
<div>
<input type="radio" name="q1" id="radio3" class="radio" value="1"/>
<label for="radio3">Milk</label>
</div>
</div>
<div>
</br>
<div><div>
<button type="button" onclick="hp(this.form)">Check</button>
<input class="reset" type="reset" value="Reset">
</div></div></div>
</form>
<div id="result"></div>
<div id="total"></div>
</body>
</html>
this is javascript
function hp(form)
{
var count1=0, count2=0, count3=0, count4=0, count5=0, count6=0, count7=0, count8=0, count9=0, count10=0,a ;
for(var i=0;i<3;i++){
if (form.q1[i].checked === true)
{
count1++;
}
}
if(count1!==1){
alert("Please Answer 1st Question");
return false;
}
answer1 = (form.q1.value);
a=Math.floor(answer1);
document.getElementById("result").innerHTML= "The selected values are "+"</br>"+answer1;
}
you should declare a answer variable .and you should access "q1" elements by giving index since you have 3 "q1" elements .basically form.q1 is a object NodeList .you can't get value from object NodeList.so actually in your case you should add brake to for loop and find the clicked radio button index .
you should use
answer1 = form.q1[i].value;
instead of
answer1 = form.q1.value;
explain
form.q1 is a object NodeList so
form.q1.value --> undefined since object NodeList/collection has no property "value"
and
form.q1[0] --> HTMLInputElement so
form.q1[0].value --> is not undefined
fixed code .WORKING DEMO http://jsfiddle.net/madhawa11111/3rywkdvf/
function hp(form) {
var i;
var answer;
var count1 = 0,count2 = 0,count3 = 0,count4 = 0,count5 = 0,count6 = 0,count7 = 0,count8 = 0,count9 = 0,count10 = 0, a;
for (i = 0; i < 3; i++) {
if (form.q1[i].checked === true) {
count1++;
break;
}
}
if (count1 !== 1) {
alert("Please Answer 1st Question");
return false;
}
answer1 = form.q1[i].value; //error was here .
a = Math.floor(answer1);
document.getElementById("result").innerHTML = "The selected values are " + "</br>" + answer1;
}
if it worked in google chorm that's because browsers ignore some errors.
I have a JavaScript defined in my file as follows:
<script language="javascript">
var transports = "<%=api.transports%>";
var httpsTransport;
var httpTransport;
var splittedTransports= transports.split(',');
for(i = 0; i < splittedTransports.length; i++)
{
if(splittedTransports[i]=="https") {
httpsTransport="https";
} else if (splittedTransports[i]=="http") {
httpTransport="http";
}
}
</script>
And I would like to read it in my HTML page like:
<div class="checkbox">
<label class="checkbox inline">
<input type="checkbox" id="transport_http" name="transport_http" value="http" <%if(httpTransport=="http"){%>checked<%}%> />
</label>
<label class="checkbox inline">
<input type="checkbox" id="transport_https" name="transport_https" value="https" <%if(httpsTransport=="https"){%>checked<%}%>/>
</label>
</div>
But now I get an error that states:
org.mozilla.javascript.EcmaError: ReferenceError: "httpTransport" is not defined.
What am I doing wrong here?
I want to allow user to select an checkbox and save the form, and when he tries to edit the form, I want to show what he has saved in his previous operation.
So, when he tries to edit I try to read the values form backend and would like to show that particular option as checked.
<script language="javascript">
var transports = "<%=api.transports%>";
var splittedTransports= transports.split(',');
for(i = 0; i < splittedTransports.length; i++)
{
if(splittedTransports[i]=="https"){
document.getElementById("transport_https").checked = true;
}else if (splittedTransports[i]=="http"){
document.getElementById("transport_http").checked = true;
}
}
</script>
HTML :
<div class="checkbox">
<label class="checkbox inline " >
<input type="checkbox" id="transport_http" name="transport_http" value="http" />
</label>
<label class="checkbox inline" >
<input type="checkbox" id="transport_https" name="transport_https" value="https"/>
</label>
</div>
The variables in your code are declared, but not defined.
Give them a random value first, and then update it with the if
<script language="javascript">
var transports = "<%=api.transports%>";
var httpsTransport = 'no';
var httpTransport = 'no';
var splittedTransports= transports.split(',');
for(i = 0; i < splittedTransports.length; i++)
{
if(splittedTransports[i]=="https"){
httpsTransport="https";
}else if (splittedTransports[i]=="http"){
httpTransport="http";
}
}
</script>
Here's my code:
<script type="text/javascript" xml:space="preserve">
function ATHD(f) {
var aa = "I would like help with the following topic(s): "
var bb = "Password Reset "
var cc = "Password Setup "
var dd = "Firmware Upgrade (if applicable) "
var ee = "Local Access Setup "
var ff = "Remote Access Setup "
var gg = "Mobile Access Setup "
var hh = "Recording Schedule Setup "
var ii = "How to playback video "
var jj = "How to convert video "
var kk = "Email Notification Setup "
var ll = "PTZ Setup (if applicable) "
if( f.pr.checked == true) {
f.sup.value = aa + bb;
}
if( f.ps.checked == true) {
f.sup.value = aa + cc;
}
}
</script>
<form><input onclick="ATHD(this.form)" id="1" type="checkbox" name="pr" /> Password Reset<br />
<input onclick="ATHD(this.form)" id="2" type="checkbox" name="ps" /> Password Setup<br />
<input onclick="ATHD(this.form)" id="3" type="checkbox" name="fu" /> Firmware Upgrade (if applicable)<br />
<input onclick="ATHD(this.form)" id="4" type="checkbox" name="la" /> Local Access Setup<br />
<input onclick="ATHD(this.form)" id="5" type="checkbox" name="ra" /> Remote Access Setup<br />
<input onclick="ATHD(this.form)" id="6" type="checkbox" name="ma" /> Mobile Access Setup<br />
<input onclick="ATHD(this.form)" id="7" type="checkbox" name="rss" /> Recording Schedule Setup<br />
<input onclick="ATHD(this.form)" id="8" type="checkbox" name="pb" /> How to playback video<br />
<input onclick="ATHD(this.form)" id="9" type="checkbox" name="cv" /> How to convert video<br />
<input onclick="ATHD(this.form)" id="10" type="checkbox" name="en" /> Email Notification Setup<br />
<input onclick="ATHD(this.form)" id="11" type="checkbox" name="ptz" /> PTZ Setup (if applicable)<br />
<br />
<span style="FONT-WEIGHT: bold">Question</span><span style="COLOR: #ff0000">*</span> (please be specific)<br />
<br />
<textarea style="HEIGHT: 164px; WIDTH: 577px" rows="10" cols="40">
</textarea></p>
<p><button>Continue...</button>
<textarea style="HEIGHT: 164px; DISPLAY: hidden; WIDTH: 577px" rows="10" cols="40" name="sup">
</textarea>
</p>
</form>
Basically, what I am looking to do is to whenever a box is checked, I want the value of the checkbox to be added into a hidden field. I understand that I still need to add the "value=[the value of the checkbox]" in the html code; what I want to allow for is multiple checkboxes to be selected so that multiple items will get added to the textbox.
I understand that one way of doing this would be to be to create if-then statements for every possible variation; this would not be very time effective as there would be thousands of permutations.
I am also trying to figure out if using an array would work to simplify this; I am not really sure how to conceptualize this in the simplest way as I have only been doing javascripting for three weeks. If someone can tell me how to think about this, I would greatly appreciate it. Looking more to learn how to do this so I can contribute to these forums and simplify the process of scripting functions as I do not have a background in coding.
If you can use jQuery, you won't need much code:
You could update the results whenever somebody clicks on a checkbox ($('input').on('click', function() {).
I personally would use <label> elements, but that's just me. You could grab the values by
$('input:checked').each(function() {
values.push($(this).parent().text());
});
Here is a working example: http://jsfiddle.net/HarryPehkonen/zNfju/1/
I have made small changes your dom like removing onclick events and It may solve your problem
var arr = [];
remove_item = function(arr,value){
for(b in arr ){
if(arr[b] == value){
arr.splice(b,1);
break;
}
}
return arr;
}
var inputs = document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
if(inputs[i].getAttribute('type') == 'checkbox')
{ inputs[i].addEventListener("change",function() {
if(this.checked)
arr.push(parseInt(this.id));
else
{
remove_item(arr,parseInt(this.id));
}
console.log(arr); document.getElementById("chcbx").value = arr.join(",");
},false);
}
}
and have a look at jsFiddle remove_item
Here's another way of doing it.
// find number of checkboxes (you haven't specified if you
// have a set number or not. If you have a set number, just
// set checkboxCount to whatever number you have.
var checkboxCount = 0;
var inputTags = document.getElementsByTagName('input');
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
function ATHD() {
var totalValue = '';
for (var i = 1; i < checkboxCount; i++) {
if (document.getElementById(i).checked)
totalValue += inputTags[i].getAttribute("name") + ';';
}
document.getElementById("hdnValues").value = totalValue;
alert(totalValue);
}
This basically counts all the checkboxes, loops through all, checks if they're checked, gets the value of the name attribute, then appends it to a string which is delimited by ;
jsfiddle: http://jsfiddle.net/mcDvw/
Alternatively, you could set all the values you want into the value attribute of the checkbox and read that instead of having the value in JS variable. e.g.
HTML:
<input onclick="ATHD()" id="1" type="checkbox" name="pr" value="Password Reset" /> Password Reset<br />
<input onclick="ATHD()" id="2" type="checkbox" name="ps" value="Password Setup" /> Password Setup<br />
JS:
function ATHD() {
var totalValue = '';
for (var i = 1; i < checkboxCount; i++) {
if (document.getElementById(i).checked)
totalValue += inputTags[i].value + ';';
}
document.getElementById("hdnValues").value = totalValue;
document.getElementById("showValues").value = totalValue;
}
jsfiddle: http://jsfiddle.net/mcDvw/1/