1

I have html form with action ="script.php" which sends data.

I want prevent form to being sent with JS but it does nothing and sends data. Naslov = title

This is html:
<form name = "my_form" enctype="multipart/form-data"  method = "POST" action = "skripta.php">
    <div class="form-group row  ">
         <div class="col-md-6">
             <span id="porukaTitle" class="bojaPoruke"></span> 
             <label  for="naslov">Naslov</label>
             <input  type="text"  name="naslov" class="form-control" id="naslov">
         </div>
</form>

And this is JS:

<script type="text/javascript">
     document.getElementById("slanje").onclick = function (event) {
       var slanjeForme=true;
       var poljeTitle=document.getElementById("naslov");
       var naslov=document.getElementById("naslov").value;
       if (naslov.lenght < 5 || naslov.lenght > 30) {
          slanjeForme=false;
          poljeTitle.style.border="1px dashed red";
          document.getElementById("porukaTitle").innerHTML="Naslov vjesti mora imati između 5 i 30 znakova!<br>"; 
       } else { 
          poljeTitle.style.border="1px solid green";          
          document.getElementById( "porukaTitle").innerHTML="";                    
       }

       if (slanjeForme != true) {
        event.preventDefault();
       }            
     }
</script>

Problem is that it always sends data.

Rastalamm
  • 1,712
  • 3
  • 23
  • 32
Unknow123
  • 19
  • 2
  • Which element has id "slanje"? Do you have the script before or after the form? – Guy Incognito Jun 11 '20 at 20:23
  • After, submit has id=slanje – Unknow123 Jun 11 '20 at 20:25
  • I don't know if it is a typo or your actual issue cause, but indenting your code I noticed that a div closing tag is missing. – Roberto Caboni Jun 11 '20 at 20:38
  • 1
    don't use a click event on the submit button. use a .submit event on the form and event.preventDefault on the form submit event and not the click event on the button in the form here's some relevant info https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission https://stackoverflow.com/questions/3350247/how-to-prevent-form-from-being-submitted/34347610 – admcfajn Jun 11 '20 at 20:42
  • At the very least, `naslov.lenght` should be `naslov.length` – Rastalamm Jun 11 '20 at 20:48
  • I dont understand – Unknow123 Jun 11 '20 at 20:58
  • He means you have a typo. The property name is not `lenght` it's `length`. – JakeParis Jun 11 '20 at 21:07

3 Answers3

0
  • Don't use the "click" handler, instead use the FORM's "submit" Event handler!
  • Create a nifty reusable validate function that will also handle the input style using classList.toggle()
  • Populate your validate function with the needed validators
  • Use finally CSS to handle error borders and messages visibility using the class is-error
  • Always place the error SPAN elements as siblings to a desired action element, that way when an input gets the .is-error we can target it using the CSS's General Sibling Combinator ~

No matter how many inputs you have, you don't need to write extra JS logic. Just validate the desired ones like const has_err = validate(EL("#foo"), "length");

const validate = (el, validatorName = "length") => {

  const val = el.value.trim();
  const isErr = {

    // Basic, validates if there's value
    length: () => val.length < 1,
    
    // Validate between 5 and 30 charaters
    length_5_30: () => val.length < 5 || val.length > 30,
    
    // Add more validators
    
  }[validatorName]();
  
  el.classList.toggle("is-error", isErr);
  return isErr;
};


const EL = (sel, EL) => (EL || document).querySelector(sel);
EL("#my_form").addEventListener("submit", function(event) {

  const err_1 = validate(EL("#naslov"), "length_5_30");
  const err_2 = validate(EL("#bla"), "length");

  if (err_1 || err_2) {
    event.preventDefault();
  }
});
form .is-error {
  outline: 1px dashed red;
}

form .error-message {
  display: none;
  color: red;
}

form .is-error ~ .error-message {
  display: block;
}
<form id="my_form" name="my_form" enctype="multipart/form-data" method="POST" action="skripta.php">
  <div class="form-group row">
    <div class="col-md-6">
      <label for="naslov">Naslov</label>
      <input type="text" id="naslov" name="naslov" class="form-control">
      <span class="error-message">Naslov vjesti mora imati između 5 i 30 znakova!</span>
    </div>
  </div>
  <div class="form-group row">
    <div class="col-md-6">
      <label for="naslov">Bla bla</label>
      <input type="text" id="bla" name="bla" class="form-control">
      <span class="error-message">Ovo polje ne može biti prazno!</span>
    </div>
  </div>
  <button type="submit">Pošalji</button>
</form>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • Are you just downvoting my answer because yours is more developed? Your answer is fine, but there's also nothing wrong with mine. Please don't misuse the downvote mechanism that way. Or, if you think there's something wrong with it, at least tell me so I can fix it. – JakeParis Jun 12 '20 at 01:54
-1

The best way to stop a form from submitted is to hook into its submit event, and do so in the javascript, rather than add javascript into the html. That would look like this:

var form = document.querySelector('form.myform');

form.addEventListener('submit', e => {
  // put your conditional here
  if( please_dont_submit == true ) {
    e.preventDefault();
  }
  
  // else form will submit; 
});
<form class="myform">
   <!-- form stuff -->
   <input type="submit" value="Submit">
</form>

You may also wish to submit the form from within itself, after doing the preventDefault(). You can do that by setting a flag to indicate that the check has already been processed:

const form = document.querySelector('form.myform');

var okToSubmit = false;

form.addEventListener('submit', e => {
    // put your conditional here
    if( please_dont_submit == true && ! okToSubmit ) {
        e.preventDefault();

        // do some further processing and submit again.
        okToSubmit = true;
        e.target.submit();
    }

    // else form will submit; 
});
JakeParis
  • 11,056
  • 3
  • 42
  • 65
  • Not the drive-by*er*, but having a look at what you posted: your answer seems OK-ish?, though, the live snippet is not of much use. Also, fixing a user input from within a function is extremely odd, and than needlessly setting `okToSubmit = true;` is not much of a gain. Also `please_dont_submit` is `undefined`... clearly an example, but could present quite a task for a novice developer (*"where to define it? How to handle it?"*). – Roko C. Buljan Jun 12 '20 at 07:57
  • also, you're presuming an `// else form will submit;` therefore *"code can go here"* (I suppose...) but you didn't Early Return with `return e.target.submit();` to exit the function and prevent further useless actions since you already manually submitted the form. – Roko C. Buljan Jun 12 '20 at 07:58
-1

You should use a form validation function instead. In your form, add an attribute called "onsubmit". The form should look similar to this:

<form onsubmit="return checkBeforeSubmitting()"></form>

Then, you can have a function run before data is sent. If you don't want data to be sent, make the "checkBeforeSubmitting()" return false under a certain condition.

Link to more info on how to use this: https://www.w3schools.com/js/js_validation.asp

Ezi CS
  • 24
  • 6