JavaScript form validation removes values

I am using a JavaScript library for client-side form validation (https://github.com/cferdinandi/bouncer). It works very well but has one strange behaviour that I don’t understand.

I have two buttons for the form submit, each with a different value. Without validating this form using the library I will retrieve the exact value on server-side. But when I use the library for validation the value will disappear. All other form values are available. I checked the whole library code and found out that "event.preventDefault()" seems to be the problem.

When I remove this line everything is fine but of course, form validation won’t work.

Someone has any idea?

var submitHandler = function (event) {              // Only run on matching elements             if (!event.target.matches(selector)) return;              // Prevent form submission             event.preventDefault();              // Validate each field             var errors = publicAPIs.validateAll(event.target);              // If there are errors, focus on the first one             if (errors.length > 0) {                 errors[0].focus();                 emitEvent(event.target, 'bouncerFormInvalid', {errors: errors});                 return;             }              // Otherwise, submit if not disabled             if (!settings.disableSubmit) {                 event.target.submit();             }              // Emit custom event             if (settings.emitEvents) {                 emitEvent(event.target, 'bouncerFormValid');             }          }; 
<button class="" name="page[__page]" type="submit" value="0">back</button> <button class="" name="page[__page]" type="submit" value="2">next</button> 
Add Comment
1 Answer(s)

The issue, accordingly to standards, seems to be that the submitter is not forwarded, when .submit() is invoked:

If any of the following is true:

  • The field element is a button but it is not submitter.

Then continue.

This case seems to be resolvable moving that information into an hidden field, and use the submitter, which is either next, or prev, to populate its value.

Example

document.body.innerHTML = `   <form>     <input type="hidden" name="page[__page]">     <button class="" type="submit" value="0">back</button>     <button class="" type="submit" value="2">next</button>   </form> `;  document.body.firstElementChild.addEventListener('submit', e => {   e.preventDefault();   var page = e.target.querySelector('input[name="page[__page]"]');   page.value = e.submitter.value;   e.target.submit(); }); 

At this point, the page will be passed around as expected, and your issue should be resolved.

P.S. you could also explore form.repostValidity() and use e.preventDefault() only if the report returns false.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.