1

$('.submitform').submit(function(event) {
  event.preventDefault();

  if (($(this).attr("modal-val") == 'modal1') && ($(this).attr("field-value") == '0')) {
    console.log('You can not submit 0');
    return;
  }

  console.log("This one continues to execute")

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div>

  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal1" data-hidden-val="a" name="submit_hidden" style="position: center;">Add</button>
</div>


<div class="modal" id="modal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form action="process.php" method="POST" class="submitform">
        <div class="modal-body">
          <div class="form-group">
            <label for="field-value">Field Value:</label>
            <input type="number" value="0" id="field-value" name="field-value">
          </div>
          <div class="form-group">
            <input type="hidden" value="modal1" id="modal-val" name="modal-val">
          </div>
          <div class="form-group">
            <input type="hidden" value="" id="subfield" name="subfield">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

I want to conduct a form validation inside submit(function(event){}). Normally people follow these steps:

  • on button click call validation function.
  • Validate the form and forward to submit function if valid.
  • If not properly filled form warn the user.

What I want to do is:

  • call submit(function(event){}).
  • Inside an if block check the validation.
  • If form is validated continue.
  • If form is not validated break from submit(function(event){}).

I want to follow this practice because I'm accessing some data attibutes of the submit button and don't want to pass it around.

colt.exe
  • 708
  • 8
  • 24
  • Lets see it run – react_or_angluar Dec 17 '20 at 00:00
  • At a glance the code seems to do what you want. What's the problem here? –  Dec 17 '20 at 00:04
  • Normally it should stop execution if someone submits 0 to the mentioned field but it continues to execution. I got my database written and receive POST message. – colt.exe Dec 17 '20 at 00:14
  • You could use PHP for the validation, but I wouldn't. – react_or_angluar Dec 17 '20 at 00:16
  • Okay, possibly a stupid question, PHP brought me here but where is the `modal-val` attribute? – user3783243 Dec 17 '20 at 00:18
  • @user3783243 inside modal body. It is a hidden attribute and I use it in the sql query to determine which table should I write in. – colt.exe Dec 17 '20 at 00:22
  • I'm not seeing an attribute named that. I see a `name` attribute with that value and an `id` attribute with that value. Maybe this is pseudo code? If this is literal than maybe https://jsfiddle.net/v37oxny6/4/ performs as expected? – user3783243 Dec 17 '20 at 00:26
  • @user3783243 added snippet. hope this clarifies. – colt.exe Dec 17 '20 at 00:34
  • 1
    Side note: never allow your app to contain only client-side validation. It's a nice touch for the user, but it's unreliable. Even if it's not performing as expected, server-side validation should prevent invalid values enter the database. – El_Vanja Dec 17 '20 at 00:37
  • @El_Vanja You are right. I skipped that part since this is kinda local project with few users plus I do also use another forms of sanitizations. – colt.exe Dec 17 '20 at 00:41
  • Moving on with debugging: `$(this).attr("modal-val")` is `undefined`. `this` represent the form; the form element doesn't have this attribute. You need to locate your hidden input specifically. Same goes for the other one with `field-value`. – El_Vanja Dec 17 '20 at 00:44
  • @El_Vanja Ouw now I get it. I was serializing the form and had `modal-val` variable and thought I could access them via `$(this).attr()`. Any way to access the modal-val? – colt.exe Dec 17 '20 at 00:51

2 Answers2

2

Your condition is your culprit:

if (($(this).attr("modal-val") == 'modal1') && ($(this).attr("field-value") == '0'))

The problem is that this represents the form element. You're trying to access attributes on the form, but the form doesn't have them - it has the inputs you need, and it is them that have these attributes. So you need to fetch these inputs specifically and get their values:

if ($("#modal-val").val() == 'modal1' && $("#field-value").val() == '0')

and it should perform as expected.

El_Vanja
  • 3,660
  • 4
  • 18
  • 21
  • Thanks for your efforts. Is there a way I can reach `modal-val` with `$(this)`. Currently `$(this).serialize()` can give a serialized string for all form fields. Any way to get these fields like `$(this).getfield('modal-val')` – colt.exe Dec 17 '20 at 01:03
  • There's probably a way of getting the jQuery objects that represent the inputs from `this`, though I don't see how it could be made any simpler than this approach. I don't think there's a shortcut such as the `getfield` you suggested. – El_Vanja Dec 17 '20 at 01:18
  • I found a way to get value of `modal-val`. `var formDataArray = $(this).serializeArray(); ` after that I can reach the value of `modal-val` by typing its index like `formDataArray[1].value`. This returns `modal1` for my example and its the exact thing that I needed. Accessing via `$("#modal-val").val()`is not feasible for me since there are 9 modals I'm sending to this function and `modal-val` should be derived from form data. Thanks for the efforts. – colt.exe Dec 17 '20 at 20:43
  • 1
    This is neater. Accessing via field name in case order of array is inconsistent. https://stackoverflow.com/questions/4236768/how-do-i-access-values-created-by-serializearray-in-jquery – colt.exe Dec 17 '20 at 20:46
0

The following code piece works as intended. It collects form data as an array and every field and value can be accessed.

<script>
    $('.submitform').submit(function(event) {
        event.preventDefault();
        
        //serialize the form into an array
        var formDataArray = $(this).serializeArray();
        //create empty array
        var formObj = {};

        //copy each element into array
        $(formDataArray).each(function(i, field) {
            formObj[field.name] = field.value;
        });

        //access with field names
        if ((formObj['modal-val'] == 'modal1') && (formObj['field-value'] == '0')) {
            console.log('You can not submit 0');
            return;
        }

    })
</script>
colt.exe
  • 708
  • 8
  • 24