How to print checked checkbox values? - javascript

The html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="scripts.js"></script>
</head>
<body>
<button id = "button1" type="button" onclick="filterValues();">Submit</button>
</body>
</html>
My javascript:
var checkingValues = ["Cat", "Dog", "Horse", "Tree"];
var createCheckboxes;
var saveValues;
document.write("Choose from the options below: </br> </br>");
for (var i = 0; i < checkingValues.length; i++) {
createCheckboxes = document.createElement("INPUT");
var checkbox = createCheckboxes.setAttribute("type", "checkbox");
createCheckboxes.setAttribute("value", checkingValues[i]);
var checkBoxText = document.body.appendChild(createCheckboxes) + document.write(createCheckboxes.value +"</br>");
}
//try to save checked values
if(createCheckboxes.checked){
saveValues = checkbox;
}
function filterValues() {
document.write(saveValues);
}
My idea is to generate a checkbox and print(filter) the selected items from the checkbox by saving the selected items in to a new array and just print them on a cick. I feel i need to make a simple if statement for that but i cant seem to write the values in the global saveValues variable. I know that is not the smartest way to do it but i want to know how to do it. I want to use pure JS.
Thanks.

If you're restricted to pure Javascript, you could always do the following:
var inputs = document.getElementsByTagName('input');
for(var i=0; i < inputs.length; i++){
if(inputs[i].type == 'checkbox' && inputs[i].checked) {
//print
console.log(inputs[i].value);
}
}
That will get all checked checkboxes on the page and print their values. Instead of printing to the console you could do some other logic, or add the checkbox to a second array for later use.

Try this,
function filterValues() {
for (var i = 0; i < checkingValues.length; i++) {
if(createCheckboxes.checked){
saveValues = checkbox;
}
}
document.write(saveValues);
}

Related

Javascript array change in realtime after button click

i'm making a web application which helps people to seek what disease they have according to the symptoms.
I want to the user to click specific symptom to add in the "u_symptom_i" array and show all of the changed array elements by alert function
However, i cannot see the added element by alert function
<script>
var j = 0;
while(j < escaped_cc.length) {
document.write('<th><button id="symptom_button">' + escaped_cc[j] + '</button></th>');
document.getElementById("symptom_button").value = escaped_cc[j];
j = j + 1;
}
$("button").click(function() {
u_symptom_i.push($(this).val());
alert($(this).val());
});
</script>
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<body>
<h2>Insert Array</h2>
<input type="text" id="example" name="value">
<button id="button">Add array new item</button>
</body>
<script>
var array=[];
$("#button").click(function() {
var str = $("#example").val();
array.push(str);
alert(array);
});
</script>
</html>
Can you try this code? Adds each new value entered to an array named array and displays the records.

Hiding class based on radio selection

I am trying to hide a class based on the name (etc. "hiddenA"), I previously used ID but I want to hide more than 1 class so ID is no longer an option. This is what I have currently:
function onChangePackage() {
const nodes = document.getElementsByClassName('Package');
var selectedValue;
// Get selected radio
for (var i = 0, length = nodes.length; i < length; i++) {
if (nodes[i].checked) {
selectedValue = nodes[i].value;
break;
}
}
// Showing all nodes first
const nodePostFix = ['A', 'B', 'C'];
nodePostFix.forEach(node => {
const currentElement = elementsToHide.item(i);
if (currentElement.hasClass('hidden' + selectedValue)) {
currentElement.style.display = 'none';
} else {
currentElement.style.display = 'block';
}
});
}
I feel like I am over complicating my code as there surely must be a simpler way.
Try this code here. You will just have to change the button to a radio button. Also use jquery. I think this is what you wanted.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1, #p2").toggle();
});
});
</script>
</head>
<body>
<button>Hide / Show</button>
<p id="p1">I have a class of p1</p>
<p id="p2"s>I have a class of p2</p>
<p id="p1">I have a class of p1</p>
</body>
</html>

Creating dynamic form using javascript

I am trying to create forms dynamically using javascript, but I struggled with creating radio buttons in the form properly. The problem is I can't display a label beside each radio button
here is the index.html file
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
</head>
<body>
<form id="myform">
</form>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
and the custom.js file
document.body.onload = newElement;
function newElement() {
var form = document.getElementById("myform");
var questions = {
name : "q1",
qType : "radio",
qLabel : "Is your system is automated online advising?",
options : ["Yes", "No"]
}
var label = document.createElement("label");
var lblContent = document.createTextNode(questions["qLabel"]);
label.appendChild(lblContent);
form.appendChild(label);
switch(questions["qType"]) {
case "radio":
var input = [];
var option;
var optionContent;
for(var i = 0; i < questions["options"].length; i++) {
input[i] = document.createElement("input");
input[i].setAttribute("type", questions["qType"]);
input[i].setAttribute("name", questions["name"]);
option = document.createElement("label");
optionContent = document.createTextNode(questions["options"][i]);
option.appendChild(optionContent);
input[i].appendChild(option);
form.appendChild(input[i]);
}
break;
}
}
Replace the last two lines of the for loop with
form.appendChild(input[i]);
form.appendChild(option);

doesnt get in the if statement javascript DOM

so I have to get the bigger salary of the average salary and to print the name of the person, but I don't get in the if at least the alert says so. Here is my code:
<html>
<body>
<script type="text/javascript">
xDOC = new ActiveXObject("Microsoft.XMLDOM");
xDOC.async = "false";
xDOC.load("pti_project.xml");
x = xDOC.getElementsByTagName("person");
alert(x.length);
var avgsal = 11450 / x.length;
for (var i = 0; i < x.length; i++) {
var salary = x[i].getElementsByTagName("salary");
if (salary * 1 > avgsal * 1) {
alert("1");
var person = x[i].getElementsByTagName("name");
document.write(person[0].childNodes[0].nodeValue);
}
}
document.write(avgsal);
</script>
</body>
</html>
No clue why is this happens, it should work.
How its name says, the method getElementsByTagName() returns a collection of objects, not their values.
Look at the example in this page: https://msdn.microsoft.com/en-us/library/ms765549(v=vs.85).aspx
The result of the function is iterated with a for loop to get each matched element and then its xml property is printed.
Something like:
(salary.length > 0 ? parseFloat(salary.item(0).xml) : 0)
would work for you instead of only salary.
This expression will check if the collection is not empty and if so will get the content of first element. Otherwise will return zero.
Here is my answer to my question I needed little time , but I made it . So here is the code if somebody needs help with such type of situation :
<html>
<body>
<script type="text/javascript">
xDOC=new ActiveXObject("Microsoft.XMLDOM");
xDOC.async="false";
xDOC.load("pti_project.xml");
x=xDOC.getElementsByTagName("person");
var avgsal = 11450/x.length;
for(var i=0; i<x.length; i++)
{
var salary=x[i].getElementsByTagName("salary");
if(salary[0].childNodes[0].nodeValue>avgsal*1)
{
var person=x[i].getElementsByTagName("name");
document.write(person[0].childNodes[0].nodeValue);
document.write("<br>");
}
}
</script>
</body>
</html>

How to add comma seperated values according to the checkboxes in textbox?

I have 3 checkboxes and 1 textbox
i use only these controls mentioned above ..
I want ---- when i check checkbox1 and checkbox2 then it will display in textbox1 as 1,2 as it is as the same ascending order not 1,2, or 2,1,
I use this type of coding in asp.net (VB) , i wanna use this coding for 45 checkboxes........
Can anybody solve this problem in asp.net (vb)
JS solution (needs adaptation to your markup) as question is tagged with javascript
<html>
<head>
<title>S.O. 4121588</title>
<script type="text/javascript">
var gMax = 45;
function $(aId) {
return document.getElementById(aId);
}
// generates gMax checkboxes with value from 1 to gMax
function onload() {
var form = $('theForm');
for (var i = 1; i != gMax; i++) {
var cb = document.createElement('input');
cb.setAttribute('type', 'checkbox');
cb.setAttribute('id', 'checkbox-' + i);
cb.setAttribute('value', i);
form.appendChild(cb);
}
}
// update the result textarea
function updateResult() {
var num = [ ];
for (var i = 1; i != gMax; i++) {
var cb = $('checkbox-' + i);
if (cb.checked) {
num.push(cb.getAttribute('value'));
}
}
$('result').innerHTML = num.join(", ");
}
</script>
</head>
<body onload='onload()'>
<form id="theForm"></form>
<input type="button" id="resultBtn" value="Result"
onclick="updateResult()" />
<br/>
<textarea id="result"></textarea>
</body>
</html>
Tested under Chrome 9.0.570.1 dev

Categories

Resources