简体   繁体   中英

Conditionally open url in new tab via js

I have a survey-like web application where a user selects a number of checkboxes and then presses "Submit" button-like link

<!-- page: /survey -->
<form id="survey" method="post" action="/complete">
    <!-- checkboxes, etc here -->
    <a id="submit" class="button" href="#">Submit</a>
</form>
<script>
    $('#submit').on('click', function (e) {
        e.preventDefault();
        //... other staff happens here
        $('#survey').submit();
    });
</script>

Then the form is processed on the server and results are shown to the user on /complete page.

What I want to achieve is to conditionally open a new tab after form was submitted. This condition and the url of the tab will be determined on the server after the survey was submitted.

I can make it work unconditionally if I plug window.open('...', '_blank') into the click-event handler on the initial /survey page:

$('#submit').on('click', function (e) {
    e.preventDefault();
    //... other staff happens here
    window.open('http://example.com', '_blank'); // <---- this line
    $('#survey').submit();
});

It fails though, if I use window.open on the /complete page: a popup warning appears instead. Probably because it is not connected to any user-initiated event.

In my case, however, there is a user-initiated event, but it happened on a previous page. Is there any way I can pass this event to the new page (obviously new page is on the same domain name, protocol, etc). Probably there is another way?

The right way to do what you're after is to change the markup:

<form id="survey" method="post" action="/complete">
    <!-- checkboxes, etc here -->
    <button type="submit" id="submit" class="button">Submit</button>
</form>

And then in JavaScript, listen for the submit event. This will allow native features—such as implicit submission (enter key in a text field), or middle-clicking on the submit button—to work by default.

Now here're some important parts:

  • only prevent the default behavior if the input is invalid
  • if you want the form to open in a new tab, change the target attribute of the form.
$('#survey').on('submit', function (e) {
    if (!checkValidity(...)) {
        e.preventDefault();
        return;
    }

    //other stuff happens

    var newTab = shouldOpenInNewTab(...);
    $(this).attr('target', newTab ? '_blank' : '');
});

Doing that will allow the browser to use its default behaviors. It's cross-browser compatible, and it's accessible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM