Ozil
Ozil

Reputation: 21

Javascript disable a clickable image when other image is clicked

i have two buttons and alert functions on both buttons. i want that if user click on 1st button the function on 1st button should work but when user click the 2nd button then the function on 1st button should not not work i mean the function should not work on 1st button if user has clicked on 2nd button. below is the code but it is not working:

<script>
function abc(){
    alert ("its a alert box!");
}

function xyz(){
    var a=150;
    alert(a);
}

<body>
<input type="button" value="submit 1" onClick="abc();">

<input type="button" value="submit 2" onClick="xyz();">
</body>

Upvotes: 0

Views: 136

Answers (4)

J E Carter II
J E Carter II

Reputation: 1506

You could use jquery to unbind the click event for the first button when the second button is clicked. But you would need to add some id attributes so that you can do so easily.

<body>
<script>
function abc(){

   alert ("its a alert box!");
}
function xyz(){
   $('#btn1').unbind('click');
   var a=150;

   alert(a);   
}
</script>

<input id="btn1" type="button" value="submit 1" onClick="abc();"></input>

<input id="btn2" type="button" value="submit 2" onClick="xyz();"></input>
</body>

You could also further refine your code to not rely on inline onclick attributes.

$(document).ready(function(){
     $('#btn1').click(abc);
     $('#btn2').click(xyz);
})

Upvotes: 2

Habibur Rahman
Habibur Rahman

Reputation: 637

try this

<div>
<input id="button1" type="button" value="Click1"/>
<input id="button2"type="button" value="Click2"/>
</div>

<script>
$('#button1').on('click', Button1Click);
$('#button2').on('click', Button2Click);

function Button1Click() {
    alert("You have clicked button 1");
}

function Button2Click() {
    alert("You have clicked button 2");
}

Upvotes: -1

Zach Lysobey
Zach Lysobey

Reputation: 15724

For starters, don't use inline click handlers. IMHO, something like this would be nicer:

<script>
$(document).ready(function(){

    function abc(){
       alert ("its a alert box!");
    }

    function xyz(){
       var a=150;
       alert(a);   
    }

   var bt1enabled = true;
   $('body').on('click', 'input[type=button]', function(){
      if(this.id==="btn1" && bt1enabled) {
          abc();
      } else if (this.id==="btn2") {
          btn1enabled = false; // or btn1enabled = !btn1enabled if this is supposed to toggle
          xyz();
      }
   });
}):
</script>

<body>
  <input id="btn1" type="button" value="submit 1"></input>  
  <input id="btn2" type="button" value="submit 2"></input>
</body>

Upvotes: 0

Joris Lindhout
Joris Lindhout

Reputation: 205

With jQuery (since it is one of the tags you gave to the post) you can work with unbind.

Upvotes: 0

Related Questions