Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to a jquery function from a button click

Tags:

jquery

I have to be able to change the colour of text via three buttons (red, blue and black)

The function I have, which works fine is as follows:

function btn_click() {
$("#col1 p").css("color", "#00f");
    }

I need to pass two variables to this function, the specific tag (e.g. col1 p) and the hex value from the following function call:

<input type="image" value="" class="but-blue" onclick="btn_click();" />

Can anyone help?

like image 232
Steve Harwood Avatar asked Dec 09 '11 07:12

Steve Harwood


4 Answers

Change script to:

function btn_click(selector, color) {
    $(selector).css("color", color);
}

And inline handler to:

<input type="image" value="" class="but-blue" onclick="btn_click('#col1 p','#00F');" />

update

But with jQuery you can do following:

<input type="image" value="" class="but-blue" data-selector="#col1 p" data-color="#00F" />

and jQuery script itself:

$(document).ready(function(){
    $('input[type=image]').click(function() {
       var selector = $(this).data('selector');
       var color = $(this).data('color');

       $(selector).css("color", color);
    });
});
like image 50
Samich Avatar answered Nov 11 '22 13:11

Samich


If you want to go full-JQuery, do the Following

function btn_click(selector, color) {
    $(selector).css("color", color);
}

$("input").bind("click", function(event) {
    btn_click($(this).attr("goal-selector"), $(this).attr("goal-color"));
});

And then in your HTML

<input type="image" value="" class="but-blue" goal-selector="#col1 p" goal-color="#00f" />

Good luck :)

like image 37
Willem Mulder Avatar answered Nov 11 '22 14:11

Willem Mulder


something like this? :

function btn_click(selector, color) {
    $(selector).css("color", color);
}

and the onclick function would be:

<input type="image" value="" class="but-blue" onclick="btn_click('#col1 p','#00f');" />
like image 2
Willem Avatar answered Nov 11 '22 12:11

Willem


Aren't this be better:

<input type="button" value="#00F" class="button-color"  />
<input type="button" value="#0FF" class="button-color"  />
<input type="button" value="#FFF" class="button-color"  />
<div id="you_need_to_change"></div>
<script type="text/javascript">
$('.button-color').click(function(){$('#you_need_to_change").css("color", $(this).val())});
</script>
like image 2
Serge Avatar answered Nov 11 '22 14:11

Serge