Here is the scenario, I have 3 html forms on a page and they look like
form1() form2(form3())
a dummy program to test out the 3 forms
__
<script language="javascript" type="text/javascript">
function submitthisform(no){
document.forms[no].submit;
}
</script>
<form action="http://cnn.com" name="1">
<input type=submit value="cnn" onclick="submitthisform('1')" name='submit1'>
</form>
<form action="http://google.com" name="2">
<form action="http://yahoo.com" name="3">
<input type=submit value="yahoo" onclick="submitthisform('3')" name="submit3">
</form>
<input type=submit value="google" onclick="submitthisform('2')" name="submit2">
</form>
now when i do submit3, the onclick function gets called, where I try to submit the form3 because otherwise it always submits the form 2
in onclick, I send the form name. But form3 seems to be inaccessible. Reason is, if i traverse all the forms on the page, it doesnt return form 3 but only form 1 & 2
var forms = document.getElementsByTagName("form");
for (var i=0; i<forms.length; i++){
alert('form'+i+' = '+forms[i].name);// displays name of form1&2
}
it also gives javascript err on click submit2.
try this small code and u will get the idea.
tell me if i can submit form 3!!!!
According to XHTML specs
form must not contain other form elements.
So please do not do this as you can not guarantee compatibility across browsers (current or future)
My solution: deactivate the parent form by moving all children into a new div. In fact, I change the form element´s type to div.
Here my code snippet tyken from a Vue.js method:
let target = document.createElement('div');
let source = document.getElementById(this.parentFormId); // change this!
source.parentNode.insertBefore(target,source);
source.childNodes.forEach(node => {
node.parentNode.removeChild(node);
target.appendChild(node);});
source.parentNode.removeChild(source);
target.id = this.parentFormId;
The nested form markup ist pasted in dynamically via computed property to avoid conflicts. Optionally, if the outer form needs to be restored, the form-attributes can by copied too. For my purpose, this is not necessary.
Maybe a hack, but it works well!
Related
https://codepen.io/anon/pen/NYaeXV
I am trying to log the value of a HTML form input. I put multiple options inside the CodePen. Here is my initial thought process.
<form action="">
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
function sConsole() {
var data = document.getElementById("data");
console.log(data.value());
}
sConsole();
You need to use value instead of value() since value is not a function , also consider using e.preventDefault() to avoid the page reload one more thing , by adding sConsole() into your js file you're asking the function to be executed when the page load, you need to move your function to the submit event instead.
Here is a working example and Happy coding :)
function sConsole(event) {
event.preventDefault();
var data = document.getElementById("data");
console.log(data.value);
}
<div id="container">
<h1>Hello, world!</h1>
<h4>Input your console data below : </h4>
<form action="" id="form" onsubmit="sConsole(event)">
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
</div>
You missed onclick or onSubmit , you should also use .value
function sConsole() {
var data = document.getElementById("data");
console.log(data.value);
//!!Option 1a
//console.log(data.submit());
}
<div id="container">
<h1>Hello, world!</h1>
<h4>Input your console data below : </h4>
<form action="">
<input type="text" name="data" id="data">
<button type="submit" onClick="sConsole()">Submit</button>
</form>
</div>
You were close, just a few things to consider.
Getting the value of an input field
The value attribute of an input element stores the text in the textbox. To retrieve, this in javascript, use ExampleElement.value, for example:
var dataValue = document.getElementById("data").value;
or
var data = document.getElementById("data");
var dataValue = data.value;
You can also specify the value attribute in the input tag with value="". This is useful if you want to prefill the input text box, for instance, if you send the user input to a php script for action and wanted to return the textbox with information already included.
Calling a Javascript Function
There are multiple ways to call a javascript function, including doing so when certain events occur. In your situation, you probably want the input value logged every time the user clicks submit. You could add an event listener, but for simplicity sake of understanding, let's just use inline code. Every time they submit, let's log it, so onsubmit="sConsole();". Now the submit action will run your logging function.
If you wanted to log every change while the user was typing, you would use an event listener with more complex evaluation of the input value.
Prevent Default
It's likely that you don't want the form to actually be submitted to the server and page reloaded every time the user clicks submit. By using event.preventDefault();, javascript prevents the usual action of submitting the form to the server and instead leaves the user input and the page as is.
If you want the textbox to be "erases" after each submit, it's probably best to reset the value in your function rather than submitting the form. To reset the value, you would simply do data.value = "".
Code Example
Putting it all together, here's an example code segment with comments about your original sample.
<form action="" onsubmit="event.preventDefault(); sConsole();"> <!-- use inline JS to print input to console on submit -->
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
<script>
function sConsole() {
var data = document.getElementById("data");
console.log(data.value); // data is the element, and we want its value
}
//sConsole(); This would call it only on script load, which isn't what you want
</script>
I have the following form as part of my webpage:
<form id="collabAccess" onsubmit="submitCollabForm()" >
<div id="row-1">
<div class="two-col" id="email"><input type="text" placeholder="Enter email addresses separated by commas"/></div>
<div id="collabSelect" class="collab two-col styled-select">
<select id="collabaccess">
<option>Can Read</option>
<option>Can Write</option>
<option>Can Read & Write </option>
<option>Administrator </option>
</select>
</div>
</div>
<div id="message">
<textarea id="personalMessage" cols="154" rows="10" placeholder="Optional: include a personal message"></textarea>
</div>
<div id="submit-wrapper"><input type="submit" value="Add Collaborators" id="addCollaborators" disabled='disabled' class="small-btn disabled"/></div>
</form>
The function submitCollabForm() is as follows:
function submitCollabForm() {
console.log('in submitCollabForm');
var valid = validateEmails();
if (valid == false) {
var email = document.getElementById('email');
email.addClass('error');
}
}
where validateEmails() is just another js function for validating that the email addresses int he form have the correct format.
However, it looks like onsubmit is not being called at all. Even if I change things to onsubmit="console.log('xyz'), no console statement is being output. I've also checked for javascript errors in the console, but I am getting nothing.
Is there any reason why onsubmit is not working properly?
Your validation function needs to return false to stop the form from submitting. It's better to have
onsubmit="return submitCollabForm()"
See With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"? for details.
The onsubmit handler is not called, because the form cannot be submitted by any normal means, i.e. the submit event cannot be caused. There is only one submit control, and it is declared as disabled.
if you feel all code is correct still it's not working then,
Simple steps to do,
1) create one script tag in the same page where your form is, create one function and set one alert and test it. If it is working then try following steps.
2) Try to check the path of your javascript file.
3) if path is correct, then change the name of your javascript function sometimes your name tag conflicts with your function name, and submit points to it, so your call is not reaching at your function. It happened with me. so I posted it here, hope it will be helpful to someone.
I am creating a page that is only javascript and html. I have 2 problems.
When it calls the function inputs() in this form, it fails at the first time and success on the next submissions.
<div id="container">
<form onsubmit="inputs()" action="#">
Variables: <input type="number" id="vars" size="1" required/>
Constraints: <input type="number" id="cons" size="1" required/>
<input type="submit" value="Submit">
</form>
</div>
I wasnt able to solve this but I skipped it because it still proceeds to the inputs() the next submissions.
But in my inputs(), i created a form dynamically. The form is created as this:
var form = document.createElement("form");
form.setAttribute("action","#");
form.setAttribute("onsubmit","solve()");
Now, when I submit the dynamically created form, the problem is it goes back to the first set of form. solve() was not called.
Why is it? What should be edited?
Thanks for the help in advance.
solve() has these lines of codes. It's just a test if it will successfully go into it but it fails. This just deletes all the elements.
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
This line
form.setAttribute("onsubmit","solve()");
isn't doing what you think it does. If it was in the actual html it would work but not now. What it does is just make the attribute appear in the console. The event handler isn't actually being set.
Instead do it via onsubmit property or addEventListener
form.onsubmit = solve; // now it must work
Try return false at the end of the function solve. this should work to show but would not perform action. Also add "return solve()" instead of "solve()".
I have following simple HTML Form & i tried to submit the form automatically during page load.
Below Javascript code is not automatically submitting the form.
HTML :
<form action="SSL.php" method="POST" name="TForm" id="transactionForm">
<input type="hidden" name="merchantTxnId" id="merchantTxnId" value="test">
<input type="submit" name="submit" id="submit" value="submit" style="visibility:hidden">
</form>
Redirecting ... Please wait...
Java script:
<script>
window.onload = function(){
alert(1); // this is working..
document.getElementById("transactionForm").submit(); //nothing is happening with this line . form is not getting submitted
}
</script>
I found following error in Chrome console mode says:
Kindly suggest me where the problem is...
You may not use submit as the name or id of any of your form elements.
The reason is, that you can reach each child of your form via document.getElementById('form').nameOfTheChild where nameOfTheChild is the name of the child. If you have a child with the name submit, document.getElementById('form').submit is a shortcut to address that child.
The documentation of .submit() says that :
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures.
I need to validate my form fields displayed in facebox.
The problem is that i am unable to get the values of the fields by using javascript.
for ex: document.form.field_name.value doesnt return its value.
Code sample :
<script type="text/javascript">
function validate()
{
if (document.form1.field.value=='')
{
alert ("Field cannot be left blank");
}
}
</script>
<form name="form1" onsubmit="return validate()">
<input type="text" name="field" />
</form>
A way to do this would be to pass the value directly from the form to the validation code.
<form name="form" id="form" onsubmit="return validate(this.field.value)">
<input type="text" id="field" />
</form>
Or you could even use a text box without the form using:
<input type="text" id="field"
onkeydown="if (event.keyCode == 13) return validate(this.value)" />
Update the script to allow for the new value parameter:
<script type="text/javascript">
function validate(val) {
if (val.length < 1)
{
alert ("field cannot be left blank");
return false; //to stop the default action of submitting the form
} else {
alert ("Value: "+val);
return true; //allow to submit the page
}
}
</script>
This is actually a pretty easy and simple validation, but don't forget to set the return action based on whether you want the system to proceed with the submit or not.
I'm not sure where your pulling your page from whether from a remote html address or a locally stored div. So I'm not sure why your solution of pulling the value from the DOM does not work. I generally have no problems using jquery to get and set the values from the different fields in facebox windows.
NOTE: you have to be careful where you place your scripts. It depends on your application but sometimes you may want to place the script in the root document instead of the facebox page because if you load a remote facebox div you have a scope change and may need to refer to parent.document to access parent fields when the script is embedded in the remote facebox div.
Facebox copies the chunk of DOM displayed, effectively creating elements with duplicate ids. This is not allowed by HTML standard. Your javascript goes bonkers looking for a single element uniquely identified by its id, yet it finds 2 of them...
This is a huge bug in Facebox. Any code in a facebox should not have ids. All your bindings should be renewed when the facebox is revealed.