Home > Software engineering >  JQuery how to refresh a div with button click
JQuery how to refresh a div with button click

Time:02-02

I would like to refresh a div element when clicking on a button. This question was asked before, but for some reason it does not work for me. Since I am new to programming, I am sure I'm missing something really obvious.

I found this already:Stackoverflow link

This is the code that I have now, based on the first answer of the above link. What I want, is that the time updates to the current time when I click on the button. But the time does not change.

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>
 $("button").click(function(){
$("#test").load(" #test > *"); //as found on 
});
</script>

<script>
function updateDiv()
{ 
    $( "#here" ).load(window.location.href   " #here" );
}
</script>
</head>
<body>

<button onclick="updateDiv()">click me</button>

<p><div id="test">
<?php
echo "The time is " . date("h:i:sa");
?>
</div>
</p>

</body>
</html>

CodePudding user response:

Not knowing what exactly you are after, here is an example that just overwrites the contents of the div with the current time, and not from the a url.

//wire up the click event to set the text of the div  (using momentjs for datetime cause its easy)
$("#refresh").on("click", () => $("#refreshable").text(moment()));
//call the click event so it happens a first time.
$("#refresh").click();
/* some simple styling */
div#refreshable { 
  margin-top: 10px;
  width: 50%;
  margin: auto;
  border: 1px solid #ccc;
  padding: 5px;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="refresh">Refresh</button>
<div id="refreshable"></div>

CodePudding user response:

Kindly try this native method. No extra library need.

function currentTime() {
  var now = new Date();
  var hours = now.getHours() < 12 ? '0'   now.getHours() : now.getHours();
  var minutes = now.getMinutes() < 12 ? '0'   now.getMinutes() : now.getMinutes();
  var seconds = now.getSeconds() < 12 ? '0'   now.getSeconds() : now.getSeconds();
  var ampm = parseInt(hours) < 12 ? 'am' : 'pm';

  return hours   ":"   minutes   ":"   seconds   ampm;
}

document.querySelector('#test').innerText = currentTime();
document.querySelector('#refresh').addEventListener('click', () => {
  document.querySelector('#test').innerText = currentTime();
});
<button id="refresh">click me</button>
<p>The time is <span id="test"><?= date("h:i:sa"); ?></span></p>

  •  Tags:  
  • Related