0

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.

1 Answers1

0

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();
}
cam
  • 3,179
  • 1
  • 12
  • 15