onclick function executes without any click on JavaScript - javascript

I am working with some JavaScript and Ajax functions. I am going to put some code while I explain myself to be more clear.
I have this element: <div id="divTest" onclick="test()">YES</div>
When the user clicks the DIV, the function replaces the "YES" for something like this:
YES <input type="radio" name="testing" value="YES" onclick="test_2(this.value)" checked />
NO <input type="radio" name="testing" value="NO" onclick="test_2(this.value)" />
This allows the user to select again the right option. Then I want to replace the radiobuttons with new value, so when the user selects any option, the DIV replaces the "radio" options and displays the value selected (YES OR NO) as it was on the beginning.
At this point everything works perfect.
Here is my problem:
I want the DIV to have the onclick() as the beginning onclick="test()" so I do it from JavaScript giving it the property this way: div.onclick = function() { test();};. The function test() is executed even if the user does not click on the div. It executes both function right away and does not wait until there is a click on it.
Does anyone knows how can I make the function to wait until there is any click on it? Am I giving the onclick property incorrectly?
I hope I made myself clear.
Here are the functions:
function test() {
var div = document.getElementById("divTest");
//I DO NOT INCLUDE THE AJAX CODE BUT THE RESPONSE INCLUDE THE RADIO BUTTONS METIONED ABOVE
div.innerHTML = xml.responseText();
}
function test_2(newValue) {
div = document.getElementById("newValue");
div.innerHTML = newValue;
div.onclick = function() { test(); };
}

Yes, your problem is with div.onclick = here you are actually assigning a click action to your div! Which will execute when your page loads.
What you want is to assign an event listener like so.
div.addEventListener('click' function(){});

I have got the same problem and I found this page. I check the spec of addEventListener and I found out I typed an excessive pair of bracket.
Two ways to do this:
1.use anonymous function(that is without a name, defined just in time to use) like the above answer.
2. you can't add the bracket. simply use ('click', myfunction).
If you want to use parameter, wrap your function into an anonymous function. like this:
div.addEventListener('click', function(){myfunction(e){}}).
it's a little bit late, hope you can read it and solve your problem.

Related

How to execute an event with javascript only after a button is clicked or other event has happened?

So I have this function called check1 which executes when you click a specific submit button (last say this is button1). Now i want a new function to execute when you click another button (last say button2) that checks whether the first button(and event thats linked to it) is clicked/ excecuted.
Example:
function check1 () {
document.getElementById("id1").innerText= "hello";
}
button1.addEventlistener("click", check1);
button2.addEventlistener("click", check2);
(The code i'm asking about:)
function check2 () {
if (button 1 is clicked/ check1 is executed) {
document.getElementById("id2").innerText= "hello you";
} else {
document.getElementById("id2").innerText= "First click the other button";
My code is quite complicated and since im not a native english speaker, it will be hard for me to explane. That's why im using this simple example. I only want to know how you (and if you) can check in javascript if a specific other button is click beforehand / how you can check in javascript if a other function is already been executed.
I hope you guys can help me!
Your best option here is most likely to use custom attributes. You can then use Javascript to discern whether the custom attribute is added to the first button and if it's not present, then you can throw the error
document.getElementById("id1").setAttribute("clicked", "true");
This line will set the custom attribute on the button, then you can use the following to know if it it’s on the button
document.getElementById("id1").hasAttribute("clicked");
If you don't need to worry about people F12 hacking then I'd add a hidden input:
<input type="hidden" value="0" id="btn_CheckValue"/>
Then have an onclick="buttonClicked()" on the button
function buttonClicked(){
document.getElementById("btn_CheckValue").value = "1";
}
Then do your function checks on the second button.
function check2 () {
let btnValue = document.getElementById("btn_CheckValue").value
if (btnValue == 1) {
document.getElementById("id2").innerText= "hello you";
} else {
document.getElementById("id2").innerText= "First click the other button";
An example:
https://jsfiddle.net/tgm7avhb/51/

Javascript not checking radio button

The following script is not checking working when testing the radio button
<script type="text/javascript">
function checkButton(){
if(document.getElementById('Revise').checked = true){
alert("hello");
}
}
</script>
The html code is:
<form:radiobutton id= "Revise" value="Revise" name="status" path="status"></form:radiobutton>
Do i need to call the function/or place it in the body?
As most people have mentioned within their comments, you either need to
write
if(document.getElementById('Revise').checked === true)(newbie way)
or
write if(document.getElementById('Revise').checked) (pro way)
Also, you haven't invoked the function "checkButton", this is how you do it:
<form> <input type="radio" id= "Revise" value="Revise" name="status" path="status" onclick="checkButton()"> Click Me!! </form>
First off, your code is not working because you defined a function (checkButton) that never make a call to, thus it is never executed.
I'm not sure of what you are trying to do but you should avoid using in-line javascript.
If you are trying to run the alert when the radio button is clicked then add an click event listener on the radio.
document.getElementById('Revise').addEventListener('click',function() {
alert('Hello');
});
JSFindle
If you are trying to define a function called checkButton that checks your radio and shows an alert then your function would be defined like this:
function checkButton() {
document.getElementById('Revise').checked = true;
alert('Hello');
}
JSFindle
And then you would just invoke checkButton() on your trigger.

How can I display alert box to users unless they click a specific button

I have set up a page with a form that users can make changes to using PHP. When they try to navigate away from the page or refresh, an alert box appears using JS. However when they click the Save button the alert box still appears.
Is there any way I can stop the alert box appearing when the user clicks on the save button?
here is my JS:
var needToConfirm = true;
$('#save').click(function(){
var needToConfirm = false;
})
if (needToConfirm == true)
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Here is my HTML (just the button): -->
<input type="submit" id="save" />
<input type="hidden" id="save" name="submitted" value="TRUE" />
If I understand correctly, you don't want to show the confirmation dialog when someone clicks the save button right? Why not just deregister the onbeforeunload method in that click handler like so:
window.onbeforeunload = confirmExit; //By default assign the confirmExit
//If user clicks on save, just set it to null.
$('#save').click function(){
window.onbeforeunload = null;
}
This way, you don't need to maintain a separate variable called needToConfirm. Also, try to understand the way javascript executes your code. It does it line by line. So, your needToConfirm defined inside the click handler right now gets set to false when the user clicks save. But even before that callback is called, you already have bound the onbeforeunload event as the default value of needToConfirm is true.
Try to also keep in mind the scoping of variables in javascript. If you redefine variable needToConfirm inside a click handler it would not necessarily access the "global" variable you intend to share across different functions. And ofcourse, like other people pointed out, don't use the same id for different HTML elements. It is not supposed to be used like that.
First of all, you are not executing your conditional code inside the if statement. It is out of it, fix that and try again. If it still doesn't work then try the following:
The page get refreshed before the $("#save").click() returns anything (in this case, needToConfirm = false. Therefore the alert box appears as usual. You have to modify your html as follows:
<input type="button" id="save" />
and use javascript to actually submit the form... You can do that as follows:
$("#save").click(function() {
var needToConfirm = false;
$("#idOfForm").submit();
return false;
}
Also, change ID of one of the buttons as 2 elements can never have the same ID... or use class instead!

Clearing a Function in JavaScript

This may seem like a simple question. I've tried to Google the answer, but I can't seem to find it so that's why I'm here for help. Part of the problem is that I can't really phrase the question properly, so I will try to explain it here. Here goes...
I have two functions in my JavaScript file (let's name them fn1() and fn2()). I am calling these functions using onclick in my HTML file. For example:
<span class="test" onclick="fn1();">Button #1</span>
<span class="test" onclick="fn2();">Button #2</span>
The functions work perfectly fine when a user clicks on their respective buttons. However, if a users clicks on Button #1, and then Button #2 - both functions are called/loaded simultaneously.
Question: How do I make it so that fn1() is disabled (or cleared) as soon as the user clicks on Button #2, which will load fn2()?
Thank you.
You can use jQuery way the noop method
Within fn1() function you should use $.noop() to empty the function fn2()
Or simply as you are calling it on onclick you can remove that attribute within that function. (I don't recommend to use this)
$('span.test').not($(this)).removeAttr('onclick');
But I extremely recommend to use namespace by which you can unbind the click event like the following instead of calling inline javascript:
The on method
$( "span.test" ).on( "click.something", function( event ) {
//do your stuff here
});
Later you can unbind the click event like this:
The off method
$("span.test").off("click.something");
The nice way: disable the fn2 button when you enter fn1 (rather than disabling the function). This also has a side effect of letting the user know that the button is not available. Disabled elements do not fire 'click' events.
$('span.test').not($(this)).prop('disable', true);
The not-so-nice-way: set a variable when you're in one function, and clear it when you exit. Return early from the functions if the variable is set.
The downright ugly way: unbind the onclick from the other buttons if one is clicked. This is so messy that you really don't want to do that.
The I-really-can't-recommend-it-less way: redefine the other functions with no-ops.
I don't know if I understand your question correctly and I don't have enough rep to comment
but if you want the user not to be able to press the second button until the first finishes execution then you could do the follwing
in the first line of your fn2() add the following line
document.getElementById("button1").disabled = true
but you should first give an id button1 to the first button
this will grey the button button1 when the user press the button
after your code finishes execution you should add:
document.getElementById("button1").disabled = false
this will make the button pressable again
u may try this with flags, this is not going to clear the function e.g.:
var runFn1 = true;
function fn1() {
if (!runFn1) {
return;
}
// ur code here
}
function fn2() {
runFn1 = false;
// ur code here
}
"The functions work perfectly fine when a user clicks on their respective buttons. However, if a users clicks on Button #1, and then Button #2 - both functions are called/loaded simultaneously."
javascript being single threaded. fn1() execution is first completed and then followed by fn2(). Hope you understand there will not be a case where both are called simultaneously.
For example
function fn1(){
while(true){
}
}
function fn2(){
alert("2");
}
<input type="button" value="Btn1" onClick="fn1();"/>
<input type="button" value="Btn2" onClick="fn2();"/>
Try invoking fn1(). you will be surprised fn2() cannot be invoked!

Javascript function only executing one line

I've got a div that starts out as hidden, and shows up when a button is clicked. There is another button on the div, and the onclick event calls this function:
function popuppage2OK() {
alert("you clicked ok!");
var x = new Object();
x.name = $("#boxforname").val(); //this is a text input
x.option = $("#boxforoption").val();//this is a text input
alert("hiding newfactorpage2");
$("#popupform").hide(); //this is a div containing the text inputs and the button with the onlcick event that calls this function
alert("popupform hidden");
displaystuff(); //another function ive written that needs to be called
alert("this is after the display attempt");
}
My probelm is that the only line that seems to execute is the line to hide the div. None of the alert boxes appear, and the displaystuff() function doesn't get executed, but the div does go back to being hidden. Any thoughts on why lines of code might get skipped like that?
When do you attach the eventhandler to the button inside the div ?
You should do it after the page has done loading, so in Jquery you can do something like:
$(document).ready(function () {
//attach the eventhandler here
})
Usually this kind of behavior happens when you've got an error in your javascript. Check to ensure that all of your selectors are valid and that there aren't any errors elsewhere.

Categories

Resources