Clubesorte
Clubesorte

Reputation: 63

How to output two different labels on two buttons?

I have this code that shows a label when clicking the button, but I need the following:

(function() {
  $('button').on('click', function() {
    $("#action").html("button was clicked");
  });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- this button has default style -->
<button>Action</button>

<label id="action"></label>

See example: https://jsfiddle.net/fr4x32g7/

Upvotes: 1

Views: 172

Answers (3)

devd
devd

Reputation: 703

(function () {
  var active = "";
  $('button').on('click', function (e) {
    var id = "#" + e.target.value;
    $(active).html("");
    active = id;
    $(id).html("button was clicked");
  });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- this button has default style -->
<button value="action">Action</button>
<label id="action"></label>
<button value="action1">Action</button>
<label id="action1"></label>

Upvotes: 2

Lajos Arpad
Lajos Arpad

Reputation: 76583

I assume that both labels are to be hidden initially and to show only one of them if the user clicks on a button. Here's a solution:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- this button has default style -->
<button data-label="action1">Action 1</button>
<button data-label="action2">Action 2</button>
<br>
<label class="action" id="action1" style="display:none;">button 1 was clicked</label>
<label class="action" id="action2" style="display:none;">button 2 was clicked</label>

and

$(function() {
  $('button').on('click', function() {
    $("#" + $(this).data('label')).show().siblings("label").hide();
  });
});

Fiddle: https://jsfiddle.net/0phz62ot/

Basically we bind the button with its label via an attribute and whenever a button is clicked, the label bound to it will be shown and the sibling labels will be hidden.

Upvotes: 2

Namysh
Namysh

Reputation: 4627

Does this solve the problem ?

(function() {
  $('#button1').on('click', function() {
    $("#action").html("button1 was clicked");
  });
  $('#button2').on('click', function() {
    $("#action").html("button2 was clicked");
  });
})();

    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- this button has default style -->
<button id="button1">Action1</button>
<button id="button2">Action2</button>


<label id="action"></label>

Upvotes: 2

Related Questions