HTML Button pressed - check status (not trigger when clicked) with Javascript

880 Views Asked by At

I am looking for a way to tell if a button is pressed as a state - note, this is something other than onclick functionality triggering action the moment the button pressing happens. Here is the js code (https://jsfiddle.net/tearex/812rkLpt/14/).

code

    <meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>

<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

<input  type="button" name="nomen" ID="first" value="1" onclick="one()"> 
<input  type="button" name="omen" ID="second" value="2" onclick="two()"> 

JS

function one(){
if (document.getElementById('first').clicked=="clicked") {alert('clicked')}
one();}

function two(){

document.getElementById('first').click();
if (document.getElementById('first').clicked=="clicked") {alert('clicked')}

}

Pressing button 1 should trigger a check of the button being pressed. Pressing button 2 should result in button 1 being pressed and in an alert confirming that this has happened.

Neither works. What is wrong with that?

Thanks

2

There are 2 best solutions below

2
17axaH On

You have the function "one" calls itself that affects an infinite loop.

Something like this. Hope this helps you.

function one(){
  if (document.getElementById('first').clicked !== "clicked") {
    document.getElementById('first').clicked = 'clicked'
  }
}

function two(){
  if (document.getElementById('first').clicked=="clicked") {
   alert('clicked')
  }
}

1
maverick On

I am not sure why "clicked=="clicked"" this is written. But when pressing Button 1 following code is working

  function one(){
           alert('clicked on number 1')
     }

And when pressing for Button 2, we can trigger the one()

function two(){

one(); }

and it is giving the alert.