Reputation: 4356
jQuery('#button1').removeClass('before');
jQuery('#button1').addClass('after');
is the code used to change a single button in Jquery. I want to know how to change a button based on what button is pressed, when I have buttons named button1, button2, etc.
Upvotes: 1
Views: 62
Reputation: 10530
If you use <button>
tags to create button then
$("button").click(function () {
$(this).toggleClass('after')
});
If you use <input type='button' />
then
$("input[type='button']").click(function () {
$(this).toggleClass('after')
});
See : http://jsfiddle.net/CWSY9/
Upvotes: 0
Reputation: 8393
Note, that rather than manually "removing / adding" a class you could use toggleClass. That aside, there are many ways to select multiple dom elements. Take a look at the available jQuery selectors.
For example you could use a class selector:
$('.before').toggleClass('after')
If you have a set of buttons that don't match a class selector but you know the id's you could do something like:
$('#number1, #number2').toggleClass('after')
EDIT:
Based upon your edit you could bind to a click event of the elements you want:
$('.before').on('click', function(e){
$(this).toggleClass('after')
});
Here is an example: http://jsfiddle.net/LqsqB/1/
EDIT 2:
If you wanted to bind to a click event you would do so on dom ready:
<script type="text/javascript">
$(function() {
$('.before').on('click', function(e){
$(this).toggleClass('after')
});
});
</script>
Upvotes: 1
Reputation: 5650
Ensure all the buttons are of the same class, say btnClass
. Then:
jQuery('.btnClass').click(function() {
jQuery(this).removeClass('before').addClass('after');
});
Upvotes: 1
Reputation: 1751
$(input[name^="button"]).removeClass('before')
$(input[name^="button"]).addClass('after')
This will select all input elements with name starting with button
as specified in your example. Check selector for more details.
Upvotes: 2