Page 1 of 1
JavaScript not work in Page_Head
Posted: Sun Jan 28, 2024 2:30 am
by ASHKAR
i have js code when user write ccc it turns to www
i have tested it and work fine in separate html file
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-time Text Replacement</title>
</head>
<body>
<label for="textInput">input:</label>
<input type="text" id="textInput">
<script>
// Select all input fields
const inputFields = document.querySelectorAll("input");
// Attach the event listener to each input field
inputFields.forEach(inputField => {
inputField.addEventListener("input", () => {
const currentText = inputField.value;
const updatedText = currentText.replace(/ccc/g, "www");
inputField.value = updatedText;
});
});
</script>
</body>
</html>
but when i write JS in Server Events > Global > All Pages > Page_Head
it not working
echo '
<script>
// Select all input fields
const inputFields = document.querySelectorAll("input");
// Attach the event listener to each input field
inputFields.forEach(inputField => {
inputField.addEventListener("input", () => {
const currentText = inputField.value;
const updatedText = currentText.replace(/ccc/g, "www");
inputField.value = updatedText;
});
});
</script>
';
any suggestion ?
Re: Why my JavaScript not work?
Posted: Sun Jan 28, 2024 9:32 am
by arbei
Note that Page_Head is outputed in the <head>
section, the HTML elements are not outputted yet. You should put your code under Startup Script.
Re: JavaScript not work in Page_Head
Posted: Mon Jan 29, 2024 2:34 am
by ASHKAR
Thanks
it works fine by go to
client scripts > global > pages with header/footer > startup script
then i add this code for replace old words with new words >> this work for all html input fields and all modal input fields
put this code without <script></script>
the code:
function replaceWords(inputText) {
var oldWords = ["old1","old2","old3"];
var newWords = ["new1","new2","new3"];
for (var i = 0; i < oldWords.length; i++) {
var regex = new RegExp(oldWords[i], "gi");
inputText = inputText.replace(regex, newWords[i]);
}
return inputText;
}
// Event listener for input changes
function handleInputChange(event) {
var inputValue = event.target.value;
var replacedValue = replaceWords(inputValue);
// Update the input value with the replaced text
event.target.value = replacedValue;
}
// Apply the event listener to all input elements
var inputElements = document.querySelectorAll('input');
inputElements.forEach(function (input) {
input.addEventListener("input", handleInputChange);
});
// Apply the event listener to all modal inputs when the modal is shown
$('.modal').on('shown.bs.modal', function () {
var modalInputElements = this.querySelectorAll('input');
modalInputElements.forEach(function (input) {
input.addEventListener("input", handleInputChange);
});
});