How do I manipulate a boolean in a function? - javascript

I'm trying to change inputX[0] from false to true, then get an alert if it worked. Unfortunately I don't get the message that inputX[0] was set to true. Do you have any ideas?
<body>
<div>
<button id="S1" onclick="btnManager(this);"></button>
</div>
<script>
var inputX = new Array();
definedInputs();
btnManager();
question();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == (id = "S1")) {
inputX[0] = true;
}
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>

try with this:
<body>
<div>
<button id="S1" onclick="btnManager(this);"></button>
</div>
<script>
var inputX = new Array();
inputX[0] = false;
function btnManager(pressedBtn) {
inputX[0] = !inputX[0];
alert(inputX[0]);
}
</script>
</body>
With this, every you push the button the value will be set by the negation of the current value, hope it helps.

It is important that you understand the Js lifecycle.
First javascript objects and functions are built and
then the code is executed, in this case it happens as follows:
The array "inputX" is created
Using the function "definedInputs()" defines "inputX[0] = false"
"btnManager()" is executed but since it is not assigned a parameter, the value of "pressedBtn.id" is "undefined" so the state of "inputX[0]" does not change
The status of "inputX[0]" is queried using "question()", but since "inputX[0]" is still false, no alert is fired.
All of this happens before you can press the button.
Pressing the button executes "btnManager(this)" and since the id is equal to "S1" the state of "inputX[0]" changes to true.
But you can't see this change because the "question()" function has already been executed.
Try:
<!DOCTYPE html>
<html>
<body>
<div>
<button id="S1" onclick="btnManager(this);">Test</button>
</div>
<script>
var inputX = new Array();
definedInputs();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == "S1") {
inputX[0] = true;
}
question();
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
</html>

Add some console logs to see what is happening. If you do, you'll see that all of your functions are executing immediately. When you click the button and enter the btnManager() function what happens next? As you'll see, your code is executing the btnManager() function but then what about checking for your alert?
If you call question() after your if statement, then you'll run your check again.
You could do this with less lines, but for the sake of keeping your exact code and making it work, this is how you would achieve your goal:
<body>
<div>
<button id="S1" onclick="btnManager(this);"></button>
</div>
<script>
var inputX = new Array();
// You could really remove these and do it like Lucretius's Answer
definedInputs();
btnManager();
question();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == (id = "S1")) {
inputX[0] = true;
}
question();
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>

You're comparing the value of pressedBtn.id which is a text string S1 to a true/false Boolean evaluation (id == "S1") which will always be false because text strings and boolean values are not the same. Since (id = "S1") is an assignment, and you can't compare an assignment, this is what I am guessing you're trying to do.
'S1' == true will always be false
'S1' == false will also always be false.
Instead of:
function btnManager(pressedBtn) {
if (pressedBtn.id == (id == "S1")) {
inputX[0] = true;
}
}
Just evaluate the id and then log it to console to make sure the input array is updated.
<body>
<div>
<button id="S1" onclick="btnManager(this);">Click</button>
</div>
<script>
var inputX = new Array();
definedInputs();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == "S1" ) { //fixed
console.log( pressedBtn.id == (id == "S1") ); // breaks, undefined
}
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>
Here is your code fixed.
You don't need to call btnManager(); or question(); immediately since these are called in a cascading fashion after the button click event is fired. The only "pre-work" your code needs to do on load is to defineInputs(); so those two lines were removed.
<body>
<div>
<button id="S1" onclick="btnManager(this);">Click</button>
</div>
<script>
var inputX = new Array();
definedInputs();
function definedInputs() {
inputX[0] = false;
}
function btnManager(pressedBtn) {
if (pressedBtn.id == "S1") {
inputX[0] = true;
console.log( "true" );
}
}
function question() {
if (inputX[0] == true) {
alert("inputX is set to true");
}
}
</script>
</body>

Related

How a make a comparison values on button click?

When the user clicks on the button, you need to compare the values ​​in certain fields and display the values ​​according to the template.
I know this is a very stupid question, but I can't make it so that all values ​​are "true" and the function is considered executed and the button works out the correct values
I try like this
function serviceCheck() {
function serviceCheck1() {
var CasePageServiceSelector = document.getElementById('CasePageServicePact00d7746a-0675-49ac-8608-323407985e07ComboBoxEdit-el').value;
var ServiceDocument = 'Case';
if (CasePageServiceSelector === ServiceDocument){
console.log('1')
}
}
function serviceCheck2() {
var CasePageServiceCategSelector = document.getElementById('CasePageServiceCategoryComboBoxEdit-el').value;
var ServiceCateg = 'Talker';
if (CasePageServiceCategSelector === ServiceCateg){
console.log('2!')
}
}
function serviceCheck3() {
var CasePageServiceItemSelector = document.getElementById('CasePageServiceItemComboBoxEdit-el').value;
var ServiceItem = '4. Problem';
if (CasePageServiceItemSelector === ServiceItem){
console.log('3')
}
}
}
function ChangeSecondTA() {
let Theme = $('#CasePageSubjectTextEdit-el').val('template');
let Symptoms = $('#CasePageSymptomsHtmlEdit-el').val('template2 ');
}
function onButtonClick(event) {
try {
alert(serviceCheck)
} catch (error) {
console.error("error: ", error);
}
};
At first, you write the function serviceCheck() and you call it using: alert(serviceCheck)
Why do you use alert, if your function does not return anything?
Secondly, you write three functions serviceCheck1-3() however you newer call these functions.
you need write something like this:
function serviceCheck() {
let in1 = document.getElementById('input1').value;
let in2 = document.getElementById('input2').value;
if (in1 == in2) {
alert('true');
} else {
alert('false');
}
}
function onButtonClick() {
serviceCheck();
};
<html>
<head></head>
<body>
<button onclick="onButtonClick()">input1 == input2 ?</button>
<br><input id='input1' type="text" value="55">
<input id='input2' type="text" value="55">
</body>
</html>

Get value from button in while loop

I've got a while loop with multiple buttons, they are like this:
<button onclick="confirmDelete()" value="<?php echo $game['id'];?>" name="deleteButton">Delete </button>
It is followed by the following confirm message:
<script>
function confirmDelete() {
var r = confirm(" **HERE I WANT THE ID TO START WITH** ");
if (r == true) {
// delete
} else {
// cancel
}
}
</script>
Each button has his own value, but now i want that value in my javascript when i click on that button. I tried multiple things but cant make it work.
EDIT:
If someone can tell me an better/easier way to do this, you're welcome to tell me
Use your function with this argument, i.e.:
<button onclick="confirmDelete(this)" id="myButton" value="someId" name="deleteButton">Delete </button>
<script>
function confirmDelete(elem) {
var r = confirm(" **HERE I WANT THE ID TO START WITH** ");
var theValue = elem.value; //someId
var theId = elem.id; //myButton
if (theValue == "True") {
alert("True")
} else {
alert("False")
}
}
</script>
LIVE DEMO:
http://codepen.io/anon/pen/QyZgqO
Pass the game ID into the confirmDelete function as a parameter
<button onclick="confirmDelete(<?php echo $game['id'];?>)" name="deleteButton">Delete </button>
<script>
function confirmDelete(id) {
var r = confirm(id);
if (r == true) {
// delete
} else {
// cancel
}
}
</script>

Javascript function doesn't break on return?

I know you are supposed to be able to break out of an each statement by returning, which is what I'm trying to do, but I must be doing something wrong and it seems so simple I can't find it.
I have code like this
function create() {
var test = hasThing();
if (test) {
$('#myForm').submit();
} else {
alert('you suck!')
}
}
function hasThing() {
$('.selects').each(function() {
if (this.value != "") {
return true;
}
});
return false;
}
I have set breakpoints on "return true;" and hit it but var test is always false because for some reason the .each() loop continues and the hasThing() function continues. I've tried switching things around so that I return false in the .each() just in case for some reason that mattered but it didn't change anything.
I don't get it. Seems counter to how the documentation says it should work.
Your return true; statement returns from the anonymous function given to each. The return false; line is always executed which explains why var test is always false.
Change your code to
function hasThing() {
var hasThing = false;
$('.selects').each(function() {
if (this.value != "") {
hasThing = true;
return false; // breaks the $.each, but does not return from hasThing()
}
});
return hasThing;
}
You could use Array.some() to check if any of the selects have a selected value
function hasThing() {
return $('select').toArray().some(function(el) {
return el.value != "";
})
}
function create() {
var test = hasThing();
if (test) {
alert('at least one select was changed');
//$('#myForm').submit();
} else {
alert('you suck!');
}
}
function hasThing() {
return $('select').toArray().some(function(el) {
return el.value != "";
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Select at least one option !</p>
<form id="myForm">
<select class="selects">
<option value="">blank</option>
<option value="2">option1</option>
</select>
<select class="selects">
<option value="">blank</option>
<option value="2">option1</option>
</select>
<input type="button" onclick="create()" value="submit" />
</form>

Return false does not prevent form submission

I have form that I need to validate using JavaScript and I need to show all the messages at the same time. E.g if the first name and surename is missing for two messages to appear. I've got this working with the below code but the form is still being returned back to the server. P Lease see below:
function validateForm() {
var flag = true;
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "First name is required";
flag = false;
} else {
document.getElementById("fNameMessage").innerHTML = "";
}
var x = document.forms["myForm"]["surname_5"].value;
if (x == null || x == "") {
document.getElementById("sNameMessage").innerHTML = "Surename is required";
flag = false;
} else {
document.getElementById("sNameMessage").innerHTML = "";
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
flag = false;
} else {
document.getElementById("titleMessage").innerHTML = "";
}
return flag;
}
My form and event :
<form action=""method="post" accept-charset="UTF-8" name="myForm" onsubmit="return validateForm();">
My Button:
<input type="submit" class="button" name="submit" id="submit" value="Submit">
Your code:
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title")
... triggers an exception and you don't catch it:
Uncaught TypeError: Cannot read property 'options' of undefined
Thus JavaScript code stops running.
Since everyone seems to be providing jQuery answers and I didn't see anything in your orignal code that was jQuery-esque I'll assume you aren't using jQuery.
You should be using the event.preventDefault:
Sources:
https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.submit
document.getElementById("submit").addEventListener(
"click", validateForm, false
);
function validateForm(){
// We should not assume a valid form!
var formValid = false;
// All your validation code goes here
if(formValid){
document.forms["myform"].submit();
}
}
try something like
if(flag){
document.getElementById("submit").submit();
}
else{
$('#submit').click(function (e) {
e.preventDefault();
});
}

How to put IF CONDITION with an AND CONDITION and the NOT OPERATOR in javascript?

<body>
<input type="radio" name="other_charges" value="To Pay" >To Pay
<input type="radio" name="other_charges" value="COD" >COD
<input type="submit" onclick="sum_cash()"/>
</body>
here is my html ...in this i am having two radio buttons with different values and i have called a function using onclick event....here is the code...
<script type="text/javascript">
function sum_cash() {
var elements_ocharges = document.getElementsByName('other_charges');
for (var i = 0; i < elements_ocharges.length; i++) {
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
}
var val_ocharges=value_ocharges;
if (val_ocharges=="To Pay") {
alert("pay");
}
if (val_ocharges=="COD") {
alert("cod");
}
if ((val_ocharges!="COD") && (val_ocharges!="To Pay") ) {
alert("hi");
}
}
</script>
Now in the function, I am checking the value of the radio button selected. If the user chooses the Pay radio button then on clicking the submit button it alerts the user for payment. When the user chooses the COD radio button then on submitting it alerts COD.
What I want is that when the user has selected nothing and clicked on the submit button then it should alert the user. Unfortunately, it is not checking the condition. Can anyone please help me?
You may try like this:
<script type="text/javascript">
function sum_cash()
{
var elements_ocharges = document.getElementsByName('other_charges');
var value_ocharges = null;
for (var i = 0; i < elements_ocharges.length; i++)
{
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
}
var val_ocharges=value_ocharges;
if(val_ocharges=="To Pay")
{
alert("pay");
}
else if(val_ocharges=="COD")
{
alert("cod");
}
else
{
alert("hi");
} }
</script>
your problem is this conditional near the top:
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
since neither radio button is checked, value_ocharges is never set. this will cause an error when you attempt to access the value with var val_ocharges=value_ocharges; you should set the value of value_ocharges to something (null is fine) before entering your loop, then everything will work:
<script type="text/javascript">
function sum_cash()
{
var elements_ocharges = document.getElementsByName('other_charges');
var value_ocharges = null;
for (var i = 0; i < elements_ocharges.length; i++)
{
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
}
var val_ocharges=value_ocharges;
if(val_ocharges=="To Pay")
{
alert("pay");
}
if(val_ocharges=="COD")
{
alert("cod");
}
if ((val_ocharges!="COD") && (val_ocharges!="To Pay") )
{
alert("hi");
}
}
</script>
Try this ,
else if ((val_ocharges =="")
{
alert("hi");
}
Hope this helps!!
First, set your value_ocharges above the for loop:
var value_ocharges = false;
Then, instead of:
if ((val_ocharges!="COD") && (val_ocharges!="To Pay") ) {
alert("hi");
}
use this outside of the loop:
if (!val_ocharges){
alert("hi");
}
Basically, this checks if val_ocharges is defined somewhere in the loop, and if it's not, it triggers the alert.

Categories