I took the script from the Bootstrap 5 documentation and incorporated it into my script.
The validation itself works. However, I don’t understand how I can start a function named webShare() in the script if the validation was successful.
function onLoad() {
const forms = document.querySelectorAll('.needs-validation')
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
if (navigator.share === undefined) {
setShareButtonsEnabled(false);
if (window.location.protocol === 'http:') {
// navigator.share() is only available in secure contexts.
window.location.replace(window.location.href.replace(/^http:/, 'https:'));
} else {
logError('Error: You need to use a browser that supports this draft ' +
'proposal.');
}
}
}
window.addEventListener('load', onLoad);
The page should not be reloaded. Only the function "webShare()" must be executed.
Does anyone have a tip for me or a solution?
>Solution :
To execute the webShare() function after successful form validation, you can add a call to webShare() at the end of the if statement that checks the form’s validity. Here is an example of how you can do this:
function onLoad() {
const forms = document.querySelectorAll('.needs-validation')
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
} else {
// Call webShare() if the form is valid
webShare();
}
form.classList.add('was-validated')
}, false)
})
if (navigator.share === undefined) {
setShareButtonsEnabled(false);
if (window.location.protocol === 'http:') {
// navigator.share() is only available in secure contexts.
window.location.replace(window.location.href.replace(/^http:/, 'https:'));
} else {
logError('Error: You need to use a browser that supports this draft ' +
'proposal.');
}
}
}
window.addEventListener('load', onLoad);
Note that you need to define the webShare() function before calling it, otherwise you will get an error.