Is it valid html to have the following:
<form action="a">
<input.../>
<form action="b">
<input.../>
<input.../>
<input.../>
</form>
<input.../>
</form>
So when you submit "b" you only get the fields within the inner form. When you submit "a" you get all fields minus those within "b".
If it isn't possible, what workarounds for this situation are available?
A. It is not valid HTML nor XHTML
In the official W3C XHTML specification, Section B. "Element Prohibitions", states that:
"form must not contain other form elements."
http://www.w3.org/TR/xhtml1/#prohibitions
As for the older HTML 3.2 spec,
the section on the FORMS element states that:
"Every form must be enclosed within a
FORM element. There can be several
forms in a single document, but the
FORM element can't be nested."
B. The Workaround
There are workarounds using JavaScript without needing to nest form tags.
"How to create a nested form." (despite title this is not nested form tags, but a JavaScript workaround).
Answers to this StackOverflow question
Note: Although one can trick the W3C Validators to pass a page by manipulating the DOM via scripting, it's still not legal HTML. The problem with using such approaches is that the behavior of your code is now not guaranteed across browsers. (since it's not standard)
In case someone find this post here is a great solution without the need of JS. Use two submit buttons with different name attributes check in your server language which submit button was pressed cause only one of them will be sent to the server.
<form method="post" action="ServerFileToExecute.php">
<input type="submit" name="save" value="Click here to save" />
<input type="submit" name="delete" value="Click here to delete" />
</form>
The server side could look something like this if you use php:
<?php
if(isset($_POST['save']))
echo "Stored!";
else if(isset($_POST['delete']))
echo "Deleted!";
else
echo "Action is missing!";
?>
HTML 4.x & HTML5 disallow nested forms, but HTML5 allows a workaround with the "form" attribute ("form owner").
As for HTML 4.x you can:
Use an extra form(s) with only hidden fields & JavaScript to set its input's and submit the form.
Use CSS to line up several HTML form to look like a single entity - but it might be complicated to do.
As others have said, it is not valid HTML.
It sounds like your are doing this to position the forms visually within each other. If that is the case, just do two separate forms and use CSS to position them.
No, the HTML specification states that no FORM element should contain another FORM element.
A possibility is to have an iframe inside the outer form. The iframe contains the inner form. Make sure to use the <base target="_parent" /> tag inside the head tag of the iframe to make the form behave as part of the main page.
You can answer your own question very easily by inputting the HTML code into the W3 Validator. (It features a text input field, you won't even have to put your code on a server...)
(And no, it won't validate.)
rather use a custom javascript-method inside the action attribute of the form!
eg
<html>
<head>
<script language="javascript" type="text/javascript">
var input1 = null;
var input2 = null;
function InitInputs() {
if (input1 == null) {
input1 = document.getElementById("input1");
}
if (input2 == null) {
input2 = document.getElementById("input2");
}
if (input1 == null) {
alert("input1 missing");
}
if (input2 == null) {
alert("input2 missing");
}
}
function myMethod1() {
InitInputs();
alert(input1.value + " " + input2.value);
}
function myMethod2() {
InitInputs();
alert(input1.value);
}
</script>
</head>
<body>
<form action="javascript:myMethod1();">
<input id="input1" type="text" />
<input id="input2" type="text" />
<input type="button" onclick="myMethod2()" value="myMethod2"/>
<input type="submit" value="myMethod1" />
</form>
</body>
</html>
As workaround you could use formaction attribute on submit button. And just use different names on your inputs.
<form action="a">
<input.../>
<!-- Form 2 inputs -->
<input.../>
<input.../>
<input.../>
<input type="submit" formaction="b">
</form>
<input.../>
no,
see w3c
No, it is not valid. But a "solution" can be creating a modal window outside of form "a" containing the form "b".
<div id="myModalFormB" class="modal">
<form action="b">
<input.../>
<input.../>
<input.../>
<button type="submit">Save</button>
</form>
</div>
<form action="a">
<input.../>
Open modal b
<input.../>
</form>
It can be easily done if you are using bootstrap or materialize css.
I'm doing this to avoid using iframe.
Fast Solution:
To obtain different validations to different forms and keep their submits in separated functions you can do this:
<form id="form1" onsubmit="alert('form1')"></form>
<form id="form2" onsubmit="alert('form2')"></form>
<div>
<input form="form1" required />
<input form="form1" required />
<div>
<input form="form2" required />
<input form="form2" required />
<button form="form2" type="submit">Send form2</button>
</div>
<input form="form1" required />
<button form="form1" type="submit">Send form1</button>
</div>
A non-JavaScript workaround for nesting form tags:
Because you allow for
all fields minus those within "b".
when submitting "a", the following would work, using regular web-forms without fancy JavaScript tricks:
Step 1. Put each form on its own web page.
Step 2. Insert an iframe wherever you want this sub-form to appear.
Step 3. Profit.
I tried to use a code-playground website to show a demo, but many of them prohibit embedding their websites in iframes, even within their own domain.
You are trying to implement nested form which is not supported in HTML.
Every form must be enclosed within a FORM element. There can be
several forms in a single document, but the FORM element can't be
nested.
Workaround
You can implement this functionality with some change in HTML and JavaScript. (without using html forms)
Steps
1. Create both forms with div tag as follows (do not use form tag)
<div id="form_a">
<input.../>
<div id="form_b">
<input.../>
<input.../>
<button id="submit_b">Submit B</button>
</div>
<input.../>
<button id="submit_a">Submit A</button>
</div >
2. Add JQuery and Ajax to submit each form data
<script>
// Submit form A data
$('#submit_a').click( function() {
$.ajax({
url: 'ajax-url',
type: 'post',
dataType: 'json',
data: $('#form_a input').not( "#form_b input" ).serialize(),
success: function(data) {
// ... do something with the data...
}
});
});
// Submit form B data
$('#submit_b').click( function() {
$.ajax({
url: 'ajax-url',
type: 'post',
dataType: 'json',
data: $('#form_b input').serialize(),
success: function(data) {
// ... do something with the data...
}
});
});
</script>
If you need your form to submit/commit data to a 1:M relational database, I would recommend creating an "after insert" DB trigger on table A that will insert the necessary data for table B.
Related
Nested Forms Acceptable?
I can't find anything in the HTML5 doc that talks about nested forms. I'm sure it's listed on some page, somewhere (perhaps a changelog), but if not, should I assume that no-mention is the same as acceptable?
Additionally, the HTML4 doc doesn't mention it. Perhaps it's been permitted all along and I was adhering to old standards.
Previous Mentions
XHTML1.0
form must not contain other form elements.
HTML 3.0
There can be several forms in a single document, but the FORM element can't be nested.
The HTML5 document does mention it in the section you link above:
Content model
Flow content, but with no form element descendants.
"Content model" means "what this element may contain". So no, nested forms are not allowed.
If they were supported then something like this would work:
$('button').on('click', function(e) {
var form = $(this).parents('form');
e.preventDefault();
if(!form) {
form = $(this);
}
$('#output').val('from '+form.attr('id')+'\n'+form.serialize());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='parent'>
<form id='childA'>
<input type='text' placeholder='value of A'/>
<button>Send part A</button>
</form>
<form id='childB'>
<input type='text' placeholder='value of B'/>
<button>Send part B</button>
</form>
<button>Send All</button>
</form>
<br/>
<textarea id='output'></textarea>
However because it is not officially supported you can look see the browser is preventing it (closing what it assumes are open-ended form elements). One alternative would be to have a single form but add data attributes to the individual inputs so JavaScript can collect the sub fields you want and manually build a POST from them.
I'm trying to combine the login and register forms on a WooCommerce/WordPress site. The idea is that a single set of fields, username and password, could be submitted by two different forms. The first way I thought of is (simplified for clarity):
<form id="login">
<input id="username">
<input id="password">
<button type="submit">LOG IN</button>
</form>
<form id="register">
<div style="visibility:hidden!important;position:fixed!important;">
<input id="register_username">
<input id="register_password">
</div>
<button type="submit">REGISTER</button>
</form>
Basically, the layout hides the second pair of inputs but shows both buttons. Then, there's some JS that mirrors the values of corresponding fields:
var u = $('#username');
var p = $('#password');
var ru = $('#register_username');
var rp = $('#register_password')
$('#login').on('change blur focus click keyup',function(){
ru.val(u.val());
rp.val(p.val());
});
This seems to trigger a warning that an "invalid field is not focusable" - which I understand - but, can this be solved and done well? Is there a way to do this without JavaScript? Is there a better way altogether?
Let's assume I will show the hidden stuff in the case that there is no JS on the user's browser. Let's also assume I was given this design and asked to implement it, i.e. this is not a question about UX.
Just merge 2 forms into one and set 2 buttons
<form id="login">
<input id="username">
<input id="password">
<button name="submit" type="submit" value="login">LOG IN</button>
<button name="submit" type="submit" value="registration">REGISTER</button>
</form>
After submitting your form you need to check submit value like
if($_POST['submit'] == 'login')
then do code for login
else if($_POST['submit'] == 'registration')
then do code for registration
To reveal the hidden fields in the case of no javascript you would put the data between the following tags:
As far as the fields that are active when there is JavaScript, place that data within the JavaScript itself using document.write("fields here");.
The end result will be that these fields appear when JavaScript is enabled, and do not appear when JavaScript is disabled.
Hope this helps.
For example, the website https://talky.io/ has a form on its homepage. When you enter text into the form and hit the button, you're taken to a page that's https://talky.io/[your text]. How do you do this? What's the best way to do it?
Thank you!
You can use onSubmit and change the action attribute of the form via javascript, then return true. The code could look like this:
HTML from linked page:
<form id="createRoom">
<input id="sessionInput" placeholder="Name the conversation" autofocus="autofocus">
<button type="submit">Let’s go!</button>
</form>
Js code:
document.getElementById("crateRoom").onsubmit = function(){
var url = encodeURIComponent(document.getElementById("sessionInput").value);
document.getElementById("crateRoom").action = "/" + url;
return true;
}
It is server-side script job. You can look at some MVC framework and the url parameters
You can use GET method of form;for example:
<form action="index.php" method="get">
Page: <input type="text" name="page">
<input type="submit" value="Submit">
</form>
that after submit will go to index.php?page=yourEnteredPage.
You can use PHP symfony or codeignitor, if you use .net then create a new MVC project.
But if you only need to change urls like
www.mysite.com/mypage.php?something=value
to
www.mysite.com/value
You can do a mod rewrite in apache or if you're using .net then use RegisterRoutes in your global.asax.cs
Using a form you can submit data to a location/url that was given in the action attribute of the for, for example
<form method="POST" action="http://example.com">
<input name="first_name" type="text" value="" />
<!-- Form elements -->
<input type="submit" name="mySubmitButton" value="Submit">
</form>
This form will submit the form data to the given action url when submit will be pressed and on the derver data could be retrieve using
$first_name = $_POST['first_name';];
and so on. The method POST is used to submit the form in the post array so you can retrieve data using $_POST['formfieldname'] and if you use method="GET" then you can get submitted data from $_GET variable, like, $fname=$_GET['first_name']. GET has limitation of amount when submitting data (safe to use up to 2000 characters IE's limit) and is visible to address bar of the browser and not being used for login (password) and POST can send more data than GET and also not visible to address bar.
You may read this.
Fairly possible with URL Rewriting
http://en.wikipedia.org/wiki/Rewrite_engine
How do I access hidden fields in angular? I have an app, where I want to submit a form for each of items in the list. The form is simple - it has submit button and a hidden field holding the ID value. But it does not work. The value is empty.
I updated the default angular example to display the situation - the todo text is in hidden field.
http://jsfiddle.net/tomasfejfar/yFrze/
If you don't want to hardcode anything in your javascript file, you can either load it via AJAX, or do:
<input type="hidden" name="value" ng-init="model.value=1" value="1">
this way, you can keep the form functionality with JS off, and still use the hidden field in AngularJS
If you want to pass the ID from the ng-repeat to your code, you don't have to use a hidden field. Here's what I did:
For example, let's say I'm looping through a collection of movies, and when you click the "read more" link it will pass your ID to your JS code:
<ul>
<li ng-repeat="movie in movies">
{{movie.id}} {{movie.title}} read more
</li>
</ul>
Then in your JS code, you can get the ID like this:
$scope.movieDetails = function (movie) {
var movieID = movie.id;
}
In your simpler fiddle, the problem can be fixed by using ng-init or setting an initial value in the controller. The value attribute won't effect the ng-model.
http://jsfiddle.net/andytjoslin/DkMyP/2/
Also, your initial example (http://jsfiddle.net/tomasfejfar/yFrze/) works for me in its current state on Chrome 15/Windows 7.
You can do something like this.
It is a dirty trick, but it works (like most dirty tricks ;-)
You just use the form name as Your hidden field
and always give the form the id "form"
<!doctype html><html ng-app><head>
<script src="angular-1.0.1.min.js"></script>
<script>
function FormController($scope) {
$scope.processForm = function() {alert("processForm() called.");
$scope.formData.bar = "";
try {$scope.formData.bar = document.getElementById("form").name;}
catch(e) {alert(e.message);}
alert("foo="+$scope.formData.foo+ " bar="+$scope.formData.bar);
};
}
</script></head><body>
<div ng-controller="FormController">
<form name="YourHiddenValueHere" id="form">
<input type="text" ng-model="formData.foo" />
<button ng-click="processForm()"> SUBMIT </button>
</form>
</div></body></html>
This allows You to use ONE Controller for ALL forms and send
them to ONE server script.
The script than distinguishes by the
form name (formData.foo) and knows what to do.
The hidden field names the operation in this scenario.
Voila - You have a complete application with as
many forms You want and one server script
and one FormController for all of them.
Simpler:
<input type="hidden" name="livraisonID" value="{{livraison.id}}"/>
It works!
Use ng-binding="{{employee.data}}". It will work properly.
I have to correct (improve) myself:
You can do it more elegantly:
<form>
<input type="text" ng-model="formData.foo" />
<input type="hidden" id="bar" value="YourHiddenValue" />
<button ng-click="processForm()"> SUBMIT </button>
</form>
and then in the JavaScript controller:
$scope.formData.bar = "";
try {$scope.formData.bar = document.getElementById("bar").value;}
catch(e) {alert(e.message);}
alert("foo="+$scope.formData.foo+ " bar="+$scope.formData.bar);
So you can have as many hidden fields as you like.
I'm a newbie to scripting. I want to update HTML content with JavaScript, but as you can see
the web page keeps refreshing.
How can I prevent the page from refreshing?
Javascript:
function showResult(form) {
var coba=form.willbeshown.value;
var coba2=coba+2;
document.getElementById("showresulthere").innerHTML=coba2;
}
HTML
<form>
<input type="text" name="willbeshown" value="">
<button onclick="showResult(this.form)">Ganti1</button>
</form>
<p id="showresulthere">Result will be shown here</p>
</body>
Don’t use a form at all. You are not submitting any form data to a server. To process data in the browser, you don’t need a form. Using a form just complicates things (though such issues could be fixed by using type=button in the button element, to prevent it from acting as a submit button).
<input type="text" id="willbeshown" value="">
<button onclick=
"showResult(document.getElementById('willbeshown'))">Ganti1</button>
<p id="showresulthere">Result will be shown here</p>
<script>
function showResult(elem) {
document.getElementById("showresulthere").innerHTML = Number(elem.value) + 2;
}
</script>
I have used conversion to numeric, Number(), as I suppose you want to add 2 to the field value numerically, e.g. 42 + 2 making 44 and not as a string, 42 + 2 making 422 (which is what happens by default if you just use an input element’s value and add something to it.
Your button should be
<button onclick="showResult(this.form); return false;">Ganti1</button>
Javascript
function showResult(form) {
var coba=form.willbeshown.value;
var coba2=coba+2;
document.getElementById("showresulthere").innerHTML=coba2;
return false; // prevent form submission with page load
}
DEMO
The others will explain how you should use jQuery, but this would explain why it didn't work in your original code.
The <button> tag submits the form, so you have to add this inside your form tag to prevent form submission:
<form onsubmit="return false">
Btw, even without giving your form an explicit action, it uses the current page to submit; it's easy to think that it will not do anything without an action.
If you define a <button /> without defining its type it will work like a submit button. Just add type="button" to your button markup and the form won't be submitted.
<button type="button" onclick="showResult(this.form)">Ganti1</button>
With this change you won't need any return false or .preventDefault() "workarounds"