Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi, from this page (saved, the original is protected) I run this script with a Chrome extension, which extracts, in "Nome" field, the publisher from the bibliographic description above (Feltrinelli, in the example ). In various cases I need to cancel the self-extracted value. Is there a way to clear this initial value at the first click on any area of the page (except clicking on "Ricerca" button), but then whatever I typed remains until the form is submitted? Thanks very much!

What I have tried:

HTML
<input type="text" onfocus="this.value=''" value="Blabla">
Posted
Updated 2-May-23 2:43am
v6

1 solution

The first thing is you define a global variable that checks whether the click has occured
let isFirstClick = true

Then you create handler, that checks if no clicks have occured then find input by id and clear it's value.
const modifyText = () => {
	if (isFirstClick) {
		const ds = document.getElementById("ds")
		ds.value = ""
		isFirstClick = false
	}	
}

Then attach click to the document
document.addEventListener("click", modifyText)

When your script is exiting destroyed don't forget to remove the listener
document.removeEventListener("click", modifyText)
 
Share this answer
 
Comments
Parvares 25-Apr-23 14:51pm    
I tried to add this script at the bottom, but "Nome" field now remains empty...

let isFirstClick = true
const modifyText = () => {
	if (isFirstClick) {
		const ds = document.getElementById("ds")
		ds.value = ""
		isFirstClick = false
document.removeEventListener("click", modifyText)
	}	
}
document.addEventListener("click", modifyText)
Richard Deeming 2-May-23 8:33am    
Rather than using a global flag, surely it would be better to use the once parameter of the addEventListener options?
EventTarget: addEventListener() method - Web APIs | MDN[^]

"once: A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked. If not specified, defaults to false."
Parvares 2-May-23 8:41am    
Thanks, Richard Deeming, I solved changing click event with selectionchange.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900