1

I have found many posts that do the opposite of what I am attempting, but none for this situation. What I currently have (working):

<script type="text/javascript">
function dotask1(a, b) {
window.open('internal.website.com/' + a + '+' + b', 'awindow');
}</script>

<form onsubmit="dotask1(this.a.value, this.b.value); return false;">
<input type="text" name="a" placeholder="First Name" />
<input type="text" name="b" placeholder="Last Name" />
<input type="submit" />
</form>

<script type="text/javascript">
function dotask2(c, d) {
window.open('internal.website.com/' + c + '+' + d', 'bwindow');
}</script>

<form onsubmit="dotask2(this.c.value, this.d.value); return false;">
<input type="text" name="c" placeholder="First Name" />
<input type="text" name="d" placeholder="Last Name" />
<input type="submit" />
</form>

This allows me to enter a first and last name into each of two forms and submit. I want to have only one form and two different submit buttons that will each have a separate task. I appreciate any help.

EDIT:

Peter advises to go with onclick, which makes sense. I have the following, which will not work, any thoughts on my error(s)?

<script type="text/javascript">
function dotask1(a, b) {
window.open('internal.website.com/' + a + '+' + b', 'awindow');
}
function dotask2(c, d) {
window.open('internal.website.com/' + c + '+' + d', 'bwindow');
}
</script>

<input type="text" name="a" placeholder="First Name" />
<input type="text" name="b" placeholder="Last Name" />
<input type="button" onclick="dotask1(this.a.value, this.b.value); return false;"/> />
<input type="button" onclick="dotask2(this.a.value, this.b.value); return false;"/> />
</form>
  • 2
    Any reason you need submit and not just a button with onclick events? – Sparky Dec 31 '14 at 18:37
  • You certainly can have multiple submit buttons, no problem there. So what is your _real_ question? – arkascha Dec 31 '14 at 18:38
  • It looks like onclick is the way to go, working on that now. – Jimmy Morrison Dec 31 '14 at 18:47
  • `this` in your context (`onclick`) is referring to the input button element, there is no `this.a`. You should to give your inputs id attributes, and then do `document.getElementById('').value`. – Brett Caswell Dec 31 '14 at 19:24
  • the obvious typo in your sample post here is that you have to specify the protocal (http|https|ftp|ws|file) in the window.open uri string.. also.. you have a typo behind the `b` and `d`.. remove the trailing apostrophe.. – Brett Caswell Dec 31 '14 at 22:52
  • Thank you, I did have the http on my test end, but I did not catch that apostrophe. – Jimmy Morrison Dec 31 '14 at 23:17

3 Answers3

1

Whenever I need to do this, I avoid using input type="submit" entirely and just use buttons with onclick handlers.

<input type="button" value="Submit Task 1" onclick="function(){dotask1(a,b); return false;}"/>
<input type="button" value="Submit Task 2" onclick="function(){dotask2(c,d); return false;}"/>
elead1
  • 173
  • 1
  • 7
0

Remove the on submit from the form and attach it to the button itself.

<input type="button" onclick="dostuff();" />
<input type="button"onclick="dostuff2();"  />

Then have each one submit to the specific function you want it to.

You could also leave the submit button, but you'll have to catch and stop the default submit action as well.

Peter Jewicz
  • 664
  • 1
  • 10
  • 27
0

The following is sample code I wanted to introduce to you. The intent here is not to give you a quick solution, but to show you some underline patterns and practices for your consideration.

It is more robust/complex then is required to answer your question (or fix your issue - in regards to the button inputs)... I'm sure it will raise questions, and (again) it isn't intended to be a quick solution for you.

This code is demonstrating how you can use JSON (Javascript object notation) to construct two objects:

One uses a strategy pattern and is coupled to your form controls. Note that it uses querySelectorAll, not getElementById.

The other is an abstract json framework, composed of function-delegate handlers that you'll bind to event listeners: in a decoupling manner. You'll note in the init function of the JSON instance we put together, that these functions are assigned..

The Run method of the instance JSON, calls on the validate method, followed by the execute method.. which it doesn't (can't) account for.


Sample Code (Mix - HTML & Inline Javascript)

<html>
    <head>
        <script type="text/Javascript">
            var controlHandlers = {
                "OnExecuteFirstTask" : function(args) {
                    args = args || {"a":"", "b":"", "uri":""};
                    args.a = args.a || "";
                    args.b = args.b || "";
                    args.uri = args.uri || (args.a.length > 0 && args.b.length > 0) ? args.a + "+" + args.b : "";
                    console.log("Executing... [OnExecuteFirstTask] - EventArgs: %o", args);
                    window.open('http://internal.website.com/' + args.uri, 'awindow');
                },
                "OnExecuteSecondTask" : function(args) {
                    args = args || {"a":"", "b":"", "uri":""};
                    args.a = args.a || "";
                    args.b = args.b || "";
                    args.uri = args.uri || (args.a.length > 0 && args.b.length > 0) ? args.a + "+" + args.b : "";
                    console.log("Executing... [OnExecuteSecondTask] - EventArgs: %o", args);  
                    window.open('http://internal.website.com/' + args.uri, 'awindow');  
                },
                "OnValidateTask" : function(arr) {
                    console.log("Validating... [OnValidateTask]");
                    if (!(arr)) {return false;}
                    if (!(arr.length > 0)) { return false;}

                    var isValid = true;
                    for (var i = 0; i < arr.length; i++)
                    {
                        if (!(typeof(arr[i]["IsValid"]) == "function")) { 
                            console.log("NullException: %o - 'IsValid' Method doesn't exist", arr[i]);
                            return false;
                        }
                        if (arr[i].IsValid())
                        {
                            arr[i].ctrl.className = "valid";
                            isValid = true && isValid;
                        } else {
                            arr[i].ctrl.className = "invalid";
                            isValid = false;
                        }

                    }
                    return isValid;
                },
                "OnTextBoxFocus" : function(ev) {
                    ev = ev || {"target" : null};
                    target = ev.target || {"className" : ""};
                    target.className = "focus";
                }
            };
            var formControl = {
                "Task" : {
                    "First" : {
                        "Run" : function(ev) { 
                            var task = formControl.Task.First;
                            task.Validate = task.Validate || function (ev) {return false;};

                            if (task.Validate(formControl.elms)) 
                            {
                                task.Execute({"a": formControl.FirstNameTextBox.value, "b": formControl.LastNameTextBox.value});
                            }
                        },
                        "Execute" : null,
                        "Validate" : null
                    },
                    "Second" : {
                        "Run" : function(ev) { 
                            var task = formControl.Task.Second;
                            task.Validate = task.Validate || function (ev) {return false;};

                            if (task.Validate(formControl.elms)) 
                            {
                                task.Execute({"a": formControl.FirstNameTextBox.value, "b": formControl.LastNameTextBox.value});
                            }
                        },
                        "Execute" : null,
                        "Validate" : null
                    }
                },
                "elms" : [],
                "FirstTaskButton" : null,
                "SecondTaskButton" : null,
                "FirstNameTextBox" : null,
                "LastNameTextBox" : null,
                "init" : function() {
                    formControl.FirstTaskButton = document.querySelectorAll("input#btnFirstTask")[0];
                    formControl.SecondTaskButton = document.querySelectorAll("input#btnSecondTask")[0];
                    formControl.FirstNameTextBox = document.querySelectorAll("input#tbFirst")[0];
                    formControl.LastNameTextBox = document.querySelectorAll("input#tbLast")[0];

                    formControl.Task.First.Validate = controlHandlers.OnValidateTask;
                    formControl.Task.First.Execute = controlHandlers.OnExecuteFirstTask;
                    formControl.Task.Second.Validate = controlHandlers.OnValidateTask;
                    formControl.Task.Second.Execute = controlHandlers.OnExecuteSecondTask;  
                    formControl.FirstTaskButton.addEventListener("click", formControl.Task.First.Run);                  
                    formControl.SecondTaskButton.addEventListener("click", formControl.Task.Second.Run);                    
                    formControl.FirstNameTextBox.addEventListener("focus", controlHandlers.OnTextBoxFocus);
                    formControl.LastNameTextBox.addEventListener("focus", controlHandlers.OnTextBoxFocus);

                    formControl.elms.push( { "ctrl" : formControl.FirstNameTextBox, "IsValid" : function () { return formControl.FirstNameTextBox.value.length > 0;}});
                    formControl.elms.push( { "ctrl" : formControl.LastNameTextBox, "IsValid" : function () { return formControl.LastNameTextBox.value.length > 0;}});
                }
            };
        </script>
        <style>
            input[type="text"].valid {background-color:green;color:white;font-weight:700;text-shadow:0em 0em 0.1em black;}
            input[type="text"].invalid {background-color:red;color:white;font-weight:700;text-shadow:0em 0em 0.1em black;}

            .invalid::-webkit-input-placeholder {
                color: white;
                font-weight:700;
                text-shadow:0em 0em 0.1em black;
            }
            .invalid:-moz-placeholder {
                /* FF 4-18 */
                color: white;
                font-weight:700;
                text-shadow:0em 0em 0.1em black;
            }
            .invalid::-moz-placeholder {
                /* FF 19+ */
                color: white;
                font-weight:700;
                text-shadow:0em 0em 0.1em black;
            }
            .invalid:-ms-input-placeholder {
                /* IE 10+ */
                color: white;
                font-weight:700;
                text-shadow:0em 0em 0.1em black;
            }
        </style>
    </head>
    <body>
       <div id="msgBox" style="display:none;">Invalid Entry</div>
       <form id="mainForm" name="mainForm">
          <div>
             <label for="tbFirst">First Name:</label>
             <input type="text" id="tbFirst" name="first" placeholder="First" value="" />
          </div>
          <div>
             <label for="tbLast">Last Name:</label>
             <input type="text" id="tbLast" name="last" placeholder="Last" value="" />
          </div>
          <div>
             <input type="button" id="btnFirstTask" value="First Task" />
             <input type="button" id="btnSecondTask" value="Second Task" />
          </div>
       </form>          
       <script>
            formControl.init();
       </script>
    </body>
</html>

that's the strategy. assigning a new function to formControl.Task.First.Execute at some point after it has been initiated (formControl.init) means it will execute that function after validating..

of course, the new method assigned to the Task.First.Execute will receive the 'argument' parameter {"a": firstname, "b": lastname}.. which may or may not be useful, right?

so, a more robust argument would likely become more desirable..

in turn, you can modify/grow your 'validation bag' by working with the formControls.elms array (which may need a more suitable name then the one I gave it)..

Brett Caswell
  • 1,486
  • 1
  • 13
  • 25
  • I updated this: there was a consistent typo.. and I added the open window functionality in the OnExecuteFirstTask and OnExecuteSecondTask methods to make it fully functional to the OP scenerio – Brett Caswell Dec 31 '14 at 22:49
  • note: you should always specify a DOCTYPE (it was removed in my paste here).. also, depending on whether you can configure your web server or not, you may want to add in the proper meta headers, specifying IE compatibility mode to be **Edge** (http://stackoverflow.com/questions/4275356/ie-compatibility-mode-x-ua-compatible-tag-edge-question). – Brett Caswell Dec 31 '14 at 22:58
  • This is absolutely huge. I am adding my own elements and it appears to solve my need. I hope this helps others. Thank you! – Jimmy Morrison Dec 31 '14 at 23:20
  • I will have many questions, but I will take some time to play with this and try to learn each piece. – Jimmy Morrison Dec 31 '14 at 23:23
  • I seemed to have killed it with the third task. All looks good, but made an error somewhere: http://pastie.org/private/cdaehzsrruowgubobbn5ow – Jimmy Morrison Dec 31 '14 at 23:45
  • you need a comma here: http://pastie.org/private/cdaehzsrruowgubobbn5ow#21,71 (before the "Third" – Brett Caswell Jan 01 '15 at 00:03
  • have you worked much with Debugging in your browser? - using Developer/Debugger Tools that are integrated into every modern browser? it's usually [F12] to invoke it.. I added the console.log statements which should print to your console (browser dependent) in the developer tool/window. – Brett Caswell Jan 01 '15 at 00:06
  • excuse me.. that link was supposed to be http://pastie.org/private/cdaehzsrruowgubobbn5ow#71 (row 71).. I inadvertently clicked a row above the one I was attempting to highlight. – Brett Caswell Jan 01 '15 at 00:13
  • 1
    That did it. This is perfect. Thank you again. I do use F12 in Chrome – Jimmy Morrison Jan 01 '15 at 00:17