can someone help me? I have a simple textarea.I want to check this area for text, when you push button and if your textarea is empty it fills it with default email.
<form>
<textarea id="smth"></textarea>
<button id="btn">Sumbit</button>
</form>
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.textContent != null) {
x.textContent = '[email protected]';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});
But something went wrong...as a usuall and it works realy bad. It just calls once.
CodePudding user response:
textContent is not the proper way of getting values from textarea. And also, a blank textarea's value is ""
, not null
.
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.textContent != null) {
x.textContent = '[email protected]';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});
<form>
<textarea id="smth"></textarea>
<button id="btn">Sumbit</button>
</form>
Instead, try .value:
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.value == '') {
x.value = '[email protected]';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});
<form>
<label>Text: <textarea id="smth"></textarea></label>
<button id="btn">Sumbit</button>
</form>
CodePudding user response:
Textarea has a value. You should check if value empty or not.
const btn = document.getElementById('btn');
let x = document.getElementById('smth');
function putDefaultMail() {
if (x.value == "") { // if empty
x.value = '[email protected]';
}
}
btn.addEventListener('click', function (e) {
e.preventDefault();
putDefaultMail();
});