Home > Blockchain >  Add JS function to inner html field?
Add JS function to inner html field?

Time:12-23

Beginner JavaScript Practice. I am creating a simple page where the user can input a number of minutes and it will return the hours and minutes. Ex: 500 minutes = 8hrs 20mins

I have an input field for the user to input a number of minutes (works perfectly fine on it’s own)

I have a function that takes the total number of minutes and returns the equivalent hours:minutes (works perfectly fine on it’s own as well)

The issue I’m having is connecting these two sections of code to work together. So that the user may input a number and minutes, then run the function, and return the hours and minutes equivalent the the number of minutes they gave.

Any help would ge greatly appreciated! As I mentioned, I am very new to JavaScript (:

let form = document.getElementById("form")

form.addEventListener('submit', function(event) {
  event.preventDefault() // prevents form from auto-submitting

  let userMinutes = document.getElementById("minutes").value
  // .value = extract the value the user has inputted 
  // console.log(userMinutes)
});

// JavaScript function to convert minutes —> hours and minutes
function timeConvert(n) {
  let num = n;

  let hours = num / 60;
  let rhours = Math.floor(hours);

  let minutes = (hours - rhours) * 60;
  let rminutes = Math.round(minutes);

  return num   " minutes ="   rhours   " hour(s) and "   rminutes   " minute(s)."

  console.log(timeConvert(n));
};
<form id="form">
  <input type="text" id="minutes" name="minutes" placeholder="minutes" required>
  <input type="submit" value="submit">
</form>

CodePudding user response:

First, there's no need for a form here since you won't be submitting any form data anywhere. And, because there's no need for a form, you won't use the submit event or preventDefault() either. Instead, you just need a regular button to trigger the operation.

See additional comments inline below:

// Get your element references once rather that every time the function runs
// And, when you do get your references, just get a reference
// to the element, not any property of the element
// so that in case you need to access the element at some
// future point in time, you don't have to query the document
// for the same element again.
let userMinues = document.getElementById("minutes");
let result = document.querySelector("#result");

// No need for a separate function to do the work.
// Just do it in the click handler
document.querySelector("input[type='button'").addEventListener('click', function(event) {
  let num = userMinues.value;

  let hours = num / 60;
  let rhours = Math.floor(hours);

  let minutes = (hours - rhours) * 60;
  let rminutes = Math.round(minutes);

  // Event handlers shouldn't return anything because
  // you have no place to return the value to. Instead
  // populate an empty element that serves as a placeholder
  // for the answer. Also, don't use .innerHTML when you 
  // can avoid it because it has performance and security
  // implications.
  result.textContent = num   " minutes ="   rhours   " hour(s) and "   rminutes   " minute(s)."
});
<input type="text" id="minutes" name="minutes" placeholder="minutes" required>
<input type="button" value="Go!">
<div id="result"></div>

CodePudding user response:

Best practice is to separate your calculation/logic things from the rest. Try to get a section of code to do ONE thing.

I left your form as a form but it might also just be some elements with click handlers etc.

Here I converted your function to return an object, called that then used that object that was returned to show the values.

The whole display part might also be placed in another function but I left that to you to do that as a learning exercise here.

let form = document.getElementById("form");
form.addEventListener('submit', function(event) {
  event.preventDefault(); // prevents form from auto-submitting
  let userMinutes = document.getElementById("minutes").value;
  // just get an object with the values from a function then use them:
  let timeThings = timeConvert(userMinutes);
  /* can do this one of two ways: string or a template literal */
  //  const showMe = timeThings.entered   " minutes = "   timeThings.hours   " hour(s) and "   timeThings.minutes   " minute(s).";
  /* using a template literal:  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals */
  const showMe = `${timeThings.entered} minutes = ${timeThings.hours} hour(s) and ${timeThings.minutes} minute(s).`;
  console.log(showMe);
});

function timeConvert(minutesEntered) {
  let hours = minutesEntered / 60;
  let rhours = Math.floor(hours);
  let minutes = (hours - rhours) * 60;
  let rminutes = Math.round(minutes);
  return {
    entered: minutesEntered,
    minutes: rminutes,
    hours: rhours
  };
}
<form id="form">
  <input type="number" id="minutes" name="minutes" placeholder="minutes" required>
  <input type="submit" value="submit">
</form>

CodePudding user response:

You are not calling timeConvert() from your event handler. Also, you were trying to console.log after returning from timeConvert() which means that even if you called it, it wouldn't log anything.

let form = document.getElementById("form")

form.addEventListener('submit', function(event) {
  event.preventDefault() // prevents form from auto-submitting

  let userMinutes = document.getElementById("minutes").value
  // THE FIX
  console.log(timeConvert(userMinutes));
});

function timeConvert(n) {
  let num = n;

  let hours = num / 60;
  let rhours = Math.floor(hours);

  let minutes = (hours - rhours) * 60;
  let rminutes = Math.round(minutes);

  return num   " minutes ="   rhours   " hour(s) and "   rminutes   " minute(s)."
  };
<form id="form">
  <input type="text" id="minutes" name="minutes" placeholder="minutes" required>
  <input type="submit" value="submit">
</form>

CodePudding user response:

Simply use your function as an event handler which is a function that is invoked when a registered event is triggered. You can use the HTMLFormElement interface for terse syntax and solid control over all form controls within the <form>.

Details are commented in example

// Reference <form>
const form = document.forms.form;
/**
 * Bind <form> to "submit" event 
 * When "submit" event is triggered, 
 * invoke event handler convertTime(event)
 */
form.addEventListener('submit', convertTime);

/**
 * Event handler passes event object by default
 * Stop default "submit" behavior of <form>
 *
 * Reference all <input> and <output> within <form>
 * Reference <input>
 * Reference <output>
 * 
 * Convert the value of <input> from String to Number
 * (Next 4 lines are calculations)
 * 
 * Assign the value of <output> as a template literal with the 
 * calculated values interpolated within.
 */
function convertTime(event) {
  event.preventDefault();

  const io = this.elements;
  const dataMin = io.minutes;
  const dataRes = io.result;

  let min = parseInt(dataMin.value);
  let hrs = min / 60;
  let rhrs = Math.floor(hrs);
  let mins = (hrs - rhrs) * 60;
  let rmins = Math.round(mins);

  dataRes.value = `${min} minutes = ${rhrs} hour(s) and ${rmins} minute(s).`
};
:root {
  font: 300 2ch/1.15 "Segoe UI"
}

input,
output {
  display: block;
  min-height: 1.15rem;
  margin: 0.5rem 0;
  font: inherit;
}
<form id="form">
  <!-- Use [type="number"] instead of [type="text"] -->
  <input id="minutes" name="data" type="number" placeholder="Minutes..." required>
  <!-- Use an output element to display results -->
  <output id="result" name="data"></output>
  <input type="submit">
</form>

CodePudding user response:

There you go

<input id="minutes" type="number">
<button onclick="calc()">calc</button>
<div id="result"></div>

<script>
    function timeConvert(n) {
        let num = n;
        
        let hours = num / 60;
        let rhours = Math.floor(hours);
        
        let minutes = (hours - rhours) * 60;
        let rminutes = Math.round(minutes);
        
        
        return num   " minutes ="   rhours   " hour(s) and "   rminutes   " minute(s)."
    }
    
    function calc() {
      const result = timeConvert(parseInt(document.querySelector('#minutes').value))
      
      document.querySelector('#result').innerHTML = result
    }
</script>
  • Related