Search code examples
javascripthtmlforms

How can I change the target of a form from javascript?


So I am trying to change the target of a form in order to open a new window. Any kind of redirection of this form use the same window but one. The latter is a button that calls a custom javascript function that must change the target from "_self", set by default, to "_blank" that apparently does the job I'm wanting.

This is my form tag

<html:form action="<%=nomeAction%>" target="_self">
...
    <html:button styleClass="button" property="button" 
    onclick="javascript:redirectOnAnewWindow('mostraConguagli770')">
        <bean:message key="button.mostraConguagli770"/>
    </html:button>
</form>

So this is the js function

function redirectOnAnewWindow(event) {
    document.forms[0].action=document.forms[0].action+"?event="+evento;
    //document.forms[0].setAttribute("target", "_blank");
    document.forms[0].target = "_blank";
    document.forms[0].submit();
}

I've tried both the commented one and the non commented one, but none of them worked. So I'm not sure what's the problem but changing manually the target of the form, and fixing the value to "_blank" works perfectly fine, the only problem is that I need it to change the target only when that one button is pressed.

Is there any possible way to do this? Because I looked it up but couldn't find anything that solved my issue


Solution

  • I think your problem come form your html in tag, because this work well without.

    see :

    I made a jsfiddle : https://jsfiddle.net/4puxr6e3/

    html

    <form action="blabla.html" target="_self">
        <button class="button" onclick="javascript:redirectOnAnewWindow('mostraConguagli770')">
        Redirect
        </button>
    </form>
    

    javascript

    function redirectOnAnewWindow(event) {
        document.forms[0].action="blibli.html";
        document.forms[0].target = "_blank";
        document.forms[0].submit();
    }