Help with modal window

I am using this modal window code successfully, where a selection must be made to proceed:

<script>
$(document).ready(function() {
new jBox('Confirm', {
content: '<h5 style="color:white;">Simply Select <i>Continue</i><br /> To Agree To The</h5> <a href="/terms.html"><h5 style="color:#cccccc;"><u>Terms</u></h5></a>',
width: 430,
height: 105,
cancelButton: '<a href="/index.html"><h5 style="color:white;">Return Home</h5></a>',
confirmButton: '<h5 style="color:white;">Continue</h5>',
confirm: function () {
close();
},
    cancel: function () {
    disable(),
    window.location.href = "/index.html";
    }
  }).open();
});
</script>

I’m trying to modify it so that a Form, with a name and email address, would be required, as well, in order to proceed. I attempted adding the … code to the content: ’ ', area of the code above, with no success.
Any guidance will be appreciated.

Hi @ChrisjChrisj, first of all I would suggest not to put your markup in your JS as this becomes unreadable pretty quickly; instead, use template elements (also, better avoid inline styles and wrapping everything in headline elements just to make the text larger – this should all be done in your dedicated CSS files):

<template id="modal-content">
  Please fill in your name and email:

  <form>
    <label>
      Name:
      <input type="text" name="name" required>
    </label>

    <label>
      Email:
      <input type="email" name="email" required>
    </label>
  </form>
</template>

<template id="modal-cancel">
  <a href="/index.html">Return Home</a>
</template>

<template id="modal-confirm">
  Continue
</template>

As for the JS, I’m not familiar with jBox but from looking at the API there doesn’t seem to be a way to directly disable the confirm button; what you might do though is removing the default click handler when the modal opens, and then manually close the modal after checking the validity of the contained form:

$(document).ready(function () {
  new jBox('Confirm', {
    content: $('#modal-content').html(),
    cancelButton: $('#modal-cancel').html(),
    confirmButton: $('#modal-confirm').html(),
    onOpen: function () {
      // Get a reference to the form within
      // the modal content
      var form = $('form', this.content).get(0)

      // Remove the default click handler
      this.submitButton.off('click')

      // Then first test for the form validity
      // before closing the modal
      this.submitButton.on('click', function () {
        if (form.reportValidity()) {
          this.close()
        }
      }.bind(this))
    }
  }).open()
})

(BTW your cancel() method is actually redundant as jBox already checks for the href in your cancel button markup anyway. Furthermore, your disbale() and close() functions are not defined…)

Anyway I’m not sure if that jBox library is really intended for embedded forms and the like TBH, so you might look for a more sophisticated solution here.

1 Like

Thanks for your reply.
Can you give me an example of this:
// Get a reference to the form within
// the modal content

Also, maybe you can help me some more after seeing this .js file plugin that shows this:
// Content
content: null, // You can use HTML or a jQuery element, e.g. jQuery(‘#jBox-content’). The elements will be appended to the content element and then made visible, so hide them with style=“display: none” beforehand

getContent: null, // Get the content from an attribute when jBox opens, e.g. getContent: ‘data-content’. Use ‘html’ to get the attached elements HTML as content

title: null, // Adds a title to your jBox

getTitle: null, // Get the title from an attribute when jBox opens, e.g. getTitle: ‘data-title’

footer: null, // Adds a footer to your jBox

isolateScroll: true, // Isolates scrolling to the content container

any additional help is appreciated.

It’s just the following line:

var form = $('form', this.content).get(0)

Inside the onOpen() callback, this refers to the jBox instance, and its content property to its (jQuery’d) content. From that content, you can then get a reference to the contained form; however we need the actual DOM element (via get(0)) so we can call its reportValidity()mehod, which jQuery does not support AFAIK.

Ah I was not aware of this; in this case you can also just write

new jBox('Confirm', {
  content: $('#modal-content'),
  cancelButton: $('#modal-cancel'),
  confirmButton: $('#modal-confirm'),
  // ...
}).open()

– i.e. without the html() calls. Note however that this will append the referenced elements themselves to the modal (unless you explicitly pass clone()'d copies); this also means that it won’t work with template elements, so you’d just use divs instead then.

As for the getContent option, this seems to be used when attach()ing the modal to an element such as

<a href="" data-content="Some content" id="open">Open modal</a>

<script>
new jBox('Confirm', {
  getContent: 'data-content'
}).attach('#open')
</script>

This is obviously not suitable for complex markup such as forms though, or any markup other than text for that matter.

Many thanks for your reply.

Currently, regarding ‘name’ and ‘email’ I have this in JS:

  myConfirm = new jBox('Confirm', {
    content: $('.my-jbox-form'),
    width: 830,
    height: 205,
    cancelButton: 'Return Home',
    confirmButton: 'Continue',
    closeOnConfirm: false,
    closeOnEsc: false,
    confirm: function() {
      if (
	!$('#name').val() ||
	!$('#email').val()
    	) {
ETC.....

And this ‘name’ and ‘email’ in Html:

<form>.......
<input class="form-control" type="text" name="name" placeholder="Name">
<input class="form-control" type="email" email="email" placeholder="Email" required>
.........</form>

And this ‘name’ and ‘email’ in Php:

<?php.........
$name = $_POST['name'];
$email = $_POST['email'];
.......?>

They don’t all work together.
I can’t add the id =" " into this, like so:

<form>.......
<input class="form-control" type="text" id="name" name="name" placeholder="Name">
<input class="form-control" type="email" id="email" email="email" placeholder="Email" required>
.........</form>

so, please, what can I change to get them all to work together?

Any help is appreciated.

Why not?

You might of course use any selector here to get the value, not just the ID… such as $('..my-jbox-form .email').val(). Or better yet, use the constraint validation API so that you don’t need to explicitly query the elements at all, but can just add required and type="email" attributes etc. as shown above. Here’s a more in-depth guide:

The advantage of this more declarative approach is less JS code, and a more robust validation altogether as you don’t have to reinvent checking for valid email values (say) using unwieldy regular expressions. Here’s a pen using your updated code:

Nice solution to just set closeOnConfirm: false BTW – this is indeed much better than removing the default click handler altogether. :-) I was again not aware of this option. ^^

That looks right to me… given you have actually set your form to method="POST". How are you currently submitting the form anyway though – using AJAX or just by calling form.submit()? And what do you get when dumping the entire $_REQUEST?

Much thanks again for your reply.
Regarding your question “How are you currently submitting the form…?”
This was suggested, but, after several attempts it’s clear that I don’t know how to combine it with your code:

$.ajax({
  url: 'https://.../submit.php',
  method: 'post',
  data: {
    name: $('#name').val(),
    email: $('#email').val()
  },
  success: function (response) {
    console.log(response);
    if (response.success) {
      alert('Success');
    } else {
      alert('Error');
    }
  }
});

any additional guidance is welcomed.

Suggested in which context – is there a thread for some background? I still don’t understand why you can’t add those IDs, for example…

If you have a look at my pen, I’m simply submit()ing the form if the validation succeeds – but you might as well post the form data using $.ajax() instead. BTW you don’t need to pass each field separately, you can just serialize() the entire form and send that as the data.

Thanks for your replies.

So, I am currently using this, but after ‘Continue’ is selected, the mail is sent but the jBox doesn’t close, and I don’t know if anything is getting validated:

var myConfirm;
$(document).ready(function() {

  myConfirm = new jBox('Confirm', {
    content: $('.my-jbox-form'),
    width: 830,
    height: 205,
    cancelButton: 'Return Home',
    confirmButton: 'Continue',
    closeOnConfirm: false,
    closeOnEsc: false,
    confirm: function() {
    $.ajax({
  url: 'https://...../submit.php',
  method: 'post',
  data: {
    name: $('#name').val(),
    email: $('#email').val()
  },
  success: function (response) {
    console.log(response);
    if (response.success) {
      alert('Success');
    } else {
      alert('Error');
    }
  }
});

along with this:

<div class="my-jbox-form" style="display: none">
<input class="form-control" type="text" id="name" placeholder="Name">
<br>
<label><input class="form-control" type="email" id="email" placeholder="Email" list="defaultEmails" size="64" maxlength="256" multiple required>
</label>
</div>

<datalist id="defaultEmails">
  <option value="jbond007@mi6.defence.gov.uk">
  <option value="jbourne@unknown.net">
  <option value="nfury@shield.org">
  <option value="tony@starkindustries.com">
  <option value="hulk@grrrrrrrr.arg">
</datalist>

any additional assistance/guidance is appreciated.

Well you explicitly set the jBox to closeOnConfirm: false, so you’d have to close() it manually inside the $.ajax() success handler (where you are alert()ing “Success”).

Probably not, since you’re not doing any validation at all now – at least as far as I can tell from your frontend code. If your backend validation fails though you might handle that inside the else block where you are alert()ing “Error”; FE validation is always just an addendum to BE validation anyway for some nicer UX.

This is not even valid syntax; you can check the console of your browser dev tools for such errors. closeOnConfirm is a property you can set in the constructor options object; if you want to close the modal manually, you’ll have to use the close() method.

Thanks again.
I had posted, then realized it was incorrect, deleted it, and then I saw that you had replied. Thanks again for that.
I see the option .close(); and have tried many ways to place it within this code without success:

success: function (response) {
    console.log(response);
    if (response.success) {
      alert('Success');
    } else {

any guidance is appreciated

No worries… where are you trying to close the modal though?

Thanks again. The goal it to close the jBox upon success and not close it upon Error.
So, if you mean ‘where’ I added .close() many places like this, without success:

success: function (response) {
    console.log(response);
    if (response.success) {
      alert('Success');
.close();

also, I get no Console errors, but upon selecting ‘Continue’ the page shows a dialog box that shows “web-site-name.com says Error”, yet the Form field info gets sent successfully.

Which may be from no validation in the submit.php?

Here is submit.php:

<?php
if($_POST){
	$to = 'chrisj....@hotmail.com';
	$subject = 'Thank You';
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];
	$message1 = $_POST['message'];
	$headers = $name;
	$headers = 'from: support@web-site-name.com';

	$message1 .= "\r\n\r\nName: ".$_POST['name']." \r\n Email: ".$_POST['email']." ";

	$message = "Hello {$_POST['name']}, ~ Thank you\r\n\r\n";

   		mail( $to, $subject, $message1, $headers );
   		mail( $email, $subject, $message, $headers );

		header('Location: https://web-site-name.com');
   exit;
}
?>

Any additional guidance is welcomed.

Really? oO This is again not valid syntax; if you just open the console, type .close() and press enter, you’ll get an

Uncaught SyntaxError: Unexpected token ‘.’

This is because methods are called on objects using the dot syntax; you already did that correctly in your post #1 of this thread where you are calling open() on the jBox instance. Later, in your post #5, you are also assigning that instance to a myConfirm variable, so you can call myConfirm.close() at any point.

There doesn’t seem to be any validation in your PHP, you’re just sending the message without checking for the $_POST data. Again, the BE validation is the really important part – FE validation is just to give the user some early feedback, but can always be bypassed.

If your PHP would throw an actual error though, that would have to be handled in the error callback of your $.ajax() request (it works analogously to the success callback you’re using already).

Thanks for all the replies.
I attempted adding this call back validation code ( everything above if($_POST) ) in the submit.php file, without success:

<?php
$errors         = array();  
$data           = array();  

    if (empty($_POST['name']))
        $errors['name'] = 'Name is required.';

    if (empty($_POST['email']))
        $errors['email'] = 'Email is required.';

    if ( ! empty($errors)) {

        $data['success'] = false;
        $data['errors']  = $errors;
    }
    echo json_encode($data);

if($_POST){
	$to = 'chrisj....@hotmail.com';
	$subject = 'Thank You';
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];
	$message1 = $_POST['message'];
	$headers = $name;
	$headers = 'from: support@web-site-name.com';

	$message1 .= "\r\n\r\nName: ".$_POST['name']." \r\n Email: ".$_POST['email']." ";

	$message = "Hello {$_POST['name']}, ~ Thank you\r\n\r\n";

   		mail( $to, $subject, $message1, $headers );
   		mail( $email, $subject, $message, $headers );

		//header('Location: https://web-site-name.com');
   exit;
}
?>

After excuting the Form, still get a dialog box, on the Form page, that shows “web-site-name.com says Error”, yet the Form’s field info gets sent successfully.

And after Form submit, in the dev tools > Console it only shows one line,

[ ] upload.html:78

And, of course, the Form (jBox) doesn’t close.
Any additional help with call back and validation, is appreciated.

I wanted to edit #18, but can’t seem to do it.
Can anyone tell me why?

You can only edit your posts for a certain amount of time (not sure how long exactly though).

1 Like

It’s only for a few hours that you can edit your post, and even then it’s not a good idea to make significant changes as nobody is notified when edits occur.

2 Likes

Ok, thanks, well, I added the header line and it now looks like this:

<?php
header('Content-type: application/json');
$errors         = array();  
$data           = array();  

    if (empty($_POST['name']))
        $errors['name'] = 'Name is required.';

    if (empty($_POST['email']))
        $errors['email'] = 'Email is required.';

    if ( ! empty($errors)) {

        $data['success'] = false;
        $data['errors']  = $errors;
    }
    echo json_encode($data);

if($_POST){
	$to = 'chrisj....@hotmail.com';
	$subject = 'Thank You';
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];
	$message1 = $_POST['message'];
	$headers = $name;
	$headers = 'from: support@web-site-name.com';

	$message1 .= "\r\n\r\nName: ".$_POST['name']." \r\n Email: ".$_POST['email']." ";

	$message = "Hello {$_POST['name']}, ~ Thank you\r\n\r\n";

   		mail( $to, $subject, $message1, $headers );
   		mail( $email, $subject, $message, $headers );

		//header('Location: https://web-site-name.com');
   exit;
}?>

and the .js looks like this:

var myConfirm;
$(document).ready(function() {

  myConfirm = new jBox('Confirm', {
    content: $('.my-jbox-form'),
    width: 830,
    height: 205,
    cancelButton: 'Return Home',
    confirmButton: 'Continue',
    closeOnConfirm: false,
    closeOnEsc: false,
    confirm: function() {
    $.ajax({
  url: 'https://...../submit.php',
  method: 'post',
  data: {
    name: $('#name').val(),
    email: $('#email').val()
  },
  success: function (response) {
    console.log(response);
    if (response.success) {
      alert('Success');
    } else {
      alert('Error');
    }
  }
});

And I’ve tried to add: myConfirm.close(); into the .js code, but not sure where is the best place to put it.

After excuting the Form, still get a dialog box, on the Form page, that shows “http://…com says Error”, yet the Form’s field info gets sent successfully.

And after Form submit, in the dev tools > Console it only shows one line,

[ ] upload.html:78

And, of course, the Form (jBox) doesn’t close.

Any additional guidance/suggestions with call back and validation, and close() is appreciated.