Search code examples
javascriptif-statementconfirm

How can I make my confirm statement post a status if my function evaluates as true, or cancel if false?


I want a confirm box to pop-up when the user clicks submit, but only if their post contains a string such as 'sale' and '£'. Unfortunately the code forwards to the action page regardless of whether OK or Cancel was clicked.

I also tried creating another 'if else' containing the confirm statement, to return true for Ok or False for Cancel, but to no avail.

Sorry if some of that is hard to understand, I'm a noob and trying to wrap my head around JavaScript.

<script>
function check() {

 var post = document.forms["myForm"]["newPost"].value;
    if (post.indexOf('sale') > -1 || post.indexOf('£') > -1) {
     confirm("If this is a 'for sale' post, please post to the marketplace instead. Press OK to post as a general status."); 
 }
}
</script>

<form name="myForm" action="/post-page.php" onSubmit="return check()" method="post">
Post: <input name="newPost" id="newPost">
  <input type="submit" value="Post Now">
</form>

Expected: Pressing OK posts the status.

Results: Both options post the status.


Solution

  • You have to use the return value of confirm() to control the flow of the event:

    function check() {
    
     var post = document.forms["myForm"]["newPost"].value;
        if (post.indexOf('sale') > -1 || post.indexOf('£') > -1) {
         var res = confirm("If this is a 'for sale' post, please post to the marketplace instead. Press OK to post as a general status."); 
         if(res) return true;
         else return false;
     }
    }
    <form name="myForm" action="/post-page.php" onSubmit="return check()" method="post">
    Post: <input name="newPost" id="newPost">
      <input type="submit" value="Post Now">
    </form>