I have an issue with my script. I have an editable field and button next to it. I tried to make a function that will start working after I will press the button and it will read data from my input field, hover it doesn't read any value from my input field and returns that the input is empty. Could you please suggest any possible solutions to it? I cannot change any input or button types to other ones. Full code: https://codesandbox.io/s/cocky-black-7mezc?file=/code.html
const trigger =
document.getElementById("poga1");
trigger.addEventListener("click", next);
function next() {
document.getElementById("input")
// default to no data
let message = "there are no data!";
const output = document.getElementById("output");
// get the value, this will be text - trim all leading and trailing spaces
const value = this.value.trim();
if (value !== "") {
// try to convert it to an integer
const numeric = parseInt(value);
// check if it's a number and if it matches what was entered
if (isNaN(numeric) || numeric != value) {
message = "not a number";
} else
if (numeric >= 1 && numeric <= 3) {
message = "not passed";
} else if (numeric >= 4 && numeric <= 10) {
message = "passed!";
} else {
message = "wrong data";
}
}
output.textContent = message;
};
<span contenteditable="true"><p id="input"></p></span>
<button id="poga1">Check!</button>
<span contenteditable="true"><p id="output">Vispirms ievadi datus!</p></span>
CodePudding user response:
If you are trying to read the content of the element with an id input
, then you have to change the line
const value = this.value.trim();
to
const value = input.innerText.trim();
CodePudding user response:
The problem is you are reading this.value
. this
refers to the button so you are reading the button's value.
HTML
<div contenteditable="true" id="input"></div>
<button id="poga1">Check!</button>
<span><p id="output">Vispirms ievadi datus!</p></span>
Script
const trigger = document.getElementById("poga1"),
input = document.getElementById("input"),
output = document.getElementById("output");
trigger.addEventListener("click", next);
function next() {
document.getElementById("input")
// default to no data
let message = "There are no data!";
// get the value, this will be text - trim all leading and trailing spaces
const value = input.value.trim();
if (value !== "") {
// try to convert it to an integer
const numeric = parseInt(value);
// check if it's a number and if it matches what was entered
if (isNaN(numeric) || numeric != value) {
message = "not a number";
} else
if (numeric >= 1 && numeric <= 3) {
message = "not passed";
} else if (numeric >= 4 && numeric <= 10) {
message = "passed!";
} else {
message = "wrong data";
}
}
output.textContent = message;
};