I want to get checkbox values - javascript

It always says if (checks[i].checked === true ) this is error I face...
I want to get value from checkbox Value...
function submitFun() {
var checks = document.getElementsByClassName('checks')
var str = "";
for (let i = 0; i < 3; i++) {
if (checks[i].checked === true) {
str += checks[i].value + "";
}
}
alert(str);
}
<div class="container">
<input type="checkbox" class="checks" value="뜨거워"> hot
<input type="checkbox" class="checks" value="추워"> clod
ok
</div>

you're iterating three ( 3 ) times when you have two ( 2 ) checkboxes, by the end of your loop, i will be 2 and check[2] is undefined, do i < checks.length instead of i < 3 :
function submitFun() {
var checks = document.getElementsByClassName('checks')
var str = "";
for (let i = 0; i < checks.length; i++) {
if (checks[i].checked === true) {
str += checks[i].value + " ";
}
}
alert(str);
}
<div class="container">
<input type="checkbox" class="checks" value="hot"> hot
<input type="checkbox" class="checks" value="cold"> clod
ok
</div>

Use querySelectorAll for selecting all check box also , also use checks.length in for loop to prevent null pointer on the array
See below working snippet
function submitFun() {
var checks = document.querySelectorAll('.checks')
var str = "";
for (let i = 0; i < checks.length; i++) {
if (checks[i].checked === true) {
str += checks[i].value + "";
}
}
alert(str);
}
<div class="container">
<input type="checkbox" class="checks" value="뜨거워"> hot
<input type="checkbox" class="checks" value="추워"> clod
ok
</div>

Try this.
Avoid attaching events in HTML (it is discouraged)
Use array.length while iterating, or better use Array.forEach()
function submitFun() {
var checks = document.getElementsByClassName('checks')
var str = "";
for (let i = 0; i < checks.length; i++ ){
if (checks[i].checked === true ) {
str += checks[i].value + "";
}
}
alert(str);
}
document.querySelector('a').addEventListener('click', () => {
submitFun();
});
<div class = "container">
<input type="checkbox" class ="checks" value ="뜨거워"> hot
<input type="checkbox" class ="checks" value ="추워"> clod
ok
</div>

Related

How to check if function inserted innerHTML correctly in js?

I'm writing code for myself to set values into an array based on which checkboxes are checked.
There is one function for setting innerHTML of the checkbox (checked or unchecked) and second one for changing the value of an array based on the condition if checkbox is checked or not.
The HTML code looks like this:
function check(id) {
if (id.innerHTML == "unchecked") {
id.innerHTML = "checked";
} else {
id.innerHTML = "unchecked";
}
}
function audiences() {
var audiencesLength = [];
var checkboxes = [];
for (var i = 0; i < 3; i++) {
checkboxes.push(document.getElementById("aud" + i).innerHTML)
}
for (var j = 0; j < 3; j++) {
if (checkboxes[j] != "unchecked") {
switch (j) {
case 0:
audiencesLength[j] = 1;
break;
case 1:
audiencesLength[j] = 3;
break;
case 2:
audiencesLength[j] = 7;
break;
}
} else {
audiencesLength[j] = 0;
}
}
}
<li class="checkboxes">
<label class="checkbox-container">1
<input type="checkbox">
<span class="checkmark" id="aud0" onclick="check(this)">unchecked</span>
</label>
<label class="checkbox-container">3
<input type="checkbox">
<span class="checkmark" id="aud1" onclick="check(this)">unchecked</span>
</label>
<label class="checkbox-container">7
<input type="checkbox">
<span class="checkmark" id="aud2" onclick="check(this)">unchecked</span>
</label>
</li>
It works until I start to check the checkboxes fast. Then some of them are correct and some of them have values "checked" when unchecked and some of them "unchecked" when checked.
Is there a way to prevent this? Or is there any problem in the code?
Thanks!
Because you only binding event to span, which won't work if you're click on label nor input. Instead, you should use onchange on input, this will affect both label of it and itself
function check(element) {
id = document.getElementById(element)
if (id.innerHTML == "unchecked") {
id.innerHTML = "checked";
} else {
id.innerHTML = "unchecked";
}
}
function audiences() {
var audiencesLength = [];
var checkboxes = [];
for (var i = 0; i < 3; i++) {
checkboxes.push(document.getElementById("aud" + i).innerHTML)
}
for (var j = 0; j < 3; j++) {
if (checkboxes[j] != "unchecked") {
switch (j) {
case 0:
audiencesLength[j] = 1;
break;
case 1:
audiencesLength[j] = 3;
break;
case 2:
audiencesLength[j] = 7;
break;
}
} else {
audiencesLength[j] = 0;
}
}
}
<li class="checkboxes">
<label class="checkbox-container">1
<input onchange="check('aud0')" type="checkbox">
<span class="checkmark" id="aud0">unchecked</span>
</label>
<label class="checkbox-container">3
<input onchange="check('aud1')" type="checkbox">
<span class="checkmark" id="aud1">unchecked</span>
</label>
<label class="checkbox-container">7
<input onchange="check('aud2')" type="checkbox">
<span class="checkmark" id="aud2">unchecked</span>
</label>
</li>

Add string from textbox input

i have a textbox1 which input by user and textbox2 for user to input numbers which can automatically generate textbox1 value into multiple string such as example below:
Txtbox1 = ABC12345
Txtbox2 = 3
Result will be
ABC12345-1
ABC12345-2
ABC12345-3
You can try using something like this below, but kinda hard to make it 100% as you want, since you haven't shown any HTML.
$("[id^=Txbox]").keyup(function() {
var empty = $("[id^=Txbox]").filter(function() {
return $.trim($(this).val()).length == 0
}).length == 0;
if (empty) {
var str = $("#Txbox1").val();
var number = $("#Txbox2").val();
var arr = [];
for (i = 0; i < number; i++) {
arr.push(str + "-" + i)
}
console.log(arr)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Txbox1" />
<input id="Txbox2" type="number" />
You can just use button and apply click event.
function getString() {
var finalString = [];
var t = $("#textbox1").val()
var n = $("#textbox2").val();
if (t.toString().trim() != "") {
for (i = 0; i < n; i++) {
finalString.push(t + "-" + (i + 1))
}
}
console.log(finalString)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text : <input type="text" id="textbox1"><br><br> Number : <input type="text" id="textbox2">
<button type="button" onClick="getString()" id="textbox1">Get</button>

code not executing after for loop -- javascript

I'm writing a function that is supposed to loop through all my checkboxes and load the "value" of the checkboxes that are checked into an array, however nothing is executing beyond the first for loop. I'm completely stumped here, what am I missing?
function saveSettings(){
var count = 1; //count for db
var checked=[]; //array of checked values
var inc = 0; //only incremented when checkbox is checked
var dataString = "x";
for(var i=0; i<=2; i++) { //loads checked array with checked values
if(document.getElementById("check"+i).checked == true){
checked[inc] = document.getElementById("check"+i).value;
alert(checked[inc]) // <------ executing as expected
inc++;
}
}
alert("made it") // <------ not executing
if(checked.length>0){ // loads checked values into dataString
for(var i=0; i == checked.length; i++){
if(i == 0){
dataString = "co_" + count +"="+checked[i]
}
else {
dataString = dataString +"&co_" + count +"="+checked[i]
}
count++;
}
}
alert(dataString)
From your description of the problem, I think the problem is the number of checkboxes, if you have only 2 checkboxes then the condition i<=2 will cause problem because docuement.getElementById('check2') will be undefined causing an error like Uncaught TypeError: Cannot read property 'checked' of null in your console.
Since you are trying to deal with dynamic number of elements try to use a class to select the checkboxs of interest like
function saveSettings() {
var checked = [];
var dataString = "x";
var checks = document.getElementsByClassName('check');
//if you can't add a class then fetch all the checkboxes in the page
//var checks = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < checks.length; i++) {
if (checks[i].checked == true) {
checked.push(checks[i].value);
}
}
console.log("made it: ", checked)
if (checked.length > 0) {
dataString = '';
for (var i = 0; i < checked.length; i++) {
dataString += (i == 0 ? '' : '&') + "co_" + i + "=" + checked[i]
}
}
alert(dataString)
}
<input type="checkbox" class="check" id="check0" value="1" />
<input type="checkbox" class="check" id="check1" value="2" />
<input type="checkbox" class="check" id="check2" value="3" />
<br />
<button onclick="saveSettings()">Test</button>
in this line
if(document.getElementById("check"+i).checked == true){
//...
the getElementById will return an undefined value, and undefined does not have the .checked property.
how many checkboxes do you have in the document?
your second for loop had a mistake
function saveSettings(){
var count = 1; //count for db
var checked=[]; //array of checked values
var inc = 0; //only incremented when checkbox is checked
var dataString = "x";
for(var i=0; i<=2; i++) { //loads checked array with checked values
if(document.getElementById("check"+i).checked == true){
checked[inc] = document.getElementById("check"+i).value;
alert(checked[inc]) // <------ executing as expected
inc++;
}
}
alert("made it") // <------ not executing
if(checked.length>0){ // loads checked values into dataString
for(var i=0; i < checked.length; i++){
if(i === 0){
dataString = "co_" + count +"="+checked[i]
}
else {
dataString = dataString +"&co_" + count +"="+checked[i]
}
count++;
}
}
alert(dataString)
}
<input type="checkbox" id="check0"/>
<input type="checkbox" id="check1"/>
<input type="checkbox" id="check2"/>
<button onclick="saveSettings()">Run</button>
Try below working solution. Second for loop condition in your code (i == checked.length) is wrong. It should be i < checked.length)
function saveSettings() {
var count = 1; //count for db
var checked = []; //array of checked values
var inc = 0; //only incremented when checkbox is checked
var dataString = "x";
for (var i = 0; i <= 2; i++) { //loads checked array with checked values
if (document.getElementById("check" + i).checked == true) {
checked[inc] = document.getElementById("check" + i).value;
inc++;
}
}
if (checked.length > 0) { // loads checked values into dataString
for (var i = 0; i < checked.length; i++) {
if (i == 0) {
dataString = "co_" + count + "=" + checked[i]
}
else {
dataString = dataString + "&co_" + count + "=" + checked[i]
}
count++;
}
}
alert(dataString)
}

how to check checkboxes in javascript

I have three checkboxes in html.
In Javascript I have variable newspaper = "jang,News,Dawn";
Now I want to check the checkboxes based on newspaper values if it contain only jang then only jang check box should be checked if it contain jang,News,Dawn then all three checkbox should be checked.
The code I have written always checked last two checkboxes which is wrong.
My code is:
var newspaper = document.forms[0].newspaper;
var a = "Jang,News";
var news = ["Jang", "Dawn", "News"]
for (i = 0; i < news.length; i++)
{
if (a.indexOf(news[i]))
{
newspaper[i].checked = true;
}
}
<input type="checkbox" name="newspaper[]" value="Jang">Jang<br />
<input type="checkbox" name="newspaper[]" value="Dawn">Dawn<br />
<input type="checkbox" name="newspaper[]" value="News">The News
If you want to do it using Javascript only, you have to do some changes in your code :
Change the name of all the checkboxes to "newspaper" (without square brackets)
<input type="checkbox" name="newspaper" value="Jang"/>Jang<br />
<input type="checkbox" name="newspaper" value="Dawn"/>Dawn<br />
<input type="checkbox" name="newspaper" value="News"/>The News
Check indexOf return value is not equal to -1 :
if (a.indexOf(news[i]) != -1) {
newspaper[i].checked = true;
}
Here is the working demo.
var newspaper = document.forms[0]["newspaper[]"];
var a = "Jang,News";
for (i = 0; i < newspaper.length; i++)
{
if(a.indexOf(newspaper[i].value) > -1){
newspaper[i].checked = true;
}
}
Yeah, I would review your code, and the names of your elements. But here, this works.
http://jsfiddle.net/3qeeox0a/
Try this-
var newspaper = document.forms[0].newspaper;
var a = "Jang,News";
var news = ["Jang","Dawn", "News"]
for (i = 0; i < news.length; i++)
{
if (a.indexOf(news[i]) != 1)
{
newspaper[i].checked = true;
}
}
Fiddle:-http://jsfiddle.net/um0y5wrp/9/
Please change the code, and replace this:
if (a.indexOf(news[i]))
{newspaper[i].checked = true;
}
by:
for(j = 0; j < newspaper.length; j++){
if(newspaper[j].value == newspaper[i].value){
if (a.indexOf(news[i])){
newspaper[j].checked = true;
}
}
}

How to manipulate form field values in javascript

I'm trying to get the value of a few checkboxes and enter them in a hidden form field.
My checkboxes look like this:
<form>
<input type="checkbox" name="chicken" id="chicken" value="chicken"/>Chicken
<input type="checkbox" name="meat" id="meat" value="meat"/>Meat
</form>
<form method="post" action="">
<input type="hidden" name="my-item-name" value="" />
<input type="submit" name="my-add-button" value=" add " />
</form>
I only need to submit the hidden field data so I'd like the value of the hidden field change when the checkbox is ticked. So if the first checkbox is ticked I'd like the value of the hidden field to become chicken and if both of them are ticked the value should be chicken,meat.
I'm using the following javascript
function SetHiddenFieldValue()
{
var checks = document.getElementsByName("checkbox");
var hiddenFieldVal = "";
for(i = 0; i < checks.length; i++)
{
if(hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}
but when I add the items, it adds both of them, it doesn't check which one's been checked, is there a way to fix that, so when the first item is checked it'll only add that item and if both of them are checked, it'll add 2 items separated by comma,
for(i = 0; i < checks.length; i++)
{
if (!checks[i].checked)
continue;
....
}
You need to give the checkboxes the same name to have them grouped:
<input type="checkbox" name="food[]" id="chicken" value="chicken"/>Chicken
<input type="checkbox" name="food[]" id="meat" value="meat"/>Meat
And in your JavaScript function:
function SetHiddenFieldValue() {
var checks = document.getElementsByName("food[]");
var hiddenFieldVal = "";
for (var i=0; i<checks.length; i++) {
if (checks[i].checked) {
if (hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}
You forgot to test for checks[i].checked
function SetHiddenFieldValue() {
var checks = document.getElementsByName("checkbox");
var hiddenFieldVal = "";
for(i = 0; i < checks.length; i++) {
if (checks[i].checked) {
if(hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
}
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}
Hi your best to put the values into an array, makes it easier to then create the comma separated value. Also makes it a lot easier if you add more options later.
function SetHiddenFieldValue()
{
var checks = document.getElementsByName("checkbox");
var foods = new Array();
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
foods[i] = checks[i].value;
}
}
document.getElementById('my-item-name').value = foods.join(",");
}

Categories