I am adding a list item to my ul from an input textarea. How do I change it's color based on if it's a palindrome or not? Below is the js file of my code.
function isPalindrome(text){
return text == text.split('').reverse().join('');
}
const staticForm = document.getElementById('static-form');
let myUl = document.getElementById('list');
const textarea = document.getElementById('text');
staticForm.addEventListener('submit', (event) => {
event.preventDefault();
if (isPalindrome(text)==true) textarea.style.color='red';
else textarea.style.color='blue';
let li = document.createElement('li');
li.innerHTML = textarea.value;
myUl.appendChild(li);
myForm.reset();
textarea.focus();
const result = isPalindrome(textarea)
});
HTML:
<main>
<form id='static-form' method="POST" class="new-post-form">
<textarea id='text' name='phrase'>
Attempt here
</textarea>
<input class="sub-button" type="submit" name="submit" value="Submit" />
</form>
<ul id='list'></ul>
</main>
I know that writing textarea.style.color does not work, what is the best way to achieve this?
function isPalindrome(text) {
return text === text.split("").reverse().join("");
}
const staticForm = document.getElementById("static-form");
let myUl = document.getElementById("list");
const textarea = document.getElementById("text");
const submitBtn = document.getElementById("submit");
submitBtn.addEventListener("click", (event) => {
const text = document.getElementById("text").value;
textarea.style.color = isPalindrome(text) ? "red" : "blue";
let li = document.createElement("li");
li.innerHTML = textarea.value;
myUl.appendChild(li);
textarea.focus();
const result = isPalindrome(textarea);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
</head>
<body>
<main>
<form id="static-form" method="POST" class="new-post-form">
<textarea id="text" name="phrase">sample text</textarea
>
<input
class="sub-button"
id="submit"
type="button"
name="submit"
value="Submit"
/>
</form>
<ul id="list"></ul>
</main>
</body>
</html>
function changeTextareaColor(){
const textarea = document.getElementById("textarea");
if (textarea) {
textarea.style.color = "red";
}
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
</head>
<body>
<textarea id="textarea">
This is a static template, there is no bundler or bundling involved!
</textarea>
<button onclick="changeTextareaColor()">change color</button>
<script>
</script>
</body>
</html>
I modify your code a little bit. I hope It will work.