简体   繁体   中英

Javascript: onclick function works once then page reverts back to original

This is a prototype, so what I'm trying to get is, when you click chat without anything in text-area, the 'bot' text will change, and a counter will go up each time so the message will subsequently different.

But what I'm getting is, the text will change, but then the page quickly reverts back.

The javascript in the head

<script>
var emptyCount = 0;
function startR() {
 console.log("jkfj");
 var text = document.getElementById('talk').value;
 if (!text) {
     if (emptyCount == 0) {
         document.getElementById('bot').innerHTML = "<h2>You need to say something first</h2><br />";
         emptyCount++;
     } else if (emptyCount == 1) {
         document.getElementById('bot').innerHTML = "<h2>What's wrong with you?</h2><br />";
         emptyCount++;
     } else if (emptyCount == 2) {
         document.getElementById('bot').innerHTML = "<h2>If you send another blank message I will deactivate the chat button.</h2><br />";
         emptyCount++;
     } else {
         alert("asd");
         $.ajax({
             url: 'queryBot.php',
             type: 'get',
             data: {
                 text: text
             },
             async: false,
             success: function (data) {
                 document.getElementById('bot').innerHTML = "<h2>" + data + "</h2><br />";
             },
             cache: false
         });
     }
 }
}
</script>

HTML components

<div id="bot">
    <h2>What do you want?</h2><br />
</div>
<input id="talk" type="textarea" class="tb5" name="searchterm" placeholder="Type to talk">
<input id="chat" type="submit" class="btn btn-success" onclick="startR()" value="Chat">

You are submitting your form with your input type=submit . Try adding a button without type submit or add an eventlistener to your form and add event.preventDefault() .

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