简体   繁体   中英

Conditional form submition

I am trying to conditionally submit one form or another. I have two forms, one main and one secondary. I want onsubmit of the main one to check if an input of the secondary has value and if yes submit the secondary.

Html code sample

<form id="form1">
    <input type="submit" />
</form>
<form id="form2">
    <input type="submit" />
</form>

I have tried having a javascript function on form1 onsubmit that will check the condition i want and will submit form2 if the condition is met. It didnt work though.

You have to stop the propagation of the event from the first submit in order for the form to not be submitted. In jQuery:

$('#form1').on('submit', function(ev) {
  ev.stopPropagation();
  // Validate
  if (validated) {
    $('#form2').submit();
  }
}

NB: Code has not been tested.

Simple example:

HTML:

<form id="form1">
    <input type="submit" onclick="checkTextField();" >
</form>
<form id="form2">
    <input type="text" id="text" value="" />
</form>

JS:

function checkTextField() {
    if (document.getElementById('text').value=="") {
        //alert("Field is empty");
        document.getElementById('form1').submit();
    }
    else{
        //alert("Field not empty");
        document.getElementById('form2').submit();
    }
}

JSFiddle:

http://jsfiddle.net/FavbL/4/

I hope I understand what you are trying to do: you want to submit form2 through form1 but only if form2's input has a value?

<form id="form1" name="form1" onsubmit="return someFunction()" action="POST">
    <input type="submit" value="Submit">
</form>

<form id="form2" name="form2" action="POST">
    Some random value: <input type="text" name="something" value="">
</form>

<script>
    function someFunction() {

        // is the value blank? then don't do a thing. Otherwise submit
        if (document.forms["form2"]["something"].value != ''){
            document.forms["form2"].submit();
        }

        // always return false because we never want to submit form1...
        return false;
    }
</script>

Having written that, I would much rather use JQuery.

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