What if I want to check if the field is empty?
If the field is empty I want to send/append a static message like "Hello guys" which is e.target.value
.
If I do a check (if the e.target.value == null
), nothing happens.
<form id="user_form" action="" method="post" enctype="text/plain">
<textarea id="msg" cols="30" rows="10" placeholder="Write a message"></textarea>
<input type="submit" onsubmit="return test()" id="sendBtn" value="send" >
</form>
<!-- Send msg to whatsapp -->
<script>
const url = 'https://api.whatsapp.com/send?phone=123456789&text=';
document.getElementById('msg').addEventListener('keyup', (e) => {
document.getElementById('user_form').setAttribute('action', url e.target.value);
console.log(document.getElementById('user_form').getAttribute('action'));
});
</script>
What I want to do is:
if (e.target.value == "") {
e.target.value = "This is a default message"
}
CodePudding user response:
Check if the textarea
is empty with document.querySelector('#msg').value.length
. If the length === 0
then it means that the textarea
has no text. You can use a ternary conditional operator for that.
You also should implement a trim()
inside your condition to check if the text only contains spaces.
document.querySelector('button').addEventListener('click', function() {
let msg = document.querySelector('#msg');
let text = (msg.value.trim().length != 0) ? msg.value : 'no text';
console.log(text);
})
<textarea id="msg" cols="30" rows="10" placeholder="Write a message"></textarea>
<button>Get content of textarea</button>
CodePudding user response:
try e.target.value === ""