jQuery and Ajax not working $.on - javascript

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();

Related

Why am I getting null values when submitting a form after editing some values with JS?

I have a form with some inputs that are filled from the result of an AJAX request. When I submit the form I get only null on the back-end. I tried to submit the values without editing it and it works
this is my java script code
editPayment = function() {
if ($('#entrytransId').val() != '') {
if ($('#entryReceiptTypesselect').val() == "1") {
$.ajax({
type: "GET",
url: "#Url.Action("GetInvoiceNumber", "Payment")",
data: {transId: $('#entrytransId').val()},
success: function(response) {
if (response.invNo == 0) {
window.location.reload();
} else {
$('#reciptNo').val(response.invNo);
$('#enteryAmt').val(response.Amt);
$('#entrytransId').attr("disabled", "true");
$('#enteryhide').show(500);
}
},
error: function(reponse) {
window.location.reload();
}
});
}
}
This is Exactly My HTML Form with inputs I have tried more times and its failures
but when I deleted the javascript function and fill the data manually its works
<form action="/Payment/EditPayment" id="MF" method="post">
<div class="row">
<div class="col-md-2">
<label class="form-control">Receipt Type</label>
</div>
<div class="col-md-8">
<select class="form-control" id="entryReceiptTypesselect"
name="entryReceiptTypes" required="true"><option value="">-Choose</option>
<option value="1">MoF</option>
<option value="2">Zakah</option>
<option value="3">Tax</option>
<option value="4">Other Taxs</option>
<option value="5">M & S</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-2">
<label class="form-control">Trans Id</label>
</div>
<div class="col-md-3">
<input required="" type="number" class="form-control" id="entrytransId" name="entrytransId">
</div>
<div class="col-md-2" hidden="" id="btnHidden">
<button type="button" class="btn btn-primary legitRipple" onclick="editPayment()">check</button>
</div>
</div>
<div class="row">
<div class="row">
<div class="col-md-2">
<label class="form-control" id="lblinvoice">reciptNo</label>
</div>
<div class="col-md-4">
<input required="" type="number" name="reciptNo" class="form-control" id="reciptNo">
</div>
</div>
<div class="row" hidden="" id="enteryhide">
<div class="col-md-2">
<label class="form-control">enteryAmt</label>
</div>
<div class="col-md-4">
<input required="" type="number" value="0" name="enteryAmt" class="form-control" id="enteryAmt">
</div>
</div>
<div class="row">
<div class="col-md-2">
<label class="form-control">E15 userName</label>
</div>
<div class="col-md-8">
<input required="" type="text" class="form-control" id="userName" name="userName">
</div>
</div>
<div class="row">
<div class="col-md-2">
<label class="form-control">password</label>
</div>
<div class="col-md-8">
<input required="" type="password" class="form-control" id="password" name="password">
</div>
</div>
</div>
<br>
<br>
<br>
<br>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<input type="submit" value="submit" class="btn btn-block btn-success legitRipple" id="enterysubmit">
</div>
</div>
</form>
The issue is not with setting the values via javascript/jquery, but specifically with setting the inputs to disabled.
$('#entrytransId').attr("disabled", "true");
when an input is set to disabled, it is not included (it is excluded) from the form's POST, so will appear as null in the server-side code.
You can:
- not set them to disabled (will affect your UX)
- enable them just before POST (icky)
- use hidden fields
MVC does this for checkboxes, so you can copy that idea here:
<input type='text' name='entryid' />
<input type='hidden' name='entryid' />
POST uses the input's name field, not its id, so it's ok to have multiple inputs with the same name.
POST will then use the first input that is not disabled (so don't put the hidden one first...)
Then just update the jquery to apply the value to both inputs (if you also want it shown in the UI) rather than by id, eg:
$("name[entryid]").each(function() { $(this).val(newvalue); });
(other ways to set this may be better, not checked if .val() will apply to all, likely only applies to the first)
The proplem was on $('#entrytransId').attr("disabled", "true");
i have another function onselectChange() is disabled all inputs , i tried $('#entrytransId').attr("disabled", "true"); and its works well

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')
}
});

send input data with onsubmit method

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());
}

submit function submits twice after first submisson jquery, PHP

function slideupSubmit (name) {
$(name).submit(function ( event ) {
event.preventDefault();
var target = $(this).attr("action");
var response = $(this).attr("response");
var formName = $(this).attr("id");
$.post(target,
$(this).serialize() + '&' + $.param({ 'formName':formName, response : response}),
function (data) {
$(response).html(data);
$(name).hide();
$(name)[0].reset();
}
);
});
};
function resetForm (name){
$(name).show();
};
Im really new at this and only been coding for a few months so if my code is really bad I apologize, and if the solution is very easy, please forgive me.
I wrote this code so I could reuse it to submit diffrent forms on my page and have a response sent to a div above it. Im able to post everything I want but after the first time it posts, if I post again, it will post twice. Then three times. I know I did something wrong but I cant find the error.
I include this on my response to allow the form to be brought back after hiding.
<a onClick="resetForm('.$_POST['formName'].')" href="#" response=""> New Form?</a>
Here is the form.
<!-- Form 1 --->
<div class="row ">
<div class="col-xs-12">
<div class="well well-dark ">
<h4>Update Contacts</h4>
<span class="contactUpdate-response text-success"></span>
<form id="contactUpdate" class="form form-inline hidden contact-form" response=".contactUpdate-response" method="post" action="ajax/contactUpdate.php">
<div class="form-group">
<input hidden name="contact_entry" value="1"/>
</div>
<div class="form-group">
<label>Contact Title:</label>
<input class="form-control" name="contact_title" required />
</div>
<div class="form-group">
<label>Link to Employee</label>
<select name="empId" class="form-control select-emp-name"></select>
</div>
<div class="form-group">
<label>Category:</label>
<select name="category"class="form-control select-contact-categories ">
</div>
<div class="form-group">
<label>Link to Location</label>
<select name="locat_id" class="form-control select-location"></select>
</div>
<div class="form-group">
<label>Number:</label>
<select name="extId" class="form-control select-dig-ext"></select>
</div>
<div class="form-group">
<input hidden name="updateBy" value="24"/>
</div>
<div class="form-group">
<input onclick="slideupSubmit(contactUpdate)" type="submit" class="form-control btn btn-primary" value="Update List" />
</div>
</form>
</div>
</div>
</div>
<!--- -->
<input type="submit" class="form-control btn btn-primary" value="Update List" />
take your event listener out of function
and remove onclick=...
$(name).submit(function ( event ) {
event.preventDefault();
var target = $(this).attr("action");
var response = $(this).attr("response");
var formName = $(this).attr("id");
$.post( target, $(this).serialize()
+'&'+$.param({ 'formName': formName,
response : response}),
function(data){$(response).html(data);
$(name).hide();
$(name)[0].reset();
});

Multiple products in one form

I would like to add a functionality in my form, in which a user can add as many entries before hitting submit button, like a 'add to cart' functionality, show the added entries in same page, in a separate div with submit button then save those multiple entry in database using that submit button(in a separate div that shows added entry).
So far my form allows only entries on per submit bases, meaning is if the user wants to add another entry, he/she has to go back to the form and add and click to submit again.
<form method="POST" name="myForm" action="saveto.php">
<label> Speed Rating:</label>
<select name="speed_rating" required class="form-control" id="speed_rating" ></select>
<div class="form-group col-sm-8">
<label> Description:</label>
<select name="description" required class="form-control" id="description" >
</select>
</div>
<div class="form-group col-sm-4">
<label> Load Index:</label>
<select name="load_index" required class="form-control" id="load_index" >
</select>
</div>
<div class="form-group col-sm-6">
<label> Vendor:</label>
<select name="vendor" required class="form-control" id="vendor" >
</select>
<div class="note"> Recommended Vendor : <span id="recomvend"> </span> </div>
</div>
<div class="form-group col-sm-6">
<label> Quantity:</label>
<input type="text" required name="qty" class="form-control" id="qty"></div>
<div style="clear:both"> </div>
<input type="submit" name="submit" class="btn btn-primary smp" value="Submit">
<button id="clear" type="button" class="btn btn-primary smp smp2" > Reset </button>
</div>
<input type="submit" value="submit" name="submit">
</form>
How would you achieved this? My saveto.php is just a normal script that will process the submitted data to database, one entry in a per submit bases.
I created this jsfiddle https://jsfiddle.net/jy6vh4rp/31/
If that's what you are looking for then you should add this to your front end:
<form action="validate.php" method="post">
<div style="padding: 30px 0; text-align: center;">
<button type="button" onclick="createDOM()">Add</button>
<input type="submit" value="submit" name="submit" />
</div>
<div class="productsContainer"></div>
</form>
<script>
$(document).ready(function() {
id = 0;
createDOM = function() {
$(".productsContainer").append('<input type="text" id="' + id + '" name="products[]" value="' + id + '" />');
id++;
};
});
</script>
And this to your validation backend :
foreach($_POST['products'] as $prodInput){
$product = filter_var($prodInput,FILTER_SANITIZE_NUMBER_INT);
if( is_numeric($product) ){
echo $product;
}
}

Categories