Skip to content Skip to sidebar Skip to footer

How Do I Refresh The Contents Of A Single Div

I'm implementing a simple web-page, in that page, I have multiple div objects, what I'm trying to do is refresh the contents of a single div based on the user clicking a button or

Solution 1:

The simplest route if you're new to all of this is to change the html of the div. Given a div with id "ponies", you can change its contents via:

document.getElementById("ponies").innerHTML = '<p>new html block</p>'

If you want to swap out a div contents for another, you can opt instead to alter the DOM tree by a createChild after the div, and then removing the div. The innerHTML approach, while simple to understand, is a bit of a blunt (and slow) tool, compared to modifying the DOM itself. But if you're doing it rarely, and the html is simple, who cares?

If you have a form input for a forename then you can do:

functionshowForename(forenameDiv) {
    var text = "<p>Your forename is " + document.getElementById(forenameDiv).text + "</p>";
    document.getElementById("ponies").innerHTML = text; 
}

And put the call in the button's onClick event:

<inputtype="button"value="Who am I?"onclick="showForename('forenameinput')" />

Where forenameinput is the id of the forename form input. To learn more about all this stuff, look at the w3schools website.

Solution 2:

an example with jquery:

$("input.button").click(function(){
   $('div#content').load('ajax/test.php', function() {
      console.log('loaded.');
   });
});

Solution 3:

Based on @PhilH s answer here a cleaner jQuery solution:

jQuery( '#yourInput' ).click( function(){
    jQuery( '#ponies' ).text( 'You wrote: ' + this.value );
} );

Even in jQuery you can type in pure HTML if you want:

jQuery( '#yourInput' ).click( function(){
    jQuery( '#ponies' ).html( '<span>You wrote: <b>' + this.value + '</b></span>' );
} );

Post a Comment for "How Do I Refresh The Contents Of A Single Div"