简体   繁体   中英

Speech Recognition in HTML Forms

I'm a beginner in javascript, I want to create a form that accepts users voice and display it in the input-text field.

<body>
    <textarea name="answer1" id="my_field1" cols="80" rows="4"></textarea>
    <button onclick="change1()">Change Text</button>
</body>
<script>
function change1(){
    var recognition = new webkitSpeechRecognition();
    recognition.lang = "en-GB";

    recognition.onresult = function(event) {
        // console.log(event);
        document.getElementById('my_field1').value = event.results[0][0].transcript;
    }
    recognition.start();
}
</script>

This works perfectly, but when I use this inside a form tag it doesn't work

<form action="" method="GET">
    <textarea name="answer1" id="my_field1" cols="80" rows="4"></textarea>
    <button onclick="change1()">Change Text</button>
    <br>
    <input type="submit" name="" id="">
</form>
<script>
function change1(){
    var recognition = new webkitSpeechRecognition();
    recognition.lang = "en-GB";

    recognition.onresult = function(event) {
        // console.log(event);
        document.getElementById('my_field1').value = event.results[0][0].transcript;
    }
    recognition.start();
}
</script>

Here when I click the Change Text button, nothing happens, and the URL changes file:///C:/Users/zjohn/Desktop/sample1.html?answer1=

Please tell me where I went wrong, and how to solve this issue.

The form is submitting when you click the button! You need to preventDefault() on the button so it doesnt submit.

Try below:

<form action="" method="GET">
    <textarea name="answer1" id="my_field1" cols="80" rows="4"></textarea>
    <button onclick="preventDefault(); change1();">Change Text</button>
    <br>
    <input type="submit" name="" id="">
</form>
<script>
function change1(){
    var recognition = new webkitSpeechRecognition();
    recognition.lang = "en-GB";

    recognition.onresult = function(event) {
        // console.log(event);
        document.getElementById('my_field1').value = event.results[0][0].transcript;
    }
    recognition.start();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM