2

I want to make multiple button for different text boxes that uses the same function but store on different id names.

Name<input id="name"></input>
<button onclick="myFunction()">Start</button>

<script>
    function myFunction() {
        var recognition = new (window.SpeechRecognition || 
        window.webkitSpeechRecognition || window.mozSpeechRecognition || 
        window.msSpeechRecognition)();
        recognition.lang = 'en-US';
        recognition.interimResults = false;
        recognition.maxAlternatives = 5;
        recognition.start();
        recognition.onresult = function(event) {
           document.getElementById("name").value =(event.results[0][0].transcript);
         };
    }
</script>
1
  • 1
    Store the id into a data-* attribute in a button, then read the value of the attribute in the function instead of hardcoding the id. Commented Nov 25, 2018 at 18:15

1 Answer 1

3

Pass the ID of input field when calling the function, like this

Name<input id="name"></input>
<button onclick="myFunction('name')">Start</button>

Phone<input id="phone"></input>
<button onclick="myFunction('phone')">Start</button>


<script>
function myFunction(id) {
    var recognition = new (window.SpeechRecognition || 
        window.webkitSpeechRecognition || window.mozSpeechRecognition || 
        window.msSpeechRecognition)();
    recognition.lang = 'en-US';
    recognition.interimResults = false;
    recognition.maxAlternatives = 5;
    recognition.start();
    recognition.onresult = function(event) {    
         document.getElementById(id).value =(event.results[0][0].transcript);
    };
}
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

I am glad I was able to help. Please accept the answer so others can learn too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.