Search code examples
javascriptjqueryjquery-mobilerefreshtext-to-speech

Jquery mobile function not working == page refresh?


Ok this thing is driving me crazy. I have a simple project in which I use this mobile bootstrap theme and this text-to-speech library

Whenever there's an error in my function, the page just refreshes itself. In this way I can never read any output from the console.

Here's my code:

<script>
    $(document).ready(function() {    
        $('#input-submit').click(function() {
            var text = $('#input-box').val();
            console.log(text);
            for (var i = 0;i < text.length; i++){
                alert('test');
                meSpeak.speak(text.charAt(i));
            }
        });
    });
</script>

I want my app to spell out loud whatever the user fills in. The function works correctly until the meSpeak.speak(text.charAt(i)); line. When I type in a 3 character word I get 3 alerts, and then the page just refreshes itself.

Why does it refresh when there's something not working? I want to read the output from the console without using alerts. Also, does anyone know why I can't use meSpeak.speak(text.charAt(i)); like this?


Solution

  • You're not preventing the submit button from "submitting" the page, and as you've most likely set no destination, it's submitting to the same location, causing a page refresh.

    Preventing the click event can be done in jQuery by returning false at the end of the function

    $('#input-submit').click(function () {
        /* etc */
        return false;
    });
    

    Demo to play with