1
    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.

4 Answers 4

2
$(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.

Sign up to request clarification or add additional context in comments.

Comments

1

Ensure all the buttons are of the same class, say btnClass. Then:

jQuery('.btnClass').click(function() {
  jQuery(this).removeClass('before').addClass('after');
});

1 Comment

Oops. I realized I asked the completely wrong question. I edited it to better say what I wanted.
1

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>

2 Comments

Looks good, but I need some more help (this is the extent of my experience with JQuery). Where do I put it? The code I currently have is here: pastebin.com/NcvNnpUy
@A.J. added another edit, you wouldn't bind a click event in the success callback of an ajax, but rather on ready.
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.