The script below doesn't work and I need some help to find the reason. Because the function works as expected if I use it directly with the variable "input1" instead of "field", I think line 2 is the problem. I think using updateValue(input1) doesn't work, but I don't get any error report in the browser console.
Coloring a text input red or green, if the inserted code is found or not by API call
const input1 = document.getElementById("voucher1");
input1.addEventListener("change", updateValue(input1));
function updateValue(field) {
var InputOrgColor = field.style.backgroundColor;
const apiUrl = 'https://hook.eu1.make.com/wr3p7mnuqokj9...wns2n?voucher-id=' + field.value;
if (field.value === ``) {
field.style.backgroundColor = InputOrgColor;
document.getElementById("submit").style.visibility = `visible`;
} else
fetch(apiUrl)
.then(response => {
if (response.status === 200) {
field.style.backgroundColor = `#99ffcc`;
document.getElementById("submit").style.visibility = `visible`;
} else if (response.status === 201) {
field.style.backgroundColor = `#ffcccb`;
document.getElementById("submit").style.visibility = `hidden`;
alert("Der Gutscheincode wurde nicht gefunden. Bitte überprüfe Deine Eingabe.");
} else if (response.status === 202) {
field.style.backgroundColor = `#ffcccb`;
document.getElementById("submit").style.visibility = `hidden`;
alert("Der Gutscheincode wurde zwar gefunden, aber der Gutschein ist entweder unbezahlt oder bereits abgesprungen.");
}
})
};
() => updateValue(input1)submitif you ever plan to submit a form programmatically. Lastly don't use empty template literal backticks to validate empty strings. Change toif (field.value === '') {