Here is the code snippet I've been working on. It should be self-explanatory.
$('body:not(#name)').click(function () {
if (document.getElementById('name').value === '') {
document.getElementById('name').value = 'Anonymous';
}
});
I seem to have overlooked something with the negation operator. What mistake did I make?
UPDATE: Despite trying out all the suggested solutions, I am still facing issues. Could it be because the element #name
is an input text field? Below is the code snippet along with my latest attempt using .not()
:
<form action="process-comment.php" method="POST"> <br/>
Name: <input type"text" id="name" name="name" value="Anonymous"> <br/>
E-mail: <input type"text" id="email" name="email" value="Secret"> <br/>
Comment: <input type"textarea" id="comment" name="comment"> <br/>
<input id="submitbutton" type="submit" value="Send">
</form>
<script>
$(document).ready(function () {
$('#name').click(function () {
if (document.getElementById('name').value === 'Anonymous') {
document.getElementById('name').value = '';
}
});
$('#email').click(function () {
if (document.getElementById('email').value === 'Secret') {
document.getElementById('email').value = '';
}
});
$('body').not('#name').click(function () {
if (document.getElementById('name').value === '') {
document.getElementById('name').value = 'Anonymous';
}
});
$('body').not('#email').click(function () {
if (document.getElementById('email').value === '') {
document.getElementById('email').value = 'Secret';
}
});
The objective is to initially display "Anonymous" and "Secret" in the text fields until they are clicked. Upon clicking away from the fields with empty values, indicating no user input, I want the values to revert back to "Anonymous" and "Secret". Currently, the fields get emptied but immediately refilled upon click.