I have a page with several forms.
I am trying to submit one of the forms (say form A) (NOT through Ajax, since I need to load the result page after the submit is processed), BUT I need another form's contents (say form B) to be submitted TOGETHER with form A, i.e. the contents of forms A + B should be submitted TOGETHER to the SAME URL, as one request, and as I said before, NOT as an Ajax request.
The submit should be by a POST request. Also, the forms contain ONLY fields that are not file upload (i.e. input, select, textarea fields).
I have seen suggestions here such as
Posting/submitting multiple forms in jQuery
or
Submitting two forms with a single button
but pay attention that these do not match my case, since the forms are submitted in different requests, and/or they are submitted through Ajax.
I was thinking of getting the contents of one of the forms by (the jQuery's) serialize(), but how do I attach that string to a form submitted by POST?
Or maybe you have other ideas how to accomplish this?
SOLUTION:
Based on the ideas of Sheepy, I wrote the following code. I am also using the answer by Pointy from the following link:
submit multiple forms to same page
//Arguments: "name"s of forms to submit.
//First argument: the form which according to its "action" all other forms will be submitted.
//Example: mergeForms("form1","form2","form3","form4")
function mergeForms() {
var forms = [];
$.each($.makeArray(arguments), function(index, value) {
forms[index] = document.forms[value];
});
var targetForm = forms[0];
$.each(forms, function(i, f) {
if (i != 0) {
$(f).find('input, select, textarea')
.hide()
.appendTo($(targetForm));
}
});
$(targetForm).submit();
}
Well, you have to copy the data from form2 to form1 before the submit. Here is the basic to get you started:
$.each ( $('#form2 input, #form2 select, #form2 textarea').serializeArray(), function ( i, obj ) {
$('<input type="hidden">').prop( obj ).appendTo( $('#form1') );
} );
This function would select inputs from form2, get their current values, then create a new hidden input for each of them and add them to form1.
Depending on your scenario you may want to check the existance of input with same name on form1 first.
A solution to inject the data directly in the post request (and not in a sub field)
<form id="form1">
<input ... />
<input ... />
</form>
<form id="form2">
<input ... />
<input ... />
</form>
<form id="result" action="..." method="POST" onsubmit="merge(); return true;">
<input type="submit" />
</form>
<script type="text/javascript">
function merge() {
$result = $("#result");
$("#form1 input, #form2 input, #form1 select, #form2 select, #form1 textarea, #form2 textarea").each(function() {
$result.append("<input type='hidden' name='"+$(this).attr('name')+"' value='"+$(this).val()+"' />");
});
}
</script>
You can only do one request at a time and that will reload the page unless you use AJAX. The only other option would be to create a script which concatantes the seralizations of your two forms - but at that point, why wouldn't you just use one large form..
Edit: For your combining the two forms, there is an example of this in the answer of the second link you provided.
form A:
<form method="post" action="next.html" onsubmit="this.formbVal.value = $('#formb').serialize(); return true;">
<input type="hidden" name="formbVal" value="" />
<input type="submit">
</form>
form B:
<form id="formb" method="post" action="#" onsubmit="return false;">
</form>
I discovered that your solution will copy the form to another invissible form, but the backside is that the original forms will be cleared an such edit of the original form (eg after form validation errors) is not possible.
To solve this i tried to clone the elements before appending it to the invissible form. I edited your code like this:
//Arguments: "name"s of forms to submit.
//First argument: the form which according to its "action" all other forms will be submitted.
//Example: mergeForms("form1","form2","form3","form4")
function mergeForms() {
var forms = [];
$.each($.makeArray(arguments), function(index, value) {
forms[index] = document.forms[value];
});
var targetForm = forms[0];
$.each(forms, function(i, f) {
if (i != 0) {
$(f).find('input, select, textarea')
.clone()
.hide()
.appendTo($(targetForm));
}
});
Unfortunatly now it doesn't copy the selected values in a select element.
Hope someone can help me to impove this script
you can do some thing like this
$('#SubmitBtn).click(function () {
$("#formId").attr("action", "http://www.YourSite.com/");
$("#formId").attr("method", "post");
$("#formId").attr("target","_blank");
$('#formId').submit();
});
this will submit the for to http://www.YourSite.com/ in a new window
Related
I have a form created in HTML but when I submit my form post and there is a error in the form validation, returning back is not remembering my initial radio selection.
var radio_options = $('form#contact input[type="radio"]');
for (var i=0; i< radio_options.length; i++) {
var option = radio_options[i];
if (option.checked == true) {
console.log(option.id); // how to I check this option to the appropriate radio?
}
}
HTML:
<form action="check.php" id="contact" method="post">
<div class="radioboxes"><strong id="top-more">Options</strong><br>
<span class="othertopic" id="wwus"> <font>Please select one option</font></span>
<div id="top-wwus"><input id="topic_252" name="form_tools_form_id" type="radio" value="252"> <label for="topic_252">Recruitment</label><br>
<input id="topic_259" name="form_tools_form_id" type="radio" value="259"> <label for="topic_259">Requests</label><br>
<button name="submit" type="submit">Submit</button> </div> </div>
</form>
I can access the values but I can't make them checked on the radio returning back to the original form after a error on validation. Can you see the problem in the js?
You need to 'remember' the selected value/radio.
If this is an AJAX request then store the selected radio in JavaScript prior to sending and then if there is an issue (e.g. error) then you can reset the appropriate form value(s) from the stored value(s).
If this a form submit where the page refreshes, then you are going to either pre-populate portions of the view (i.e. form) before returning the response or some other method such as hidden fields or setting a JavaScript variable in a script tag then accessing that on load.
Another option could be to use localStorage or cookies to set the form as you intend.
This is a generalized answer as there are many ways to accomplish this.
$("input[type='radio']").click(function(){
var radioValue = $("input[name='form_tools_form_id']:checked").attr('id');
if(radioValue){
localStorage.setItem('radioValue', radioValue);
}
});
var givenRadioValue = localStorage.getItem('radioValue');
$("#"+givenRadioValue).attr('checked', true);
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 two list boxes that I can move items to and from using jQuery. A summary of the code follows:
<select multiple size="10" id="from">...</select>
<select multiple id="to" size="10" name="subitted array[]">...</select>
Some buttons that when clicked move the items from the above list boxes:
>...
<
<<
The jQuery functions:
function moveAll(from, to) {
$('#'+from+' option').remove().appendTo('#'+to);
}
function moveSelected(from, to) {
$('#'+from+' option:selected').remove().appendTo('#'+to);
}
I also have the following function that I call on submit:
<form name="selection" method="post" onSubmit="return selectAll()">... </form>
function selectAll() {
$("select option").attr("selected","selected");
}
But this only returns by POST the values in the right list box. I would also like to submit other fields present in the form (e.g. hidden fields). How can I do this?
Many thanks.
If your dropdown lists are inside your form, you dotn need any special treatment, just submit your form and all fields inside it, will be send to your controller.
In JS:
$('#formId').submit();
In your html:
<button type="submit">Send</button>
Any of this 2 options would suit your problem, if i understand workgly your problem, please let me know.
Also you should remove this code "onSubmit="return selectAll()" and leave form submit work normally, will send all your data into the form
I have a simple form, where I have a form element with one input type and button.
When I am click button, I am trying to get form data using
var fData = $("#test").serializeArray();
However for some reason, I am not able to get any values of form.
What could be the reason for this?
JSFiddle Demo
There are several issues. Firstly, the input has no name attribute, so it cannot be serialized. Secondly, you create the variable called fData, but log fdata - JS is case sensitive. Finally the form is being submit in the usual method when the button is clicked which means processing will be prevented after the first alert. To prevent this you can change the button to be a standard type, instead of a submit button:
<form id="test" method="POST">
<p>
<input id="val" name="foo" />
</p>
<button class="k-button" id="rset" type="button">submit</button>
</form>
Example fiddle
Or alternatively you can set the code to run under the submit event of the form, and use preventDefault to stop the standard form submission:
$("#test").submit(function (e) {
e.preventDefault();
alert('ok');
var fData = $(this).serializeArray();
alert('rData ' + fData);
});
Example fiddle
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!