Rectangle 27 20

You could give the form and the link some ids and then subscribe for the onclick event of the link and submit the form:

<form id="myform" action="" method="POST">
    <a href="#" id="mylink"> submit </a>
</form>

and then:

window.onload = function() {
    document.getElementById('mylink').onclick = function() {
        document.getElementById('myform').submit();
        return false;
    };
};

I would recommend you using a submit button for submitting forms as it respects the markup semantics and it will work even for users with javascript disabled.

html - How to submit a form with JavaScript by clicking a link? - Stac...

javascript html forms hyperlink
Rectangle 27 1050

You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here: W3C HTML5 Button

<button type="button">Button</button>

in order to override the default submit type. I just want to point out the reason why this happens =)

saved me a big deal in a similar situation, thx a lot for the solution

This should be the selected answer as there is no javascript involved. If you want your form to work when js is disabled, this is what you need.

Cough cough.... this is the answer.

javascript - How to prevent buttons from submitting forms - Stack Over...

javascript html forms button submit
Rectangle 27 1017

You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here: W3C HTML5 Button

<button type="button">Button</button>

in order to override the default submit type. I just want to point out the reason why this happens =)

saved me a big deal in a similar situation, thx a lot for the solution

This should be the selected answer as there is no javascript involved. If you want your form to work when js is disabled, this is what you need.

Cough cough.... this is the answer.

javascript - How to prevent buttons from submitting forms - Stack Over...

javascript html forms button submit
Rectangle 27 1003

You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here: W3C HTML5 Button

<button type="button">Button</button>

in order to override the default submit type. I just want to point out the reason why this happens =)

saved me a big deal in a similar situation, thx a lot for the solution

This should be the selected answer as there is no javascript involved. If you want your form to work when js is disabled, this is what you need.

Cough cough.... this is the answer.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - How to prevent buttons from submitting forms - Stack Over...

javascript html forms button submit
Rectangle 27 1003

You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here: W3C HTML5 Button

<button type="button">Button</button>

in order to override the default submit type. I just want to point out the reason why this happens =)

saved me a big deal in a similar situation, thx a lot for the solution

This should be the selected answer as there is no javascript involved. If you want your form to work when js is disabled, this is what you need.

Cough cough.... this is the answer.

javascript - How to prevent buttons from submitting forms - Stack Over...

javascript html forms button submit
Rectangle 27 996

You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here: W3C HTML5 Button

<button type="button">Button</button>

in order to override the default submit type. I just want to point out the reason why this happens =)

saved me a big deal in a similar situation, thx a lot for the solution

This should be the selected answer as there is no javascript involved. If you want your form to work when js is disabled, this is what you need.

Cough cough.... this is the answer.

javascript - How to prevent buttons from submitting forms - Stack Over...

javascript html forms button submit
Rectangle 27 20

You can not submit a form using an <a> tag alone. You will need some type of javascript to assist, if you insist on using the <a> tag:

<a href="#" onclick="$(this).closest('form').submit()">Submit the Form</a>
<a href="#" onclick="document.getElementById('form-id').submit()">Submit the Form</a>

<a href="backendPage.php?param1=yes&param2=no">Submit the Form</a>, then on backendPage.php you can use $_GET requests to process information, and redirect the visitor to the intended page. But that's a horrible idea haha

Hay hello man, I used this method and it worked fine, but didnt work when I changed href value to empty string (href=" ") can you tell me what is the significance of the #....

Hi @fazkan, thehref="#whatever" tells the browser to change the hash in the URL, which usually means no page reload (excluding angular, etc.). An empty href attribute will be the same as pointing to the current page which will reload the page. Alternatively, you could remove the href attribute completely and use CSS cursor:pointer to make the mouse hover look like a link.

html - Submit a form using anchor element, without javascript - St...

html forms
Rectangle 27 20

You can not submit a form using an <a> tag alone. You will need some type of javascript to assist, if you insist on using the <a> tag:

<a href="#" onclick="$(this).closest('form').submit()">Submit the Form</a>
<a href="#" onclick="document.getElementById('form-id').submit()">Submit the Form</a>

<a href="backendPage.php?param1=yes&param2=no">Submit the Form</a>, then on backendPage.php you can use $_GET requests to process information, and redirect the visitor to the intended page. But that's a horrible idea haha

Hay hello man, I used this method and it worked fine, but didnt work when I changed href value to empty string (href=" ") can you tell me what is the significance of the #....

Hi @fazkan, thehref="#whatever" tells the browser to change the hash in the URL, which usually means no page reload (excluding angular, etc.). An empty href attribute will be the same as pointing to the current page which will reload the page. Alternatively, you could remove the href attribute completely and use CSS cursor:pointer to make the mouse hover look like a link.

html - Submit a form using anchor element, without javascript - St...

html forms
Rectangle 27 58

By using return false; in the javascript that you call from the submit button, you can stop the form from submitting.

Basically, you need the following HTML:

<form onsubmit="myFunction(); return false;">
<input type="submit" value="Submit">
</form>
<script language="javascript"><!--
function myFunction() {
    //do stuff
}
//--></script>

If you desire, you can also have certain conditions allow the script to submit the form:

<form onSubmit="return myFunction();">
<input type="submit" value="Submit">
</form>
<script language="JavaScript"><!--
function myFunction() {
    //do stuff
    if (condition)
        return true;

    return false;    
}
//--></script>
function
function myFunction() { }

javascript - Want html form submit to do nothing - Stack Overflow

javascript html ajax forms submit
Rectangle 27 16

Sure you can use the submit() method to submit a form like this:

<a href="#" onclick="document.getElementById('formID').submit()">Submit Form</a>

To go unobstrusive, you can do this instead:

You can give your link an id:

<a href="#" id="link">Submit Form</a>
<script type="text/javascript">
  var link = document.getElementById('link');

  link.onclick = function(){
    document.getElementById('formID').submit();
    return false;
  };
</script>

where formID is the id of the form.

html - Submit Form Via JavaScript - Stack Overflow

javascript html
Rectangle 27 17

The jQuery submit() event adds an event listener to happen when you submit the form. So your code is binding essentially nothing to the submit event. If you want that form to be submitted, you use old-school JavaScript (document.formName.submit()).

I'm leaving my original answer intact to point out where I was off (as at least two people have already downvoted me for). What I MEANT to say, is that if you have a function like this, it's confusing why you would post the values in an ajax portion and then use jQuery to submit the form. In this case, I would bind the event to the click of the button, and then return true if you want it to return, otherwise, return false, like so

$('#submit').click( function() {
  // ajax logic to test for what you want
  if (ajaxtrue) { return confirm(whatever); } else { return true;}
});

If this function returns true, then it counts as successful click of the submit button and the normal browser behavior happens. Then you've also separated the logic from the markup in the form of an event handler.

Thats if you pass a function. If you just call submit(), the default submit action on the form will be fired, so the form will be submitted.

I've updated the answer to explain what I meant. I was not being very clear, that was my bad.

i need to get ajax data because depending on the form, the confirmation will be different (if you want specifics, i am checking to see if the file a user is uploading is already in the database, and if so, notifying that the old file will be overwritten). although it kills me to say it, your answer is better than mine, as it is more semantic and does not require an invisible submit button. i'm marking this as the correct answer, but i'm still confused as to why the submit() function didn't work =(

To be honest I think your problem is that the event that's firing it is the click of the submit button, and you're telling jQuery to perform a submit() within that function. All you really have to do is return true, and the onclick goes through.

jQuery: form not submitting with $("#id").submit(), but will submit wi...

jquery forms form-submit
Rectangle 27 56

It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.

Anyhow, with that in mind, this should do it:

<form id='myform' action='jquery.php' method='GET'>
    <input type='submit' id='btn1' value='Normal Submit'>
    <input type='button' id='btn2' value='New Window'>
</form>
var form = document.getElementById('myform');
form.onsubmit = function() {
    form.target = '_self';
};

document.getElementById('btn2').onclick = function() {
    form.target = '_blank';
    form.submit();
}

Approaches that bind code to the submit button's click event will not work on IE.

<input type="submit" formaction="action2.php" value="Other Action"></input>

javascript - HTML form with two submit buttons and two "target" attrib...

javascript html forms submit
Rectangle 27 56

It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.

Anyhow, with that in mind, this should do it:

<form id='myform' action='jquery.php' method='GET'>
    <input type='submit' id='btn1' value='Normal Submit'>
    <input type='button' id='btn2' value='New Window'>
</form>
var form = document.getElementById('myform');
form.onsubmit = function() {
    form.target = '_self';
};

document.getElementById('btn2').onclick = function() {
    form.target = '_blank';
    form.submit();
}

Approaches that bind code to the submit button's click event will not work on IE.

<input type="submit" formaction="action2.php" value="Other Action"></input>

javascript - HTML form with two submit buttons and two "target" attrib...

javascript html forms submit
Rectangle 27 7

With javascript (here jQuery), you can disable the prev button before submit the form.

$('form').on('keypress', function(event) {
    if (event.which == 13) {
        $('input[name="prev"]').prop('type', 'button');
    }
});

Multiple submit buttons in an HTML form - Stack Overflow

html form-submit html-form submit-button
Rectangle 27 7

With javascript (here jQuery), you can disable the prev button before submit the form.

$('form').on('keypress', function(event) {
    if (event.which == 13) {
        $('input[name="prev"]').prop('type', 'button');
    }
});

Multiple submit buttons in an HTML form - Stack Overflow

html form-submit html-form submit-button
Rectangle 27 27

Use the submit button type.

<input type="submit".../>

..instead of

<input type="button".../>

Your problem doesn't really have anything to do with having used an onclick attribute. Instead, you're not getting the behavior you want because you've used the button input type, which simply doesn't behave the same way that submit buttons do.

In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type "submit". In most browsers, "submit" buttons fire by default when ENTER is pressed from a focused element in the same form element. The "button" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to "submit".

<form action="/post.php" method="post">
    <!-- 
    ...
    -->
    <input type="submit" value="go"/>
</form>

@Ady mentioned a security concern. There are a whole bucket of security concerns associated with doing a login in javascript. These are probably outside of the domain of this question, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place).

Instead of drudging that up, here are links to related topics on SO, if anyone is interested in those questions directly.

Here's a quick cleanup of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to illustrate some healthy habits. If you have specific questions about why I've written something a certain way, feel free to ask. Also, browse the stack for related topics (as your question may have already been discussed here).

The main thing to notice is the removal of the event attributes (onclick="", onsubmit="", or onkeypress="") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup.

<form action="#" method="post" id="loginwindow">
    <h3>Login to view!</h3>
    <label>User ID: <input type="text" id="userid"></label>
    <label>Password: <input type="password" id="pass"></label>
    <input type="submit" value="Check In" />
</form>

<script type="text/javascript">
window.onload = function () {
    var loginForm = document.getElementById('loginwindow');
    if ( loginwindow ) {
        loginwindow.onsubmit = function () {

            var userid = document.getElementById('userid');
            var pass = document.getElementById('pass');

            // Make sure javascript found the nodes:
            if (!userid || !pass ) {
                return false;
            }

            // Actually check values, however you'd like this to be done:
            if (pass.value !== "secret")  {
                location.href = 'failure.html';
            }

            location.href = 'album.html';
            return false;
        };
    }
};
</script>

this looks pretty darn good. couple quick questions: 1. where in this code do i set the username and password? 2. would it help with security if i were to put the javascript in an external file and link to it? thank you so much for your thorough answer!

3. (haha sorry for being annoying. i really appreciate your help!) it seems as though using your code, it doesn't matter what i enter for the username and password, it just redirects to album.html. how can i fix that?

Re: 1 & 3, I've modified the example code above to make it a bit more obvious of what's going on.. See if it helps.

Re: 2 Putting the js in an external file won't help. The secure way is to allow the form to submit the values to the server over https, and control the login on the server. It's a bit much to explain entirely as an aside to this question, but I can recommend some resources or open a new question..

Javascript login form doesn't submit when user hits Enter - Stack Over...

javascript forms button submit html-input
Rectangle 27 27

Use the submit button type.

<input type="submit".../>

..instead of

<input type="button".../>

Your problem doesn't really have anything to do with having used an onclick attribute. Instead, you're not getting the behavior you want because you've used the button input type, which simply doesn't behave the same way that submit buttons do.

In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type "submit". In most browsers, "submit" buttons fire by default when ENTER is pressed from a focused element in the same form element. The "button" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to "submit".

<form action="/post.php" method="post">
    <!-- 
    ...
    -->
    <input type="submit" value="go"/>
</form>

@Ady mentioned a security concern. There are a whole bucket of security concerns associated with doing a login in javascript. These are probably outside of the domain of this question, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place).

Instead of drudging that up, here are links to related topics on SO, if anyone is interested in those questions directly.

Here's a quick cleanup of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to illustrate some healthy habits. If you have specific questions about why I've written something a certain way, feel free to ask. Also, browse the stack for related topics (as your question may have already been discussed here).

The main thing to notice is the removal of the event attributes (onclick="", onsubmit="", or onkeypress="") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup.

<form action="#" method="post" id="loginwindow">
    <h3>Login to view!</h3>
    <label>User ID: <input type="text" id="userid"></label>
    <label>Password: <input type="password" id="pass"></label>
    <input type="submit" value="Check In" />
</form>

<script type="text/javascript">
window.onload = function () {
    var loginForm = document.getElementById('loginwindow');
    if ( loginwindow ) {
        loginwindow.onsubmit = function () {

            var userid = document.getElementById('userid');
            var pass = document.getElementById('pass');

            // Make sure javascript found the nodes:
            if (!userid || !pass ) {
                return false;
            }

            // Actually check values, however you'd like this to be done:
            if (pass.value !== "secret")  {
                location.href = 'failure.html';
            }

            location.href = 'album.html';
            return false;
        };
    }
};
</script>

this looks pretty darn good. couple quick questions: 1. where in this code do i set the username and password? 2. would it help with security if i were to put the javascript in an external file and link to it? thank you so much for your thorough answer!

3. (haha sorry for being annoying. i really appreciate your help!) it seems as though using your code, it doesn't matter what i enter for the username and password, it just redirects to album.html. how can i fix that?

Re: 1 & 3, I've modified the example code above to make it a bit more obvious of what's going on.. See if it helps.

Re: 2 Putting the js in an external file won't help. The secure way is to allow the form to submit the values to the server over https, and control the login on the server. It's a bit much to explain entirely as an aside to this question, but I can recommend some resources or open a new question..

Javascript login form doesn't submit when user hits Enter - Stack Over...

javascript forms button submit html-input
Rectangle 27 114

If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");

// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");

var hiddenField = document.createElement("input");              
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);

// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');

form.submit();

+1 Better than the accepted answer, since it actually puts the result in the popup with the options the OP wanted.

Answered exactly what was asked. Thanks!

@mjaggard: What did you add? It might be worth suggesting an edit to this answer.

@SaurabhNanda As far as I can tell, target attribute on form element is not deprecated in HTML 4.01 Transitional and apparently is to stay in HTML 5.

A warning: I had to attach my form to the document body before this would work (in FF 17). Creating a fragment and trying to sumbit it didn't work.

html - Javascript Post on Form Submit open a new window - Stack Overfl...

javascript html post
Rectangle 27 59

The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.

However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, Im afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:

function submitform() {
  var f = document.getElementsByTagName('form')[0];
  if(f.checkValidity()) {
    f.submit();
  } else {
    alert(document.getElementById('example').validationMessage);
  }
}

can we use two buttons in a single form it shows error required fields alerts for both buttons why? how to solve?

@HTMLDeveloper, you should present your problem, with code, as a new question (and formulate it in more detail I really cant see what you are asking here).

html - HTML5 validation when the input type is not "submit" - Stack Ov...

html html5 forms validation html5-validation
Rectangle 27 42

cancel is not a valid value for a type attribute, so the button is probably defaulting to submit and continuing to submit the form. You probably mean type="button".

(The javascript: should be removed though, while it doesn't do any harm, it is an entirely useless label)

You don't have any button-like functionality though, so would be better off with:

<a href="http://stackoverflow.com"> Cancel </a>

javascript - How to create a HTML Cancel button that redirects to a UR...

javascript html html-form htmlbutton