Checkbox checked property got ruined by the conditionals? - javascript

a beginner coder here (and also my first post).
I was trying to make function that will change the value of a previously defined variable when the checkbox is checked or unchecked. I tried to write this code to see if the checked property of my checkbox is working.
function calc5() {
var check5Object = document.getElementById("check5");
stat5 = check5Object.checked;
console.log(stat5);
}
When i checked the console, it works out like expected. When the checkbox is checked it logs true and when the checkbox is unchecked it logs false on the console like this.
I thought it was working smoothly... until i added the conditionals. The code looks like this:
function calc5() {
var check5Object = document.getElementById("check5");
stat5 = check5Object.checked;
if ((stat5 = true)) {
bobux5 = 10000;
} else {
bobux5 = 0;
}
console.log(stat5);
}
And the result on the console looks like
this
Everytime I click the checkbox, it just logs as "true" all the time. Can someone help me figure it out what went wrong in my code? It will be very helpful!
(btw im making a robux "scam" website that will rickroll you at the end, its harmless)

You need to use == and rather use =
From:
if (stat5 = true) {
bobux5 = 10000;
}
to:
if (stat5 == true) {
bobux5 = 10000;
}

Use this code:
function calc5() {
var check5Object = document.getElementById("check5");
var bobux5 = 0;
stat5 = check5Object.checked;
if (stat5 == true) {
bobux5 = 10000;
}
console.log(stat5);
}
in fact you should use == in conditions. => (if == X TURE) and (if = X FALSE)

Related

How to set the return value of a function based on a condition?

I am a beginner at Javascript and I am creating a form. The thing is I have a function that returns the value of the checkboxes (to check if they were checked or not) when the user submits his or her answer. I want to give the user a message if he / she does not select a value in the checkbox (not an error message). I have tried the following Javascript code:
function loopForm() {
var cbResults = " ";
var error = " You did not select a value";
for (var i = 0; i < myForm.elements.length; i++) {
if (myForm.elements[i].type == "checkbox") {
if (myForm.elements[i].checked == true) {
cbResults += myForm.elements[i].value + "<br />";
}
}
}
if (cbResults != undefined) {
return cbResults;
} else {
return error;
}
}
But when I submitted the results without checking the checkbox (once again this is not an error message) the message was not shown. (I stored the message in the error var). Can anyone help me solve this problem ?? Any help would be greatly appreciated. Please note that this is not my Full Code but just a portion of it.

Javascript basic loop help - basic

Im learning Javascript now and I got a question that's been bugging me!
So, all I needed to do here is to type a color on this input box, click the button and change the headline to the color typed only if that typed color is in the array specified in the variable.
My code is half working... it does check if whatever color typed is inside the array, but the alert button pops up each time, is there a way to make the alert pop up only if the color typed isn't in the array please?
Working code: https://codepen.io/anon/pen/ddPWLP
Javascript code:
const myHeading = document.getElementById('myHeading');
const myButton = document.getElementById('myButton');
const myTextInput = document.getElementById('myTextInput');
var colors = ["red", "black", "blue"];
myButton.addEventListener('click', () => {
for (var i=0; i<colors.length; i++){
if (myTextInput.value === colors[i]){
myHeading.style.color = myTextInput.value
} else {
alert("no color")
}
}
});
Don't do it inside the loop. Use a variable to flag when you find a match, and then after the loop check that flag and display the alert accordingly. Try this:
myButton.addEventListener('click', () => {
var found = false;
for (var i = 0; i < colors.length; i++) {
if (myTextInput.value === colors[i]) {
myHeading.style.color = myTextInput.value
found = true;
}
}
if (!found)
alert("no color");
});
By the way, you don't need a loop for that. You can simply use the indexOf() methods. If the value exists in the array, it returns its index, otherwise it returns -1. Try this:
myButton.addEventListener('click', () => {
if (colors.indexOf(myTextInput.value) > -1)
myHeading.style.color = myTextInput.value
else
alert("no color");
});

How to check if all controls on the page are empty?

I have a method that is supposed to loop over all of the controls on my page and return false if any one of them has a value other than empty string / null. This gets called as part of an OnSaveValidation. If the form is empty, they should be able to save.
function IsFormEmpty()
{
var ancestor = document.getElementById('PAIQIFunc'); //PAIQIFunc is the id of a div
var descendents = ancestor.getElementsByTagName('*');
var i = 0;
for (i = 0; i < descendents.length; ++i)
{
var e = descendents[i];
try
{
var eVal = $("#" + e).val();
// just check to make sure eVal has *some* value
if (eVal != '' || eVal != undefined || eVal != null)
return false;
}
catch (err){
//simply move on to next control...
}
}
return true;
}
Code sourced from Loop through all descendants of a div - JS only
In most cases, var eVal = $("#" + e).val(); throws an exception because it's a div or something like that. I'm only interested in the 108 drop down menus and 1 textbox on my form.
I set a breakpoint on my if statement and it was never hit. But descendents has like 1200 elements in it; I couldn't possibly step through it all trying to find what I'm looking for...
How else could I modify the code to check each control on the page?
EDIT: I should note that the web application is a C# / ASP.NET project using Razor views and we're using Telerik's Kendo web UI controls, not "vanilla" .NET controls if that makes a difference. So all of the controls are defined in the .cshtml file like so:
#(Html.Kendo().DropDownListFor(m => m.SomeProperty).HtmlAttributes(new { id = "cmbSomeProperty", #class = "k-dropdown-width-30", #tabIndex = "1", style = "width:60px" }).BindTo(ViewBag.SomePropertyDataSource).OptionLabel(" "))
You could try the following:
var hasValue = false;
var div = document.getElementById('PAIQIFunc');
$(div).find('input')
.each(function() { // iterates over all input fields found
if($.trim($(this).val()).length != 0) {
hasValue = true; // if field found with content
break;
}
});
if(hasValue === false) {
// save logic here
}
Hope this helps.

how to search and compare the items in the array gotten from the output of a loop after the loop is complete (javascript)

please im having a bit of a problem with my javascript code.... im working on a reminder app in Cordova and im using Katzer notification plugin... now i am coding in javascript and im having a little challenge. im trying to achieve a feature whereby , when a user tries to add a reminder that already exists, it will throw an error... and if the reminder dosen't exist, it will add it to the list of reminders.... im using as javascript loop for this... heres my code
function checkifReminderExists(){
cordova.plugins.notification.local.getAll(function (notifications) {
var allRemInfo = "";
var newAllRemInfo = "";
// using while loop
var count = 0;
while (count < notifications.length) {
cordova.plugins.notification.local.get(count, function (notification) {
allRemInfo = allRemInfo + notification.text ;
if(allRemInfo.indexOf(""+checkedBoxes+"") == true)
{
alert("sorry you cant add a reminder that already exist...");
} else {
alert("there is no similarity so im going ahead to create the reminder now...");
setLecReminders();
}
});
count++
continue;
}
});
}
/* the above did not work so i tried using for loop to achieve this
function checkifReminderExists(){
cordova.plugins.notification.local.getAll(function (notifications) {
var allRemInfo = "";
var newAllRemInfo = "";
var count;
for(count = 0; count < notifications.length; count++)
{
cordova.plugins.notification.local.get(count, function (notification) {
allRemInfo = allRemInfo + notification.text + ", " ;
newAllRemInfo = new Array(""+allRemInfo+"");
if(newAllRemInfo.indexOf(""+checkedBoxes+"") == true)
{
alert("sorry you cant add a reminder that already exist...");
} else
{
alert("there is no similarity so im going ahead to create the reminder now...");
setLecReminders();
}
});
}
});
}
I tried both methods(for and while loop) above and none of them gave me my result... instead the "if()else" test will run separately on each of the loop...the disadvantage of this, is that when a test runs on the first item in the list of reminders, the setLecReminders(); function runs irrespective of if the subsequent test are true or false... i want a solution whereby the loop runs completely first and all items on the list are outputted into an array and then i can use a if()else test on all members of the array simultaneously. Please pardon my long question... thanks in advance
I would suggest setting a boolean inside of your loop like this:
var reminderExists = false;
while (count < notifications.length)
{
cordova.plugins.notification.local.get(count, function (notification) {
allRemInfo = allRemInfo + notification.text;
if (allRemInfo.indexOf(""+checkedBoxes+"") == true)
{
reminderExists = true;
}
count++;
}
Then you can check the boolean outside of the loop and show your alerts based on that result:
if (reminderExists) {
alert("sorry you cant add a reminder that already exist...");
} else {
alert("there is no similarity so im going ahead to create the reminder now...");
setLecReminders();
}

Chrome removes property value

I think I've run into a possible bug in chrome, but wondering if this is something I'm doing wrong. I am collecting data from an IndexedDb and adding this to an array BUT one property was always empty so I started debugging.
Below is my code for the onsuccess function and below that is a print screen of one of the rows from my console.log with one property marked with yellow. Notice how this exists and has a value!
On my second image which is when I "open" the object in chrome developer tools to see how it looks, I noticed that Title is undefined. What am I missing? What causes this behavior?
This exact code is working on the same site, just another page.
cursorRequest.onsuccess = function (evt) {
var cursor = evt.target.result;
if (cursor) {
var pushItem = true;
if (opts.searchCriterias && opts.searchCriterias.length > 0) {
pushItem = false;
for (var i = 0; i < opts.searchCriterias.length; i++) {
if (opts.searchCriterias[i].values.contains(cursor.key)) {
if (opts.includeKeyInResponse == true) items.push({ key: cursor.primaryKey, value: cursor.value });
else items.push(cursor.value);
}
}
}
if (pushItem) {
if (opts.includeKeyInResponse == true) items.push({ key: cursor.primaryKey, value: cursor.value });
else {
items.push(cursor.value);
}
console.log(cursor.value);
}
cursor.continue();
}
};
Title exists and have value
Title exists but is undefined (This is same as above, just expanded)

Categories

Resources