0

I want to prevent reloading the page on button click. On click I just want to swap the button values not refresh the page. How can I do so?

<button id="4">134</button> // button 1 
<button id="5">234</button> // button 2 

After clicking button 1 (button with id of "4") I want the following result

// After clicking button 1
<button id="4">234</button> // button 1
<button id="5">134</button> // button 2 

How can I do this without reloading/refreshing the html page.

knownasilya
  • 5,998
  • 4
  • 36
  • 59
user1934833
  • 33
  • 1
  • 5
  • 1
    Can you give us a code example of what you already have? – jharig23 Dec 28 '12 at 15:56
  • 134 // button 1 //button 2 .....onclick of button id(4)..the value of id=4 and id=5 swap i.e(234 will be on id=5 and 134 will be id=4).Without reloading/refreshing of html page. – user1934833 Dec 28 '12 at 16:00
  • @user1934833, I updated my answer to provider some direction. Have a look. http://stackoverflow.com/a/14072548/358834 – Mechlar Dec 28 '12 at 17:09

3 Answers3

6

To prevent the refresh just add type="button"

<button id="4" type="button">134</button> 
<button id="5" type="button">234</button>

As for swapping values I reiterate bmargulies, you need to learn javascript, or make your question more clear so we can give you a better answer.

But with your vague question (stating that after clicking #4 the text should swap) here is some direction using jQuery. Doing it this way will only swap it once.

<script type="text/javascript">
    $(function(){
        $('#4').click(function(){
            $(this).html(234);
            $('#5').html(134);
        });
    });
</script>

For help with jQuery: http://api.jquery.com/

Mechlar
  • 4,946
  • 12
  • 58
  • 83
2

You have asked an extremely broad question, and it's not related to HTML5 at all. To get this functionality, you have to attach javascript handlers to your buttons. There are many different javascript libraries that can help you with this, or you can write raw javascript.

You will have to go do a lot of basic learning about coding in javascript to accomplish this.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
0

Your main problem of page reload is solved by the UpHelix's answer. The default type for a button on many browsers is reset, which results in reload of page as stated in an answer to problem How do i make an html button not reload the page?

And regarding your task for value swap, my code does the work for you

$(function() {
        $('button#4').click(function() {
            var firstButtonVal = $('button#4').text();
            var secondButtonVal = $('button#5').text();
            $('button#4').text(secondButtonVal);
            $('button#5').text(firstButtonVal);
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="4" type="button">134</button>
<button id="5" type="button">234</button>
Community
  • 1
  • 1
Savitoj Cheema
  • 460
  • 2
  • 9
  • 22