skip to Main Content

I’m making a small application which shows how strings are manipulated in javascript by using different methods ,I’m trying to get number as a input and pass that number as parameter to slice the string but it is not working because i am unable to get number from user . i tried to print the number in the console but it is showing an empty line

here is my that might help you understand where i’m making a mistake
HTML Code

<input type="number" placeholder="number" class="number1">
<input type="number" placeholder="number" class="number2">
<button class="sliced">slice</button>
<h1 id="displaytext"></h1>

Javascript code

let message = document.querySelector("#displaytext")
let slicedButton = document.querySelector(".sliced")
let number1 = document.querySelector(".number1").value 
let number2 =document.querySelector(".number2").value
slicedButton.addEventListener("click", ()=>{
    console.log(number1,number2)
    message.innerHTML = userInput.value.slice(number1, number2)
})

2

Answers


  1. Try getting the values inside the call back function.

    let message = document.querySelector("#displaytext")
    let slicedButton = document.querySelector(".sliced")
    
    slicedButton.addEventListener("click", ()=>{
    let number1 = document.querySelector(".number1").value 
    let number2 =document.querySelector(".number2").value
        console.log(number1,number2)
        //message.innerHTML = userInput.value.slice(number1, number2)
    })
    
    Login or Signup to reply.
  2. Your Javascript code executes as soon as your page loads, which is why number1 and number2 get assigned "" immediately. Move the logic that gets the input value into the listener, to receive the latest value:

    let message = document.querySelector("#displaytext")
    let slicedButton = document.querySelector(".sliced")
    slicedButton.addEventListener("click", ()=>{
    let number1 = document.querySelector(".number1").value 
    let number2 =document.querySelector(".number2").value
        console.log(number1,number2)
        message.innerHTML = userInput.value.slice(number1, number2)
    })
    

    However this still throws as uerInput is undefined

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search