How to write a js script that verifies input on html - javascript

I am trying to add validation to a html form that looks like this:
<div id="container">
<header>
<h1>Production Form</h1>
</header>
</br>
<div class="content">
<div class="row">
<article class="col-xs-12">
<form id="cf-task-form">
<section>
<br><br>
<div class="row form-group">
<div class="col-xs-3">
<label for="link">Link</label>
<input type="url" id="link" class="form-control" name="output[link]">
</div>
<div class="col-xs-3">
<label for="address">Address</label>
<input id="address" class="form-control" name="output[address]">
</div>
<div class="col-xs-3">
<label for="research">Research</label>
<select id="research" name="output[research]">
<option value="0">0</option>
<option value="1">1</option>
</select>
</div>
</section>
<div class="col-xs-offset-6 col-xs-6">
<input type="button" class="btn sub-btn pull-right" id="submit-btn" value="Submit" tabindex="10">
</div>
</form>
</article>
</div>
<div class="clear"></div>
</div>
</div>
However the code is not picking validation when I use the required attribute, how can I add validation for this within a js script that will check against the values in this html form before submitting

I think maybe you get the errors because the HTML tags were not opened and closed in the correct order, and you had an opened div that needed to be closed. Try validating the HTML code. I think it can cause problems if your html is not valid.
I added these attributes to your HTML (and validated it), and also some CSS to see the validation result.
<input type="text" id="link" class="form-control" name="output[link]" required="true" pattern="^http.*">
<input id="address" class="form-control" name="output[address]" required="true" pattern=".*street.*">
and
:invalid {
border: 1px solid red;
}
This works and validates as expected.
:invalid {
border: 1px solid red;
}
input {
margin: 1em
}
<div id="container">
<header>
<h1>Production Form</h1>
</header>
<div class="content">
<div class="row">
<article class="col-xs-12">
<form id="cf-task-form">
<section>
<div class="row form-group">
<div class="col-xs-3">
<label for="link">Link</label>
<input type="text" id="link" class="form-control" name="output[link]" required="true" pattern="^http.*">
</div>
<div class="col-xs-3">
<label for="address">Address</label>
<input id="address" class="form-control" name="output[address]" required="true" pattern=".*street.*">
</div>
<div class="col-xs-3">
<label for="research">Research</label>
<select id="research" name="output[research]">
<option value="0">0</option>
<option value="1">1</option>
</select>
</div>
<div class="col-xs-offset-6 col-xs-6">
<input type="button" class="btn sub-btn pull-right" id="submit-btn" value="Submit" tabindex="10">
</div>
</div>
</section>
</form>
</article>
</div>
<div class="clear"></div>
</div>
</div>
Note that the validation patterns are only for testing and not real patterns that should be used!
I used this page as reference: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation

If you want the required attribute to work, I think you need to change your last input type to "submit" :
<input type="submit" class="btn sub-btn pull-right" id="submit-btn" value="Submit" tabindex="10">
But I agree that it would be great to add some JS if you want to do proper form validation. I see some people shared useful links on the subject.

<form id="cf-task-form" onsubmit="return validateForm()">
const link = document.querySelector("#link").value
const Address = document.querySelector("#Address").value
const research = document.querySelector("#research").value
function validateForm() {
if (link == '') {
alert("filled out url");
return false;
}
else if (Address == '') {
alert("filled out Address");
return false;
}
else if (research == '') {
alert("filled out research");
return false;
}
}

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

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

ng-repeat with form in angularjs

I have created dynamic forms with ng-repeat directive. I am getting form field according to userid value. Once I have filled every field in form my add user button should be enabled. As of now its not enabled. I have attached my code below.
My html code:
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="myid in userid">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="myid" id="myid" name="myid" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="manualComment" id="textarea1" rows="1"></textarea>
</div>
<div class="col-md-3 ">
<label>Gender</label>
<select ng-model="gender" name="select2">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="!(myid && manualComment && gender)" type="button" id="adduser">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
</div>
my app.js file
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope) {
$scope.userid = [1, 2, 3]
});
How can I enable add user button once all field are filled?
Update:
If you want to convert your initial array from the server to a usage array check this fiddle
JSFiddle Demo
If you want an object which contains all the form values, please refer to the below fiddle!
JSFiddle Demo
Based on the statement below, this is my solution.
How can I enable add user button once all field are filled?
I have added the required attribute to all the input fields, the form name userForm is a variable in the scope. It has its validation variables, in my case I am using userForm.$invalid which will be true unless all the fields with required attribute are filled. The Add User is disabled by using the ng-disabled attribute, check the below JSFiddle for a demo.
JSFiddle Demo
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="myid in userid">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="myid" id="myid" name="myid" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="manualComment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Gender</label>
<select ng-model="gender" name="select2" required>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
</div>
</div>

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

ng-submit is not working

I HAVE A FORM BUT NG SBMIT DOESNOT CALL THE FUNCTION
I dont understand why this form not submitting . i have check every thing but it not even call the alert button also
HTML
<form role="form" name="frmCashback" method="post" ng-submit="CashbackUser(frmCashback, Rates)">
<!-- Personal Details Start -->
<div class="well">
<legend> Cashback Details </legend>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="Store">Store:</label>
<select name="Store" class="form-control" ng-model="Rates.Store" ng-options="stores.StoreID as stores.StoreName for stores in StoreList" >
<option value="">Select</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="Store">Category:</label>
<select name="Category" class="form-control" ng-model="Rates.Category" ng-options="Cate.CategoryID as Cate.CategoryName for Cate in CategoryList" >
<option value="">Select</option>
</select>
</div>
<!-- Modal -->
<!---------Model End-------->
</div>
<div class="col-md-4">
<div class="form-group">
<label for="usr">Cash Back Rate:</label>
<input type="text" class="form-control" name="Cashback" id="Cashback" ng-model="Rates.Cashback" required>
</div>
</div>
</div>
<!---------Model End-------->
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary" type="submit">Add Cashback</button>
</div>
</div>
</div>
<!-- Personal Details End -->
</form>
Here is my controller
CONTROLLER
$scope.CashbackUser = function(frm, Rates) {
alert('Hi');
//query_params.Status = CheckStatus.Action;
//console.log(Rates);
}
I have check :
function is within the controller
I am figthing with this for 4 hr kindly help me.
Your template seems to be having error ,form submit will not work if your template having error think so
<!---------Model End-------->
</div>
</div>
In your form, you can use this:
ng-submit="CashbackUser()"
And in your controller:
$scope.CashbackUser = function(){
console.log($scope.frmCashback);
console.log($scope.Rates);
}

Categories