How get the input field values using template literal in js

function loving(){

  'use strict';

let firstName=document.getElementById(‘firstName’).value;

let secondName=document.getElementById(‘secondName’).value;
let rand = Math.random() * 99;

  let lovepercentage= Math.floor(rand);

 document.getElementById('love').innerHTML=lovepercentage+'%';

 document.getElementById('loveMessage').innerHTML=` love percentage between ${firstName} and ${secondName}`; 

}

loving();

If I understand correctly, you want to get the value of an input field.
You can access that with the value key. The code below listens for a key press, and then console.logs the value of the input field.

var input = document.getElementById('<id here>')
input.addEventListener('keyup', () => {
  console.log(input.value)
})

i want to use the input values in string and print it

Sorry, I think I misunderstood you. Your template literals look correct, and the value key is a string already.
Is there something that isn’t working for you?

i have a button to calculate the love percentage between 2 inputs , on click , i can’t get the values of the 2 inputs
this is the string i get : love percentage between and

When you call loving(), is there any text in either of the inputs?

no there not no text

If there is no text in the inputs, then their value keys will just be an empty string. Make sure loving is called only after you have typed some text in the input fields.

1 Like