Open a link using onsubmit

2k views Asked by At

I have the following mock snippet:

JS :

function generateLink()
{
  var A = document.getElementById('AAA').value;
  var B = document.getElementById('BBB').value;

  if(B == "1" || B == "2")
    link ='http://' + B + '.' + A + '.domain';
  else if(B == "3" || B == "4")
      link ='http://' + B + '.' + A + '.domain/link.jsp';
  else
    link ='/404.html';

  return link;
}

function showLink()
{
  var link = generateLink();

  document.getElementById("link").href = link;
  document.getElementById("link").innerHTML = link;
}

document.formName.onsubmit = function(){
    this.action = generateLink();
}

HTML :

<form name="formName" target="_blank">

<div style="margin: 0 auto; width:600px;">

  <div style="float:left;"><span>Pick AAA</span><br>
    <select id="AAA" onchange="showLink()">
      <option value="11">Eleven</option>
      <option value="12">Twelve</option>
      <option value="13">Thirteen</option>
      <option value="14">Fourteen</option>
    </select>
  </div>

  <div style="float:right;"><span>Pick BBB</span><br>
    <select id="BBB" onchange="showLink()">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
      <option value="4">Four</option>
    </select>  
  </div>

  <div style="float:left; margin-left:120px; margin-right: 40px; margin-top:70px;">
    <a href="generateLink()" id="link"></a><br><br>
    <input type="submit" value="Go to"><br><br>
    <input type="reset" value="Reset Selection">
  </div>

When I run this code what happens is that the href opens the correct url in a new tab, while the submit button opens the page I am currrently on in a new tab. I am not sure what I am doing wrong. Doesn't the document.formName.onsubmit suppose to make the submit button work the same as the href?

2

There are 2 answers

3
Aioros On BEST ANSWER

I tried to setup a fiddle with your code, and it worked well enough. But while doing it, I realized I had to move a piece of code around to avoid a small problem, so I'm going to guess that you are having the same situation. My guess is that you have all your JavaScript code before the HTML. When this part

document.formName.onsubmit = function(){
    this.action = generateLink();
}

is executed, the form does not exist yet, and the onsubmit can't be set (you should see an error about it in your console, too). When you click on your submit button later, the form has no action defined, and just goes to the same page (its default behaviour). Here's a fiddle having with this problem.

The simplest fix is moving the onsubmit assignment after the form. Here's the same fiddle, with the relevant code moved, that actually does what you expect.

0
raphael75 On

You want to set an action="" on the

<form> 

tag. When the form is submitted, it will submit to the page defined in action="". If not defined, it will submit back to the same page by default.