send input data with onsubmit method - javascript

I have a Multi forms that contain some inputs
<form class="form" role="form" onsubmit="completeSave()">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
<form class="form" role="form" onsubmit="completeSave()">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
I want to get value of inputs on submitting form I tried this code but it didnt worked
function completeSave() {
event.preventDefault();
var thisForm = $(this);
console.log(thisForm.find('input[name="name"]').val())
}
it returns undefined in console

you are using jQuery for this case.
You need to import your jQuery then use below function
jQuery can be found at
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
function completeSave(e) {
event.preventDefault();
var thisForm = $(e).find("[name=name]");
console.log(thisForm.val());
}
FORM
<form class="form" role="form" onsubmit="completeSave(this)"> <!-- add this -->
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>

use this java script code
function completeSave() {
event.preventDefault();
console.log($("#name").val());
}
but add an id on text input as -
<input type="text" class="form-control" name="name" id="name"
value="{{$media->name}}">

HTML forms
<form class="form" role="form" id="form1">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="button" id="{{$media->id}}" class="btn blue" onclick="completeSave("form1");">ارایه</button>
</div>
Scripts
function completeSave(formId) {
console.log($("#"+formId+' input[name="name"]').val())
}
Hope it helps :)

fist i assume you are using jquery
solution 1
the keyword this only evaluates to the form if the completeSave function
is called via jquery's submit event, so for this solution, you don't need the completeSave function on the form's HTML tag
$('form').submit(function(event) {
event.preventDefault();
var thisForm = $(event.target);
console.log(thisForm.find('input[name="name"]').val())
})
solution 2
you should pass the event argument to the completeSave function located on onsubmit attribute of form's HTML tag
ex: <form onsubmint="completeSave(event)">
since the this keyword doesn't evaluate to the form, you gotta select it manually
function completeSave(event) {
event.preventDefault();
var thisForm = $(event.target);
console.log(thisForm.find('input[name="name"]').val())
}
and the input[name="name"] will be the one whos form is submited

Please try this one:
For sure you should add unique id to your forms
<form class="form" role="form" id="form1" onsubmit="completeSave(form1)">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
<form class="form" role="form" id="form2" onsubmit="completeSave(form2)">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
and your javascript code could look like this:
function completeSave(form) {
event.preventDefault();
var input = $("#" + form + " :text");
console.log(input.val());
}

Related

jQuery and Ajax not working $.on

I want when I click on Clear button, all fields in the form to be cleared.
The ajax request is only replacing the form from the tag <form> to </form>.
When it is clicked on Clear button, the console output is working.
I have the following form:
<div class="col-lg-5 formWrapper">
<form data-th-fragment="layoutForm" id="layoutForm" class="form-horizontal" data-th-object="${layout}" data-th-action="#{/layouts/add}" method="POST" role="form">
<div class="row">
<input id="objectId" data-th-field="*{id}" type="hidden">
<input data-th-if="*{filePath} !=null" data-th-field="*{filePath}" type="text" hidden="hidden">
<label for="layoutName" >Layout name</label>
<input data-th-field="*{name}" id="layoutName" class="form-control" type="text">
</div>
<div class="row">
<div class="col-lg-4">
<label for="status">Status</label>
<select id="status" data-th-field="*{status}"class="form-control">
<option value="1">Active</option>
<option value="0">Blocked</option>
</select>
</div>
<div class="col-lg-6">
<label for="exhibitorName">Exhibitor</label>
<select data-th-field="*{exhibitor}" name="exhibitorName" id="exhibitorName" class="form-control">
<option data-th-each="exhibitor : ${exhibitorsList}" data-th-value="${exhibitor.id}" data-th-text="${exhibitor.exhibitorName}"></option>
</select>
</div>
</div>
<div class="row">
<div class=" col-lg-3">
<input id="clearForm" type="reset" value="Clear" class="form-control btn-lg btn btn-default">
</div>
<div class=" col-lg-3 col-lg-offset-4">
<input id="submitButton" type="submit" value="Add" class="form-control btn-lg btn btn-success">
</div>
</div>
</form>
</div>
The form looks something like this:
The jQuery is as follow:
$(document).ready(function() {
$('.formWrapper').on('click','#clearForm', function (event) {
$(this).closest('form').find("input[type=text]").val("");
console.log("ASD");
});
});
The snipped is how I replace the form:
$("body").on('click','#editLayout', function(event){
var ajax = $.ajax({
url : "/layouts/edit/" + $(this).data("id"),
dataType : "html",
success: function (data) {
$("#layoutForm").replaceWith(data);
$('#submitButton').val('Edit').addClass('btn-warning').removeClass('btn-success');
}
});
});
Try this,
$('#form_id').trigger("reset");
or
$('#form_id')[0].reset();
A reset button doesn't need any script at all (or name or id):
<input type="reset">
and you're done. But if you really must use a script, note that every form control has a form property that references the form it's in, so you could do:
<input type="button" onclick="this.form.reset();">
But a reset button is a far better choice.
Try to use $('#clearForm').reset(); or $('#clearForm')[0].reset();

validation form with regex while using Javascript

i'm trying to validate my bootstrap form with regex in javascript. I've started the javascript but don't know the right way to continue the validation with my regular expression. I'm trying to validate every input in my form before submitting it.
If anyone could help me with my issue it would be appreciated.
Thank you very much in advance.
In javascript no Jquery please
John Simmons
HTML (This is my html bootstrap form)
<div class="col-md-6">
<div class="well well-sm">
<form class="form-horizontal" id="form" method="post" onsubmit="return validerForm(this)">
<fieldset>
<legend class="text-center header">Contact</legend>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="lastName" name="LN" type="text" placeholder="Nom" autofocus class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="firstName" name="FN" type="text" placeholder="Prenom" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="email" name="email" type="text" placeholder="Courriel" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="phone" name="phone" type="text" placeholder="Téléphone" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<textarea class="form-control" id="message" name="Message" placeholder="Entrez votre message. Nous allons vous répondre le plus tôt que possible." rows="7"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
<input class="btn btn-primary btn-lg" type="reset" onclick="clearForm()" value="Clear">
</div>
</div>
</fieldset>
</form>
</div>
</div>
Javascript (this is my javascript with my regexs, I was thinking about doing a function that would verify every value entered with the regex)
var nameregex = /(^[A-Z][a-z]{1,24})+$/;
var emailregex= /^([A-Za-z])([A-Za-z0-9])+\#([a-z0-9\-]{2,})\.([a-z]{2,4})$/;
function validerForm(form) {
window.onload = function(){
document.getElementById('lastName').focus();
}
var valName = Formulaire.name.value;
var valFirst = Formulaire.firstname.value;
var valEmail = Formulaire.email.value;
var nameValide = validationName(valName);
var firstValide = validationFirstName(valFirst);
var emailValide - validationEmail(valEmail);
}
function validationName(valName){
if(nameregex.test(valName) == true){
}else{
}
}
function clearForm() {
document.getElementById("form").reset();
}
You may use string.match()
i.e.: if (valEmail.match(emailregex)) { do stuff!; }

How to make a second submit button?

I have a classic form that submits data to a controller. Nothing special until here.
The thing is I want a second button, let's say "Save and Exit" that I want to also submit and redirect to home page.
How could I do that? I guess this includes a little javascript for checking?
I just can't wrap my head around it. Thank you!
<form method="POST" action="link/here" id="main_form" class="form-horizontal">
<input name="_token" value="JDtRMqc4aRFlK4QFzDPRTxKvNxIj5EnoLOceOUBT" type="hidden">
<div class="box-body">
<div class="form-group">
<label for="url" class="col-sm-3 control-label">Figura</label>
<div class="col-sm-9">
<input class="form-control" id="Figura" name="figura" placeholder="Figura" value="" type="text">
</div>
</div>
<div class="form-group">
<label for="url" class="col-sm-3 control-label">Parcela</label>
<div class="col-sm-9">
<input class="form-control" id="Parcela" name="parcela" placeholder="Parcela" value="" type="text">
</div>
</div>
<div class="form-group">
<label for="url" class="col-sm-3 control-label">Rand</label>
<div class="col-sm-9">
<input class="form-control" id="Rand" name="rand" placeholder="Rand" value="" type="text">
</div>
</div>
<div class="form-group">
<label for="url" class="col-sm-3 control-label">Nr. Locuri</label>
<div class="col-sm-9">
<input class="form-control" id="Locuri" name="locuri" placeholder="Locuri" value="" type="text">
</div>
</div>
<div id="locuri_div" class="col-sm-offset-1"></div>
<div class="pull-right">
<button type="submit" class="btn btn-success">Salveaza</button>
</div>
<div class="pull-left">
Inapoi
</div>
</div>
<!-- /.box-body -->
</form>
your current button :
<button type="submit" name="check" value="0" class="btn btn-success">Save</button>
add a new one:
<button type="submit" name="check" value="1" class="btn btn-success">Save and Exit</button>
then in your save.php do:
if($_POST['check'] == 0){
//redirect to page
}
else{
//redirect to home
}
Give each button a name and a value. In your controller (client-side JS is the wrong tool for this), test the name and then redirect based on that.
For example:
<button name="action" value="save">Save</button>
<button name="action" value="save_and_go_home">Save & Go Home</button>
And then (to use expressjs as an example):
app.post('/here', function (req, res) {
// Do everything else you want to do with the data
// Then
var action = req.body.action;
if (action === "save_and_go_home") {
res.redirect("/");
} else {
res.send('Whatever you were sending before')
}
});

Detect the name of required field and not validated when submit a form

I create a form in html5 like this example :
<form action="/my/url/insert.php" method="POST">
<div class="row">
name <input name="name" required/>
</div>
<div class="row">
type <input name="type" required/>
</div>
<div class="row">
year <input name="year" required/>
</div>
....
<div class="row">
album <input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save"/>
</div>
</form>
<script>
$('form').submit(function(){
console.log('test');
});
</script>
The problem :
I want to detect the name of the required field that are not validated when submiting and logging it.
for example : if I don't fill the input "album" when submit i detect it before the message "a field is required..."
is there a way to do this ?
thank you.
Here you go.. Loop through each input:required field and get its name with .attr.
$('form').submit(function(e) {
e.preventDefault();
$(this).find('input:required').each(function(){
console.log($(this).attr('name'));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/my/url/insert.php" method="POST">
<div class="row">
name
<input name="name" required/>
</div>
<div class="row">
type
<input name="type" required/>
</div>
<div class="row">
year
<input name="year" required/>
</div>
....
<div class="row">
album
<input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save" />
</div>
</form>
Updated
$('form').submit(function(e) {
e.preventDefault();
$(this).find('input:required').each(function(){
if($(this).val()==""){ //check if its empty
console.log($(this).attr('name'));
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form novalidate action="/my/url/insert.php" method="POST">
<div class="row">
name
<input name="name" required/>
</div>
<div class="row">
type
<input name="type" required/>
</div>
<div class="row">
year
<input name="year" required/>
</div>
....
<div class="row">
album
<input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save" />
</div>
</form>
Assuming that only required will be the property for validation, above condition will hold good and yea, by default when you say required, browser will have its validation suppressing validation written by you. If you want your validation to work, add novalidate to form as said in one of the comments above..
Select them by property required:
$(function() {
$('form').submit(function(){
$("input:required", $(this)).each(function() {
console.log($(this).attr("name"));
});
});
});
To do a simple required check on your own make a simple "not empty" condition. But for this, your form need the novalidate class, otherwise submit callback will not be triggered and nothing ever happens.
$(function() {
$('form').submit(function(){
$("input:required", $(this)).each(function() {
if( $(this).val() != "" )
console.log($(this).attr("name"));
});
});
});
Full example here: https://jsfiddle.net/vvdh66rb/
You can also do like this:
<form action="/my/url/insert.php" method="POST" onSubmit="return myFunction()">
<div class="row">
<!--I am only giving id to one to show an exmaple you can give to differnt-->
name <input name="name" id="some" required/>
</div>
<div class="row">
type <input name="type" required/>
</div>
<div class="row">
year <input name="year" required/>
</div>
....
<div class="row">
album <input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save"/>
</div>
</form>
<script>
function myFunction() {
var x = document.getElementById('some').value;
if (x == "" || x == null) {
alert('sadsd');
return false;
//You can give anything else than alert
}
}

How to get form's id, only which submitted

I have 4 forms in my html, and required that form's id which submitted. But every time constantly first form's id comes in output.
My HTML is:
<form name="form" id="filterHeadByFamNum" class="form-horizontal" role="form">
<div class="form-group">
<label>Family Number</label> <input type="text" name="familyNumber" placeholder="Family Number" class="form-control">
</div>
<button type="button" class="btn btn-primary" onclick="filterByFamNum();return false;">Submit</button>
</form>
<form name="form" id="filterHeadByMemName" class="form-horizontal" role="form">
<div class="form-group">
<label>Head Name</label> <input type="text" name="head" placeholder="Head Name" class="form-control">
</div>
<button type="button" class="btn btn-primary" id="head" onclick="filterByMemName();return false;">Submit</button>
</form>
<form name="form" id="filterMemberByPhone" class="form-horizontal" role="form">
<div class="form-group">
<label>Phone Number</label> <input type="text" name="phone" placeholder="Phone Number" class="form-control">
</div>
<button type="button" class="btn btn-primary" onclick="filterByPhone();return false;">Submit</button>
</form>
<form name="form" id="filterMemberByCNIC" class="form-horizontal" role="form">
<div class="form-group">
<label>CNIC</label> <input type="text" name="cnic" placeholder="CNIC" class="form-control">
</div>
<button type="button" class="btn btn-primary" onclick="filterByCNIC();return false;">Submit</button>
</form>
and my js is
function filterByFamNum(){
var name = $(this.form).attr('id');
console.log(name);
}
function filterByMemName(){
var name = $(this.form).attr('id');
console.log(name);
}
function filterByPhone(){
var name = $(this.form).attr('id');
console.log(name);
}
function filterByCNIC(){
var name = $(this.form).attr('id');
console.log(name);
}
Ouptut of every form submit is constantly filterHeadByFamNum
Rather than adding event listeners to the buttons, just listen for the submit event on the form:
$('form').on('submit', function () {
var id = this.id;
console.log(id);
});
..or without jQuery:
Array.prototype.forEach.call(document.querySelectorAll('form'), function (el) {
el.addEventListener('submit', function () {
var id = el.id;
console.log(id);
});
});
I would use #JoshCrozier's solution for this problem but just for the sake of completion and/or if you're adamant about using your solution instead. Here it is:
jsbin DEMO -> http://jsbin.com/yiteludomu/2
Add this as a parameter in each of your javascript functions to send the button you're clicking.
<button type="button" class="btn btn-primary" onclick="filterByFamNum(this);return false;">Submit</button>
here is how you handle button click .. observe btn which is the clicked button.
function filterByFamNum(btn){
var name = $(btn).parent('form').attr('id');
alert(name);
}
var submittedForms = [];
$('form').on('submit', function () {
submittedForms.push(this.id);
});
submittedForms array will hold the ids of all the submitted form.

Categories