Submit a form via this object - javascript

I have a form that I want to submit, and I don't know the best way to call the form.
This is my HTML
<form id="form2" name="form2">
<select id="situation_matrimoniale" name="situation_matrimoniale">
<option value="Célibataire">Célibataire</option>
<option value="Marié(e)">Marié(e)</option>
<option value="Veuf(ve)">Veuf(ve)</option>
<option value="Divorcé(e)">Divorcé(e)</option>
</select><input type="text" name="nombre_enfant" id="nombre_enfant" value="" /><input type="button" value="Enregistrer" name="submit" onclick="submitFormInfoEtatCivil()" />
</form>
Now the Javascript, I included jQuery.
function submitFormInfoEtatCivil() {
var update = "index.php/rh/updateinfo";
var dataString = $( this ).serialize();
// dataString return <empty string>
jQuery.ajax({
});
}
I have many forms with ids : form1, form2, form3 ...
My problem is how to specify the fonction submitFormInfoEtatCivil() to get the form where button is submitted. I used $( this ).serialize() but I am wrong because the output is empty.

You can pass this inside function and then use .closest("form") to get input datas from form where button has been clicked.
Demo Code :
function submitFormInfoEtatCivil(el) {
var update = "index.php/rh/updateinfo";
//use closest to get form where button is clicked
var dataString = $(el).closest("form").serialize();
console.log(dataString)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form2" name="form2">
<select id="situation_matrimoniale" name="situation_matrimoniale">
<option value="Célibataire">Célibataire</option>
<option value="Marié(e)">Marié(e)</option>
<option value="Veuf(ve)">Veuf(ve)</option>
<option value="Divorcé(e)">Divorcé(e)</option>
</select><input type="text" name="nombre_enfant" id="nombre_enfant" value="" />
<!--pass `this` inside function-->
<input type="button" value="Enregistrer" name="submit" onclick="submitFormInfoEtatCivil(this)" />
</form>
<form id="form" name="form">
<select id="situation_matrimoniale" name="situation_matrimoniale">
<option value="Célibataire">Célibataire</option>
<option value="Marié(e)">Marié(e)</option>
<option value="Veuf(ve)">Veuf(ve)</option>
<option value="Divorcé(e)">Divorcé(e)</option>
</select><input type="text" name="nombre_enfant" id="nombre_enfant" value="" />
<!--pass `this` inside function-->
<input type="button" value="Enregistrer" name="submit" onclick="submitFormInfoEtatCivil(this)" />
</form>

$(this) that you use refers to button and you are getting empty string when you are serialize() a button.
I strongly recommend an another solution for this problem; you can catch the form when it is submitted with the on() function;
$('form').on('submit',function(){
var thiz = $(this);
var update = thiz.attr("form-url"); //get update url from the form as an attiribute or define it staticly.
var dataString = thiz.serialize();
return false; //to prevent original form action.
});
When you use above code snippet you can remove onclick="submitFormInfoEtatCivil(this)" from your code and also if you want to deep dive with on() function, you can find here an documentation.

Related

onsubmit doesn't display text [duplicate]

I'm new to Javascript and HTML.
I have the following form in HTML:
<div id="form-select">
<form id="date_form" action="" METHOD="POST">
<datalist id="dates">
<option value="February 7">February 7</option>
<option value="February 14">February 14</option>
<option value="February 21">February 21</option>
<option value="February 28">February 28</option>
</datalist>
<input type="text" class="input" name="data" id="date" value="" list="dates" placeholder="pick a date"><br>
<input type="submit" name="submit" onClick="myFunction()"/>
</form>
</div>
Here's the javascript in a file called script.js. The js file is linked in the header as 'script type="text/javascript" src="script.js':
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>;
}
};
When I fill out the form and hit submit, the javascript correctly executes the function, but the result (i.e. adding HEADING to the html) happens for a couple of milliseconds before disappearing and resetting to the original page before I had hit submit.
How do I make it so that the insertion of HEADING remains permanent?
Move the listener to the form's submit handler. Have the function return false to stop submission:
<form id="date_form" onsubmit="return myFunction();" ...>
Take the listener off the button:
<input type="submit">
Do not give it a name of submit as that will mask the form's submit method so you can't call it. Submit buttons only need a name if there are two or more on a form and you want to know which one was used to submit the form.
There is an error in your code, it's missing a closing double qoute:
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>";
}
return false; // to stop submission
};
This may or may not fix you issues, you haven't said what you are actually trying to do.

send form data to function on submit

I have an html page which has around six different forms with different somewhat unrelated fields in each form. What I'm trying to do is create a single jquery or javascript function to handle all the Fetch() on form submit without knowing the form ID (which is most of what I found in tutorials online). Right now I'm just trying to get the form data to display in an alert, but the alert is always blank (no form data being passed?).
My code for what I think should capture any form submit and display the form data:
<script>
$(document).ready(function() {
$("form").on("submit", function(e) {
console.log("CCCCCCC in script CCCCCCCCCc")
e.preventDefault();
var dataString = $(this).serialize();
alert(dataString);
return false;
});
});
</script>
I have a couple of these type of forms (took out bootstrap class info for ease of reading:
<form>
<div>
<div>
<label for="thing1">Choose:</label>
<select id="thing1" name="thing1">
<option value="XXX">XXX</option>
<option value="YYY">YYY</option>
</select>
</div>
<div>
<label for="inputtext">Command</label>
<input type="text" id="inputtext" name="thing2">
</div>
<div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
How can I get any of the form data into the alert box? Ideally later I will use fetch() after I massage the input string.
The form doesn't have any serializable data.
A form control's data comes from a combination of its name and value but none of your form controls have name attributes.
As #Quentin suggested, you need to give a name to select and input elements, in order to get their values.
For instance:
$('form').submit(function(e) {
e.preventDefault();
var el_1 = this.thing1;
var el_2 = this.inputtext;
alert(el_1.value + ', ' + el_2.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
<div>
<div>
<label for="thing1">Choose:</label>
<select id="thing1" name="thing1">
<option value="XXX">XXX</option>
<option value="YYY">YYY</option>
</select>
</div>
<div>
<label for="inputtext">Command</label>
<input type="text" id="inputtext" name="inputtext">
</div>
<div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>

Why The Validation is not working for the provided html/ js code

I want the to get the required in the html page if none is selected.
function validation() {
var country = getElementById("country");
if (country.value = "") {
documnet.getElementById("countryy").innerHTML = "Required";
return false;
} else
return true;
}
<form onsubmit="return validation();">
<select id="country"><span id="countryy"></span>
</select><br>
<input type="submit" name="Submit" value="Submit">
</form>
Why The Validation is not working for the provided html/ js code. I want the to get the required in the html page if none is selected. I am new to js learning.
Several issues
Spelling mistake in the document.getElementById
missing document on the other document.getElementById
No preventDefault which will submit the form if any JS errors
= is assignment - you need == or === to compare
span needs to be outside the select
You did not use value="Default" in the "NONE" options
It is not recommended to have inline event handlers. Here is a better version
Note I added a class to toggle the required in case the user changes the select to conform
window.addEventListener("load", function() {
const errorSpan = document.getElementById("countryy"); // cache the elements
const country = document.getElementById("country");
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = country.value; // get the value
if (val === "") {
e.preventDefault(); // stop submit
}
errorSpan.classList.toggle("hide",val); // hide if value
})
country.addEventListener("change",function() { // if user changes the select
errorSpan.classList.toggle("hide",this.val); // hide if value
})
})
.hide { display : none; }
<form id="myForm">
<select id="country">
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select> <span id="countryy" class="hide">Required</span><br>
<input type="submit" name="Submit" value="Submit">
</form>
HOWEVER you could remove all the script and just add required attribute to the select and keep the empty default
<form id="myForm">
<select id="country" required>
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select><span id="countryy"></span><br>
<input type="submit" name="Submit" value="Submit">
</form>
Use required attribute in the select tag. It will considered in html 5 validation.
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_select_required

Two forms on the same page needs the value of the same element

I have two forms on a php page. They post to different pages when they are submitted. Both forms need the value of a dropbox that is inside form A. How do I get this value posted when form B is submitted?
Create a hidden input in form B and put a change event on the dropdown in form A which copies it's value to that.
Example (using jQuery - if you want to do it with another library or plain javascript you'll need to adapt it).
<script type="text/javascript">
$(function(){
$('#copy-src').change(function(){
$('#copy-target').val( $(this).val() );
}).change();
});
</script>
<form id="a" action="/a">
<input type="text" name="a_only" />
<select id="copy-src" name="also_b">
<option value=""></option>
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select>
<button type="submit">Submit</button>
</form>
<form id="b" action="/b">
<input type="text" name="b_only" />
<input type="hidden" name="also_a" id="copy-target" />
<button type="submit">Submit</button>
</form>
The .change(function(){}) creates a change event to copy the value while the final .change() triggers that event (on page load) to ensure the value is right initially.
You can copy dropbox value to Form B while submitting;
On formB;
<form onsubmit="getDropdownValue()">
.....
</form>
And in function;
function getDropdownValue() {
var formB = document.getElementById("formB");
// Get selected value from FormA
var e = document.getElementById("formADropdown");
var value = e.options[e.selectedIndex].value;
// Append it to formB
var input = document.createElement("input");
input.type = "hidden";
input.name = "dropdownValue";
formB.appendChild(input);
}
You can see demo: Demo . I demo when you click submit, you will see dropdownvalue from form A will be copied to formB before submit

Need help to redirect the form on submit

I need help. When I submit this form I want it to automatically redirect to the value option (which is url) in the select list.
So on pressing submit for Ahmedabad selected in select list it should redirect to http://intranet.guj.nic.in/passport
Currently it is not redirecting. What is the best way to do it using inline javascript code?
<html><body>
<form id="pass-form" >
<select id="pass-dropdown" ><option selected="selected">Select Passport Office
for Status page </option><option value="http://intranet.guj.nic.in/passport/">Ahemadabad
</option><option value="http://passportstatus.nic.in/passmain.php?city=asr">Amritsar
</option><option value="http://rpobangalore.gov.in/npassport.asp">Bangalore
</option><option value="http://passportstatus.nic.in/passmain.php?city=bly">Bareilly
</option></select>
<input type="submit" onsubmit="var sel = document.getElementById('pass-dropdown'); window.location = sel.options[sel.selectedIndex].value" />
</form>
</body>
</html>
onsubmit is an event of the <form> element and not of the submit button.
Change your form code to:
<form id="pass-form" onsubmit="window.location.href = 'newlocation'; return false;">
...
<input type="submit" value="Submit" />
</form>
In some cases you might have to use return to ensure the desired return value gets used:
<form onsubmit="return redirectMe();">
<input placeholder="Search" type="text">
</form>
... more code here ...
function redirectMe() {
window.location.replace("http://stackoverflow.com");
return false;
}
Source: How to pass an event object to a function in Javascript?
Change the type = "submit" to button
<input type="button" onclick="var sel = document.getElementById('pass-dropdown'); window.location = sel.options[sel.selectedIndex].value" />
Update
<input type="button" onclick="var sel = document.getElementById('pass-dropdown');
var frm = document.getElementById("pass-form"); frm.action = sel; frm.submit();" />
It would be better if you put that in a function and call the function instead
<form id="pass-form" onsubmit="var sel = document.getElementById('pass-dropdown'); window.location = sel.options[sel.selectedIndex].value" >
...
<input type="submit" />
</form>
You must do the submit attribute to the form tag. Then it should work.
http://www.w3schools.com/jsref/event_form_onsubmit.asp

Categories

Resources