guihknx
guihknx

Reputation: 11

How to each 3 different buttons with different actions?

Well i have 3 buttons and these must have just a one class .fdm so how is possible every button have a different actions just calling the class?

I actually using, but like this i must set id to each button. I no want this, i wanna set just a classname and identify diff actins for all buttons.

JS:

jQuery(function(){
$('#r').bind('click',function(){
$('#alvo').css('background','#ff0000');
})
$('#g').bind('click',function(){
$('#alvo').css('background','#155c00');
})
$('#b').bind('click',function(){
$('#alvo').css('background','#001eff');
})
})

HTM:

<div id="alvo" style="width:200px;height:200px;border:2px #000 solid;">
</div>

<button class="fdm" type="button" id="r">R</button>
<button class="fdm" type="button" id="g">G</button>
<button class="fdm" type="button"  id="b">B</button>

Like i said i just wanted to use a classname to all buttons

Fiddle

Upvotes: 0

Views: 79

Answers (2)

Konrad Gadzina
Konrad Gadzina

Reputation: 3404

As you can't add other classes and and cannot use id, you can decide about action using the text of the button:

$(function(){
  $('.fdm').bind('click',function(){
    var text = $(this).text();
    if(text  == 'R')
        $('#alvo').css('background','#ff0000');
    if(text  == 'G')
        $('#alvo').css('background','#155c00');
    if(text  == 'B')
        $('#alvo').css('background','#001eff');
  }) ;    

});

Upvotes: 1

ripu1581
ripu1581

Reputation: 300

Updated the fiddle here

http://jsfiddle.net/EGn9z/2/

$(function(){

    $ ( ".fdm" ).click( function(){
        $('#alvo').css('background', $(this).attr("data-color"));
    });

})

<div id="alvo" style="width:200px;height:200px;border:2px #000 solid;">
</div>

<button class="fdm" type="button" id="r" data-color="#ff0000">R</button>
<button class="fdm" type="button" id="g" data-color="#00ff00">G</button>
<button class="fdm" type="button" id="b" data-color="#0000ff">B</button>

have put the colors in data-attribute

Upvotes: 3

Related Questions