Uros Tadic Uros Tadic - 5 months ago 11
CSS Question

Check my codepen. Triggering html button on enter click

So check my codepen on http://codepen.io/urketadic/pen/JKbddV
I need button to play its animation even if i dont click it but press enter.
what do i need to do?

$(document).ready(function() {
var secondsPerMin = 60;
var minsPerHour = 60;
var hoursPerDay = 24;
var daysPerWeek = 7;
var weeksPerYear = 52;
var yearsAlive;
var secondsPerDay = secondsPerMin * minsPerHour * hoursPerDay;

function calculateSeconds(yearsAlive) {
$("#output").val("For "+ yearsAlive + " years you have lived " + secondsPerDay * daysPerWeek * weeksPerYear * yearsAlive + " seconds.");
}

$("#inpute").on("keydown", function(e) {
if (e.keyCode == 13) {
e.preventDefault();
var yearsAlive = $('#inpute').val();
if (isNaN(yearsAlive)) {
$("#output").html("Your age must be a number.");
}
else {
calculateSeconds(yearsAlive);
}
}
});

$("#buttoninput").on('click', function() {
var yearsAlive = $('#inpute').val();
if (isNaN(yearsAlive)) {
$("#output").html("Your age must be a number.");
}
else{
calculateSeconds(yearsAlive);
}
});
});

Answer

Please have a look at below approach:

$(document).ready(function() {
  var secondsPerMin = 60;
  var minsPerHour = 60;
  var hoursPerDay = 24;
  var daysPerWeek = 7;
  var weeksPerYear = 52;
  var yearsAlive;
  var secondsPerDay = secondsPerMin * minsPerHour * hoursPerDay;

  function calculateSeconds(yearsAlive) {
    $("#output").val("For " + yearsAlive + " years you have lived " + secondsPerDay * daysPerWeek * weeksPerYear * yearsAlive + " seconds.");
  }

  $("#buttoninput").on('click', function() {
    var yearsAlive = $('#inpute').val();
    if (isNaN(yearsAlive)) {
      $("#output").html("Your age must be a number.");
    } else {
      calculateSeconds(yearsAlive);
    }
  });

  $("#inpute").on("keydown", function(e) {
    if (e.keyCode == 13) {
      e.preventDefault();
      $("#buttoninput").click();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div class="container">
  <div class="jumbotron">
    <div class="page-header">
      <h1 class="text-center animated bounceInDown">How old are you? <small>IN SECONDS.</small></h1>
    </div>


    <div class="input">
      <input type="text" id="inpute" class="col-xs-12 col-sm-6 col-md-8 animated bounceInLeft" placeholder="write age">
      <button type="submit" id="buttoninput" class="col-sm-4 btn btn-default btn-danger animated bounceInRight">Calculate</button>
    </div>

    <div class="output">
      <output id="output" placeholder="output" class="col-xs-12">
    </div>

  </div>