HTML-store checked items in a array - html

How to store the items checked in a checkbox in an array?
I tried using a for loop but it didn't work
for(i=0;i<selectedQuote.length;i++) {
}

I believe this will serve your purpose.
function ShowValue(){
var arrayTemp=[];
$('input[type=\"checkbox\"]:checked').each(function(){
arrayTemp.push($(this).val());
});
/*
If you want to itterate the array
for(var i=0;i<arrayTemp.length;i++){
console.log(arrayTemp[i]);
}
*/
$("#result").html(arrayTemp);
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" value="val1">Val 1
<input type="checkbox" value="val2">Val 2
<input type="checkbox" value="val3">Val 3
<button onclick="return ShowValue()"> Show </button>
<div id="result">
</div>
</body>
</html>

To achieve expected result, use below option using querySelectorAll to get all checkboxes using attribute name
var elem = document.querySelectorAll('[name=sports]');//all checkbox elements
var checkbox =[];
for(var i =0; i < elem.length; i++){
if(elem[i].checked){
checkbox.push(elem[i].value)
}
}
console.log(checkbox)
https://codepen.io/nagasai/pen/OQoBeL
For capturing the checked elements dynamically use addEventListener
var elem = document.querySelectorAll('[name=sports]');//all checkbox elements
var checkbox =[];
for(var i =0; i < elem.length; i++){
elem[i].addEventListener('change', function(e){
console.log(e.target.checked)
if(e.target.checked){
checkbox.push(e.target.value)
console.log(checkbox)
}else{
checkbox.splice(checkbox.indexOf(e.target.value),1)
console.log(checkbox)
}
});
}
https://codepen.io/nagasai/pen/rJZQOp

Related

.val() is not working and is returning as "on"

Why does this happen ? I am not using correct syntax here?
HTML is as below
<div id="tasks" value="1" class="1">
<input type="checkbox">
<label>Task has been added</label>
</div>
jQuery is as below
$("#cButton").click(function () {
var arr_id = [];
$(":checkbox:checked").each(function (i) {
arr_id[i] = $(this).val();
console.log("$(this).val() : " + $(this).val());
})
if (arr_id.length == 0) {
alert("atleast check one");
} else {
for (var i = 0; i < arr_id.length; i++) {
$("." + arr_id[i]).remove();
console.log("Hello");
}
}
});
Console O/P is as below
$(this).val() : on
The best way to get a boolean value from a checkbox input with jQuery is using prop: $(this).prop("checked").
If the value attribute was omitted, the default value for the checkbox is on
MDN input type="checkbox"
If you need to use the value of the input you should be placing it inside the input tag. Because you didn't set a value it's taking the default "on" when calling val() on it.
$("#cButton").click(function () {
var arr_id = [];
$(":checkbox:checked").each(function (i) {
arr_id[i] = $(this).prop("checked");
console.log($(this).prop("checked"));
})
if (arr_id.length == 0) {
alert("atleast check one");
} else {
for (var i = 0; i < arr_id.length; i++) {
$("." + arr_id[i]).remove();
console.log("Hello");
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tasks" value="1" class="1">
<input type="checkbox">
<label>Task has been added</label>
</div>
<button id="cButton">Button</button>
You placed the value attribute on the parent <div>... A <div> does not have a value. It has to be on the input.
The elements which can have a value are ref:
<button>
<data>
<input>
<li>
<meter>
<option>
<progress>
<param>
$("#cButton").click(function() {
var arr_id = [];
$(":checkbox:checked").each(function(i) {
arr_id[i] = $(this).val();
console.log("$(this).val() : " + $(this).val());
})
if (arr_id.length == 0) {
alert("atleast check one");
} else {
for (var i = 0; i < arr_id.length; i++) {
$("." + arr_id[i]).remove();
console.log("Hello");
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tasks" class="1">
<input type="checkbox" value="1">
<label>Task has been added</label>
</div>
<button id="cButton">Button</button>

How to add columns into Data table eachtime after certain selection is done?

I tried updating my Data table depending upon which checkbox is checked..I am able to display the specified column in Data table depending upon which checkbox is checked...but I am unable to display anything when multiple checkboxes are checked.
How I am supposed to display multiple columns in the Data table when multiple checkboxes are selected?? ...please help.
Here is my code
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(cal);
function cal()
{
var data = new google.visualization.DataTable();
var newData = [
['What is your name?', 'What is your age?','How do you get to work?' ,'How long is your commute?' ],
['2005', '1170', '460' , '421' ],
['2006', '660', '1120' , '4324' ],
['2007', '1030', '540' , '4234' ],
['2008', '1530', '50' , '234' ]];
var numRows = newData.length;
var numCols = newData[0].length;
if(document.getElementById('cb1').checked==true)
{
data.addColumn('string', newData[0][0]);
for (var i = 1; i < numRows; i++)
data.addRow([newData[i][0]]);
}
if(document.getElementById('cb2').checked==true)
{
data.addColumn('string', newData[0][1]);
for (var i = 1; i < numRows; i++)
data.addRow([newData[i][1]]);
}
if(document.getElementById('cb3').checked==true)
{
data.addColumn('string', newData[0][2]);
for (var i = 1; i < numRows; i++)
data.addRow([newData[i][2]]);
}
if(document.getElementById('cb4').checked==true)
{
data.addColumn('string', newData[0][3]);
for (var i = 1; i < numRows; i++)
data.addRow([newData[i][3]]);
}
var table = new google.visualization.Table(document.getElementById('tablechart'));
table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
}
</script>
</head>
<body>
<form name="myform">
<input type="checkbox" name="c1" id="cb1">What is your name?
<input type="checkbox" name="c1" id="cb2">What is your age?
<input type="checkbox" name="c1" id="cb3">How do you get to work?
<input type="checkbox" name="c1" id="cb4">How long is your commute?
<input type="button" name="b1" onclick="cal()">Submit
</form>
<div id="tablechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
I am able to display single column when only one checkbox is checked..but unable to display/add multiple columns into Data table when multiple checkboxes are selected..please help.
Thank you :)

Get string value in angularJS

Here is my code for show and hide div using loop,i have 9 div like
<div ng-show="div1">.......</div>
<div ng-show="div2">.......</div>
<div ng-show="div3">.......</div>
<div ng-show="div4">.......</div>
<div ng-show="div5">.......</div>
<div ng-show="div6">.......</div>
<div ng-show="div7">.......</div>
<div ng-show="div8">.......</div>
<div ng-show="div9">.......</div>
am trying to show and hide the div using loop based on the value.suppose here am giving value as 4.i mean 4 div ll be show,
var testOk='';
var testFAIL='';
$scope.tests=function(){
for(var i=1; i<=9; i++){
if(i <= 4)
{
testOk+='$scope.div'+i+'=true;';
}
else{
testFAIL +='$scope.div'+i+'=false;';
}
}
alert(testOk);
}
here testOK var contain showing div and testFail var contain hiding div,
output:-
testOK =$scope.Div1=true;$scope.Div2=true;$scope.Div3=true;$scope.Div4=true;
testFAIL =$scope.Div5=false;$scope.Div6=false;$scope.Div7=false;$scope.Div8=false;$scope.Div9=false;
how can i bind that value in div section.i hope u understand what am trying to asking.Thanks in advance.
You have a weird approach for this. I'd show/hide divs like this:
angular.module('app', []).controller('ctrl', function($scope) {
$scope.nums = []
for (var i=0; i <= 9; i++) {
$scope.nums.push(i);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input ng-model="hideFrom" placeholder="Hide from this number onwards">
<div ng-repeat="num in nums" ng-hide="hideFrom && $index >= hideFrom">
{{num}}
</div>
</div>

Javascript how to allow array to take more than one digit?

I've been trying lately to build up a mean calculator using html and javascript. i want to take all the inputs from the one text box add them to an array and get the average result. what i did in the following code takes only one digit because of str[i-1] is there any other alternative way of doing it? Thanks!
Output photo
function calculate()
{
var str= document.getElementById("meanvalue").value;
for(var i=0; i<str.length; i++)
{
if(str[i] == ".")
{
sum+=parseInt(str[i-1]);
count++;
}
}
sum/=count;
document.getElementById("meanresult").value=sum;
}
Here is a small example:
document.getElementById('input').onkeyup = function() {
this.value = this.value.replace(/[^0-9\.]/gi, '');// restrict non digit
var sum = 0;
var array = this.value.split(/\./);
array.forEach(function(str) {
sum += (parseInt(str, 10) || 0); //avoid NaN
});
document.getElementById('output').value = (sum / array.length || 0);// avoid NaN
}
<input type="text" id="input" />
<input type="text" id="output" readonly='' />
i just want to know how the values are updated while im typing my
inputs automatically
Here, I am using onkeyup event to handle user input.
document.getElementById('input').onkeyup = function() {
document.getElementById('output').value = this.value;//get input, set output
}
<input type="text" id="input" />
<input type="text" id="output" readonly='' />
You can use the split function on the input. I give you a quick example here :
var string = "1.3.45.7";
var array = string.split(".");
// array = [1, 3, 45, 7]
document.write(array);
First split your str and than use for loop.
var str= document.getElementById("meanvalue").value.split('.');
Also remove your if condition inside the loop.
for(var i=0; i<str.length; i++)
{
//if(str[i] == ".")
// {
sum+=parseInt(str[i-1]);`
count++;
// }
}
sum/=count;
document.getElementById("meanresult").value=sum;
hope this helps you.

Input type=file, restrict to .rpt only

I'm using tag <input type="file" accept="application/x-rpt, magnus-internal/rpt"/> to only allow .rpt files to be uploaded, but it's unsuccessful. User still can upload whatever they want.
What's wrong here? Please help me. Thank you so much.
Put the following script in head
<script type="text/javascript">
function ValidateForm() {
var fileBox = document.getElementById("fileBox");
var val = fileBox.value;
var splittedValue = val.split(".");
//alert(splittedValue.length);
//for (var i = 0; i < splittedValue.length; i++) {
// alert(splittedValue[i]);
//}
var NthElementIndex = splittedValue.length - 1;
var nThElement = splittedValue[NthElementIndex];
if (nThElement != "jpg"
&& nThElement != "rpt") {
alert("Please select valid rpt file");
}
}
</script>
Now Use the following information for id in input tag
<input type="file" id="fileBox" />
<input type="button" onclick="ValidateForm()" value="Validate" />