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);
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 HTML code:
<html>
<!-- assume jquery is loaded -->
<body>
<form id="sform" method="get" style="display:none;">
<input type="hidden" name="eid" />
<input type="hidden" name="returnURL" />
<input type="hidden" name="returnID" value="ieid" />
<select id="dropdownlist" name="ieid">
<option selected="selected"></option>
</select>
</form>
</body>
</html>
What happens is the user enters an email address, it checks (server-side with PHP) the credentials and if valid, returns the following JSON object (in this case, assume that the values are valid urls (ie. http://sitehere.com/somethingelse):
{
"get_action" : "geturl",
"eid" : "eidurl",
"return_url" : "returnurl",
"option_url" : "optionurl"
}
This is retrieved when the user hits the login button on the home page. This button triggers a POST request which retrieves the results and parses the JSON into the form above. I then change the values of the form from the original code and the action of the form itself before submitting the form. This is shown below.
$.post('/?c=controller&a=method', {'email' : $('input[name="email"]').val() }, function(data){
var result = $.parseJSON(data);
$('#sform').change_action(result.get_action);
$('input[name="eid"]').change_val(result.eid);
$('input[name="returnURL"]').change_val(result.return_url);
$('select[name="ieid"]').find('option:selected').change_val(result.option_url);
$('#sform').submit();
};
Where change_val() and change_action() are defined like this:
$.fn.change_val = function(v){
return $(this).val(v).trigger("change");
}
$.fn.change_action = function(v){
return $(this).attr('action', v).trigger("change");
}
The reason why I defined these functions was because originally, I had just been calling val('new value'); and the form seemed to not be updating at all. I read that I had to trigger a change when using jQuery to update the form before submitting it.
However, even after triggering a change, it seems like the HTML still isn't updated (at least in Chrome) and the form is not being submitted correctly because none of the values are actually changing.
So, I need to be able to take a parsed result, update the values in the form (with specific id's), and then submit the form so that it re-directs somewhere. Is there a way to do this correctly?
Im currently loading my pages in Codeigniter using ajax for sections of the page.
but, when i press submit on one of the loaded forms, i dont get the response out from it. its like the form never was sent. im exspecting the layout to be proccessed, instead it returns the same layout as if it wasnt proccessed.
How can i make so, when pressing submit button on the loaded form data, that it will be proccessed by the same url, and then load the new response to the view?
piece of code:
$("form").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$(".main_center").html(data);
});
return false; // prevent normal submit
});
piece of html:
<form method="POST" action="/crime">
<input type="hidden" name="crimeinput" id="crimeAction" value="123">
<input type="submit" value="do" name="docrime" id="krimsubmit" style="display:none">
</form>
EDIT:
After more looking into it, it seems like only the crimeInput variable is sent to the server, and not the docrime. How can i make it able to send the submit name aswell?
As per the docs for serialize:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
So if you want that field to be passed, you'll have to add it in a different way, perhaps as another hidden input.
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
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!