html
<form>
<label>Enter Text: </label>
<textarea placeholder="Enter text here for detection." id="name" name="name" autofocus class="result" >
</textarea>
</form>
<div class="options" style="display:none">
<div class="anguage" >
<p>Language</p>
<select name="input-language" id="language"></select>
</div>
</div>
<button class="btn record" id='myid'>
<p><b> Start Listening</b></p>
</button>
<div style="margin-top:-50px;" class="buttons">
<button class="btn clear" id='clr' style="margin-left:150px" onClick="eraseText()">
<b>Clear</b>
</button>
</div>
Btn clear function
<script>
function eraseText(){
document.getElementById('name').value='';
}
</script>
Voice to Text conversion code
<script>
const languages = [
{
no: "16",
name: "English",
native: "English",
code: "en",
}
];
const recordBtn = document.querySelector(".record"),
result = document.querySelector("result"),
inputLanguage = document.querySelector("#language")
clearBtn = document.querySelector(".clear");
let SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition,
recognition,
recording = false;
function populateLanguages() {
languages.forEach((lang) => {
const option = document.createElement("option");
option.value = lang.code;
option.innerHTML = lang.name;
inputLanguage.appendChild(option);});
}
populateLanguages();
function speechToText() {
try {
recognition = new SpeechRecognition();
recognition.lang = inputLanguage.value;
recognition.interimResults = true;
recordBtn.classList.add("recording");
recordBtn.querySelector("p").innerHTML = "<p style='margin-top:8px'>Stop Listening...</p>";
recognition.start();
recognition.onresult = (event) => {
const speechResult = event.results[0][0].transcript;
//detect when intrim results
if (event.results[0].isFinal) {
result.innerHTML = " " + speechResult;
result.querySelector("p").remove();
}
else {
//creative p with class interim if not already there
if (!document.querySelector(".interim")) {
const interim = document.querySelector('textarea')
interim.classList.add("interim");
result.appendChild(interim);
}
//update the interim p with the speech result
document.querySelector("textarea").innerHTML =" " + speechResult;
}
};
recognition.onspeechend = () => {
speechToText();
};
recognition.onerror = (event) => {
stopRecording();
if (event.error === "no-speech") {
alert("No speech was detected. Stopping...");
} else if (event.error === "audio-capture") {
alert(
"No microphone was found. Ensure that a microphone is installed."
);
} else if (event.error === "not-allowed") {
alert("Permission to use microphone is blocked.");
} else if (event.error === "aborted") {
alert("Listening Stopped.");
} else {
alert("Error occurred in recognition: " + event.error);
}
};
}
catch (error)
{recording = false;
console.log(error);
}
}
recordBtn.addEventListener("click", () => {
if (!recording) {
speechToText();
recording = true;
}
else {
stopRecording();
}
});
function stopRecording() {
recognition.stop();
recordBtn.querySelector("p").innerHTML = "<b> Start Listening</b>";
recordBtn.classList.remove("recording");
recording = false;
}
</script>
I am converting voice to text in a textarea. When I load a page than the start listening button works perfectly, but when I press clear button than using the start listening button, it works but the data that I speak is not written to the textbox. For checking issue, I used alert statement for printing new data that is spoken in the alert box. The new data spoken is found and printed in the alert box.
I am confused why the new spoken data is not printing in the textarea box after using clear button when listening button working perfectly. Is there any way to get rid of this problem? I mean to say to solve this issue.
You declare this: const result = document.querySelector("result")
So the result, is the textarea element. Later do this:
function speechToText() {
...
if (!document.querySelector(".interim")) {
//const interim referd to the same element with const result
const interim = document.querySelector('textarea')
interim.classList.add("interim")
//and you add it as a child to itself.....???
result.appendChild(interim)
}
...
}
Related
I want to stop the form from submitting when the username is below 3 characters. I tried using return false but it didn't work.
Below is the code (didn't used return false in this one)
I am a beginner so please give an easy explanation 😅
const messageElement = formElement.querySelector(".form__message");
messageElement.textContent = message;
messageElement.classList.remove("form__message--success", "form__message--error");
messageElement.classList.add(`form__message--${type}`);
}
function setInputError(inputElement, message) {
inputElement.classList.add("form__input--error");
inputElement.parentElement.querySelector(".form__input-error-message").textContent = message;
};
function clearInputError(inputElement) {
inputElement.classList.remove("form__input--error");
inputElement.parentElement.querySelector(".form__input-error-message").textContent = "";
};
document.addEventListener('DOMContentLoaded', () => {
const loginForm = document.querySelector("#login");
const createAccountForm = document.querySelector("#createAccount");
document.querySelector("#linkCreateAccount").addEventListener("click", e => {
e.preventDefault();
loginForm.classList.add("form--hidden");
createAccountForm.classList.remove("form--hidden");
});
document.querySelector("#linkLogin").addEventListener("click", e => {
e.preventDefault();
loginForm.classList.remove("form--hidden");
createAccountForm.classList.add("form--hidden");
});
loginForm.addEventListener("submit", e => {
e.preventDefault();
setFormMessage(loginForm, "error", "Invalid Username/Password Combination");
});
document.querySelectorAll(".form__input").forEach(inputElement => {
inputElement.addEventListener("blur", e => {
if(e.target.id === "signupUsername" && e.target.value.length < 3 ) {
setInputError(inputElement, "Username must be atleast 3 letters in length");
}
});
inputElement.addEventListener("input", e => {
clearInputError(inputElement);
});
});
});```
For me this always works:
function check_form(form) {
var ok = confirm("is it ok?");
return ok
}
<form onsubmit="return check_form(this)">
<input>
<input type="submit">
</form>
Bonus: if you want to asynchronously check the form and only then submit, it goes like this:
function check_form(form) {
setTimeout(function() {
var ok = confirm("is it ok?")
if (ok) {
form.submit()
}
}, 100);
}
<form onsubmit="check_form(this); return false;">
<input>
<input type="submit">
</form>
I've created an HTML form with JS validation. I've called the function through a button via onclick but it is firing multiple times resulting in unnecessary blank form data. Here's the code.
I'm pushing the data to firebase realtime db.
I'm new to JS, any help would be appreciated.
HTML
<form class="subscribe-form" id="subscribe-form">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<input class="email-input" name="email" id="email" type="text" placeholder="Email">
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<button onclick="updateSubscribeEmail();" class="sitebtn btn-submit"
type="submit">Subscribe</button></div>
</form>
JS
function updateSubscribeEmail() {
// Reference messages collection
var messagesRef = firebase.database().ref("Subscription Emails");
var resetForm = document.getElementById("subscribe-form");
// Listen for form submit
document.getElementById("subscribe-form").addEventListener("submit", submitSubscribeForm);
// Submit form
function submitSubscribeForm(e) {
// To avoid entire page getting refreshed
e.preventDefault();
var email = getInputVal("email");
// Get values
var text;
console.log("Before Validation");
if (email.indexOf("#") === -1 || email.length < 6) {
console.log("After Validation");
text = "Please enter a valid email address!";
red_inner_html.innerHTML = text;
red_div.style.display = "block";
setTimeout(function () {
red_div.style.display = "none";
}, 5000);
} else {
saveMessage(email);
console.log("Before reset");
resetForm.reset();
console.log("after reset");
text = "You have successfully subscribed!";
green_inner_html.innerHTML = text;
green_div.style.display = "block";
setTimeout(function () {
green_div.style.display = "none";
}, 5000);
}
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(email) {
var newMessageRef = messagesRef.push();
newMessageRef.set({
Email: email
});
}
}
I'm trying to have a case in a switch statement that jumps into a different switch statement.
In practice, I want the user to type "close page" in a text box and, before the browser closes the page, I want the user to be asked if he is sure about it. Typing "yes" will close the page, and typing "no" will go back to the previous switch statement.
I need to use a switch statement because there are many other things the user can type into the textbox, which generate different feedback.
I used a different textbox for each switch statement, swapping them when necessary, to try to be able to call both functions with the same key.
This is what I have. But it does not work...
Any help?
function SwapDivs(div1, div2) {
d1 = document.getElementById(div1);
d2 = document.getElementById(div2);
if (d2.style.display == "none") {
d1.style.display = "none";
d2.style.display = "block";
} else {
d1.style.display = "block";
d2.style.display = "none";
}
}
function myFunction01() {
var text;
var answers = document.getElementById("myInput01"").value;
switch (answers) {
case "close page":
text = "are you sure?";
SwapDivs('div01', 'div02');
break;
default:
text = "no valid input";
}
document.getElementById("feedback").innerHTML = text;
}
function myFunction02() {
var text;
var answers = document.getElementById("myInput02").value;
switch (answers) {
case "yes":
text = "Why?";
break;
case "no":
text = "Good!";
break;
default:
text = "no valid input";
}
document.getElementById("feedback").innerHTML = text;
}
<p id="feedback"></p>
<div id="div01" style="display:block">
<input id="myInput01" type="text" placeholder="This is TextBox 01." onKeyDown="if(event.keyCode==13) myFunction01();">
</div>
<div id="div02" style="display:none">
<input id="myInput02" type="text" placeholder="This is TextBox 02." onKeyDown="if(event.keyCode==13) myFunction02();">
</div>
You have an extra quote on your first function:
var answers = document.getElementById("myInput01"").value;
It should be:
var answers = document.getElementById("myInput01").value;
I understand the behaviour is:
If user enters any text other than "close page", we give them feedback of invalid input.
If user enters "close page", we ask them if they are sure and change to input 2.
On input 2, if they input yes we say why, if they input no we say good else say no valid input.
If this is expected, the code works for me.
You can run this one below (converted to ES6):
const SwapDivs = (div1, div2) => {
const d1 = document.getElementById(div1);
const d2 = document.getElementById(div2);
if (d2.style.display == "none") {
d1.style.display = "none";
d2.style.display = "block";
} else {
d1.style.display = "block";
d2.style.display = "none";
}
};
const myFunction01 = () => {
let text;
const answers = document.getElementById("myInput01").value;
switch (answers) {
case "close page":
text = "are you sure?";
SwapDivs('div01', 'div02');
break;
default:
text = "no valid input";
}
document.getElementById("feedback").innerHTML = text;
};
const myFunction02 = () => {
let text;
const answers = document.getElementById("myInput02").value;
switch (answers) {
case "yes":
text = "Why?";
break;
case "no":
text = "Good!";
break;
default:
text = "no valid input";
}
document.getElementById("feedback").innerHTML = text;
};
<p id="feedback"></p>
<div id="div01" style="display:block">
<input id="myInput01" type="text" placeholder="This is TextBox 01." onKeyDown="if(event.keyCode==13) myFunction01();">
</div>
<div id="div02" style="display:none">
<input id="myInput02" type="text" placeholder="This is TextBox 02." onKeyDown="if(event.keyCode==13) myFunction02();">
</div>
The code checks barcodes using a barcode scanner.
Search_code is filled by a user (keyboard) , and insert_code is filled automatically by a barcode scanner.
Currently, code works if both inputs are introduced in barcode scanner values ​​which is not functional for me.
The code needs to run when:
search_code is entered manually ( keyboard ) and
insert_code is filled automatically by the barcode scanner
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate(e) {
e.preventDefault();
// show verification result:
if (search_code.value == insert_code.value) {
result.textContent = 'code ok';
result.className = "ok";
audio.play();
} else {
result.textContent = 'code is not ok';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
function clearField(input) {
input.value = "";
};
....
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value=""/><br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>
</div>
<div id="result"></div>
</div>
<script src="js/action_input.js"></script>
</body>
</html>
Thank you!
To prevent a textbox from being filled by a bar-code reader simply disable onpaste event .
$(document).ready(function(){
$('#search_code').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
I have added the following before end of head
<script src='https://www.google.com/recaptcha/api.js'></script>
I have added this before end of form
<div class="g-recaptcha" data-sitekey="== xxxxxx =="></div>
I can see the recaptcha similar to https://developers.google.com/recaptcha/
HOwever, when user presses data without checking the checkbox, the data is submitted. Is there any other code I need to add to check if user has pressed the checkbox? Hopefully in js?
Google has a call back option for when the checkbox is checked.
Add this to your form element:
data-callback="XXX"
Example:
<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="== xxxxxx =="></div>
And a disable attribute to your submit button.
Example:
<button id="submitBtn" disabled>Submit</button>
Then a create a callback function and write whatever code you need.
Example:
function recaptchaCallback() {
$('#submitBtn').removeAttr('disabled');
};
You can also call the grecaptcha object to check. grecaptcha.getResponse(); is empty when unchecked and has the verification code when checked.
grecaptcha.getResponse().length === 0 when unchecked
function isCaptchaChecked() {
return grecaptcha && grecaptcha.getResponse().length !== 0;
}
if (isCaptchaChecked()) {
// ...
}
To check if google recaptcha is checked or not you can do it by the following code :
<script>
if(grecaptcha && grecaptcha.getResponse().length > 0)
{
//the recaptcha is checked
// Do what you want here
alert('Well, recaptcha is checked !');
}
else
{
//The recaptcha is not cheched
//You can display an error message here
alert('Oops, you have to check the recaptcha !');
}
</script>
To check if google recaptcha v2 is checked or not you can do it by the following code :
var checkCaptch = false;
var verifyCallback = function(response) {
if (response == "") {
checkCaptch = false;
}
else {
checkCaptch = true;
}
};
$(document).ready(function() {
$("#btnSubmit").click(function() {
if (checkCaptch && grecaptcha.getResponse()!="") {
//Write your success code here
}
});
})
Let the browser do the job for you! (based on slinky2000 answer)
note: this is only to prevent sending an 'accidentally' unchecked recaptcha. You still have to verify the recaptcha on server side because a bot does not care ...
Add a an invisible input tag with required=true attribute just below the div.g-recaptcha.
<input id='recaptcha_check_empty' required tabindex='-1',
style='width:50px; height:0; opacity:0; pointer-events:none;
position:absolute;
bottom:0;'>
Enclose both width a div with position=relative; to point the bottom:0; above to the bottom of recaptcha.
Now the Browser asks nicely to fill out this field - pointing to the recapcha.
Now we need the callback:
<div class="g-recaptcha" data-callback="recaptchaCallback" ...
and
function recaptchaCallback() {
$('#recaptcha_check_empty').val(1);
}
<div class="contact-inner contact-message">
<label for="message-text" class="col-form-label">CAPTCHA</label>
<div class="g-recaptcha" data-sitekey="<?php echo 6LfSJmocAAAAAFFMpMKB1CtYNJYDyDswO7GpxRXS ;?>">
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<!DOCTYPE html>
<html>
<head>
<title>CAPTCHA</title>
</head>
<body>
<div class="contact-inner contact-message">
<label for="message-text" class="col-form-label">CAPTCHA</label>
<div class="g-recaptcha" data-sitekey="<?php echo GOOGLE_KEY ;?>"></div>
</div>
</body>
</html>
if for some reason you are conditioning a form by hand like me, and required is not working.
First import ReCAPTCHA
import ReCAPTCHA from 'react-google-recaptcha'
Apply it in your component
<ReCAPTCHA style={{margin: '5px', transform: 'scale(0.8)'}} ref={recaptchaRef} sitekey={recaptchaKey} onChange={updateRecaptcha}/>
you can use a useRef or just use the ReCAPTCHA you've imported, I used useRef.
const recaptchaRef = useRef<any>()
And now, how do I check if recaptchaRef is checked?
if (recaptchaRef.current.props.grecaptcha.getResponse().length !== 0) {
//your condition
}
basically, you are saying 'if recaptcha is true, then do this'
this is complete form code that helps you (I'm using typeScipt)
const Formid = // yout formid
const FormSpark = `https://submit-form.com/${Formid}`
type FormState = {
name: string,
mail: string,
message: string
}
const initialState = {
name: '',
mail: '',
message: '',
}
const [wrongmail, setWrongmail] = useState(false)
const [wrongname, setWronname] = useState(false)
const [wrongtext, setWrongtext] = useState(false)
const [alert, setAlert] = useState(false)
const recaptchaRef = useRef<any>()
const recaptchaKey = //your recaptcha public key const [recaptchaToken, setRecaptchaToken] = useState<string>()
const [formstate, setFormState] = useState<FormState>(initialState)
const submit = async(event: FormEvent) =>{
event.preventDefault()
await postSubmission()
}
const updateRecaptcha = (token: string | null)=>{
setRecaptchaToken(token as string)
}
const {name, mail, message} = formstate
const postSubmission = async() => {
const payload = {
...formstate,
"g-recaptcha-response": recaptchaToken
}
try {
if (name && mail && message) {
if (mail.includes('#') && mail.includes('.') && mail.length > 5) {
if (name.includes(' ') && name.length> 5) {
if (message.length > 20) {
if (recaptchaRef.current) {
if (recaptchaRef.current.props.grecaptcha.getResponse().length !== 0) {
console.log('hola')
setAlert(true)
const result = await axios.post(FormSpark, payload)
setFormState(initialState)
recaptchaRef.current.reset()
if (result) {
setTimeout(() => {
setAlert(false)
},2000)
}
}
}
}
}
}
if (!name && !(name.length> 5) && !(name.includes(' '))) {
setWronname(true)
setTimeout(() => {
setWronname(false)
},3000)
}
if (!mail && !mail.includes('#') && !mail.includes('.') && !(mail.length > 5)) {
setWrongmail(true)
setTimeout(()=>{
setWrongmail(false)
},3000)
}
if (!message && !(message.length > 20)) {
setWrongtext(true)
setTimeout(() => {
setWrongtext(false)
},3000)
}
}
} catch(error){
console.log(error);
}
}
const updateForm = (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const {id, value} = event.target
const formKey = id as keyof FormState
const updatedFormState = {...formstate}
updatedFormState[formKey] = value
setFormState(updatedFormState)
}