Home > other >  How to add timestamp conditionally for a checkbox value in jQuery?
How to add timestamp conditionally for a checkbox value in jQuery?

Time:12-30

I am trying to add a timestamp in the checkbox input field as a value. But its always shows the same value.

How to add a different value ( Blank ) while unchecking?

Here is he HTML Code,

<div >                    
<input type="checkbox" id="newsletter" name="join-my-newsletter"  value="Yes">
<label  for="newsletter">Join my newsletter</label>
</div>

I used the javascript

$(function() { // when page loads
  var timeNow = new Date().getTime();
$(".newsletter-check input[type='checkbox']").on("click",function() {
if (this.checked) $("#newsletter").attr('value',    timeNow );
});
});

CodePudding user response:

You can try this code:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".newsletter-check input[type='checkbox']").on("click",function() {
    var timeNow = new Date().getTime();
    if ($(this).prop('checked')==true){
     $("#newsletter").attr('value', timeNow );
     alert(timeNow);
    }else{
     $("#newsletter").attr('value', '');
    } 
  });
});
</script>
</head>
<body>

<div >                    
<input type="checkbox" id="newsletter" name="join-my-newsletter"  value="Yes">
<label  for="newsletter">Join my newsletter</label>
</div>

</body>
</html>

CodePudding user response:

Timestamp gets set on page load so it does not update.
You can move the timestamp declaration inside the click event so it gets updated whenever you trigger the checkbox.

$(function() { // when page loads
$(".newsletter-check input[type='checkbox']").on("click",function() {
  var timeNow = new Date().getTime();
  console.log(timeNow);

  if (this.checked) $("#newsletter").attr('value',    timeNow );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div >                    
<input type="checkbox" id="newsletter" name="join-my-newsletter"  value="Yes">
<label  for="newsletter">Join my newsletter</label>
</div>

  • Related