pass the json object to angular form - javascript

[ https://drive.google.com/open?id=0B2PqgB8bPJ5xVmpjdTBOakdoTk0 ] this is the image link This is my ng-app and controller of my form:
<!DOCTYPE>
<html>
<head>
<title>Student EditForm</title>
<script src = "javascript/QueryData.js"></script>
<script src = "jquery/jquery-1.10.2.min.js"></script>
<script src = "jquery/jquery-ui.js"></script>
<script src = "angularjs/angular.min.js"></script>
<link rel = "stylesheet" href = "css/jquery-ui.css" />
<link rel = "stylesheet" href = "css/bootstrap.min.css" />
<style>
body{
background-color:#FFFFE0;
width: 1038px;
float: right;
}
form{
width: 400px;
margin: 60px 10px 10px 10px;
}
.form-control{
background-color:#FFFAFA;
}
#btn,#btn1{
margin-top: 10px;
background-color:#ADFF2F;
}
ul{
list-style-type: none;
margin: 0;
padding:0;
width: 25%;
height: 100%;
position: fixed;
background-color: #f1f1f1;
overflow: hidden;
border: 1px solid #000000;
}
li a.active {
background-color: #4CAF50;
color: white;
}
li a{
display: block;
color: white;
text-align: left;
padding: 14px 20px;
text-decoration: none;
}
li{
border-bottom: 1px solid black;
}
li a:hover{
background-color: red;
}
</style>
</head>
<body ng-app = "MyForm" ng-controller = "StudentControl as stdCtrl">
<div class = "content-container col-sm-3">
<table>
<nav>
<ul>
<li><a class = "active" href = "studentForm.html">Student-Registration</a></li>
<li><a class = "active" href = "studentDetails.html">Student-Details</a></li>
<li><a class = "active" href = "studentEdit.html">Student-Update</a></li>
</ul>
</nav>
</table>
</div>
<div class = "bodycontainer col-lg-9">
<form name = "logForm" class = "col-lg-12" novalidate ng-repeat = "x in fType" ng-submit = "stdCtrl.StudentCtrl()">
<input type = "hidden"
id = "studentid"
name = "studentid"
ng-model = "stdCtrl.stdId"
class = "form-control" />
<div class = "form-group col-lg-6">
<label>Firstname</label>
<input type = "text"
id = "first"
name = "fname"
ng-required = "true"
ng-model = "stdCtrl.fName"
class = "form-control"
autofocus
placeholder = "FirstName">{{x.firstname}}</input>
<span class = "help-block"
ng-show = "logForm.fname.$invalid && !logForm.fname.$pristine">FirstName Required</span>
</div>
<div class = "form-group col-lg-6">
<label>Lastname</label>
<input type = "text"
name = "lname"
ng-required = "true"
ng-model = "stdCtrl.lName"
class = "form-control"
placeholder = "LastName">{{x.lastname}}</input>
<span class = "help-block"
ng-show = "logForm.lname.$invalid && !logForm.lname.$pristine">LastName Required</span>
</div>
<div class = "form-group col-lg-12">
<label>Gender:&nbsp&nbsp&nbsp</label>
<input type="radio" name="gender" ng-model="stdCtrl.gender" value="male" required>Male{{x.gender}}</input>
<input type="radio" name="gender" ng-model="stdCtrl.gender" value="female" required>Female{{x.gender}}</input>
<span class = "help-block"
ng-show = "logForm.gender.$invalid && !logForm.gender.$pristine">Gender Required</span>
</div>
<div class = "form-group col-lg-6">
<label>Email</label>
<input type = "email"
name = "email"
ng-required = "true"
ng-model = "stdCtrl.Email"
class = "form-control"
placeholder = "Your Email" >{{x.email}}</input>
<span class = "help-block"
ng-show = "logForm.email.$invalid && !logForm.email.$pristine">Email Required</span>
</div>
<div class = "form-group col-lg-6">
<label>Fathername</label>
<input type = "text"
name = "fathername"
ng-required = "true"
ng-model = "stdCtrl.Fname"
class = "form-control"
placeholder = "Father's Name">{{x.fathername}}</input>
<span class = "help-block"
ng-show = "logForm.fathername.$invalid && !logForm.fathername.$pristine">FatherName Required</span>
</div>
<div class = "form-group col-lg-6">
<label>Mothername</label>
<input type = "text"
name = "mothername"
ng-required = "true"
ng-model = "stdCtrl.Mname"
class = "form-control"
placeholder = "Mother's Name"/>{{x.mothername}}
<span class = "help-block"
ng-show = "logForm.mothername.$invalid && !logForm.mothername.$pristine">MotherName Required</span>
</div>
<div class = "form-group col-lg-6">
<label>DOB</label>
<input type = "text"
id = "birthdayPicker"
name = "birthdy"
ng-required = "true"
ng-model = "stdCtrl.brthdy"
class = "form-control"
placeholder = "DOB-Date Of Birth">{{x.birthday}}</input>
<span class = "help-block"
ng-show = "logForm.birthdy.$invalid && !logForm.birthdy.$pristine">BirthDay Required</span>
</div>
<div class = "form-group col-lg-12">
<label>Home-Address</label>
<textarea name = "address"
ng-required = "true"
ng-model = "stdCtrl.address"
class = "form-control"
placeholder = "PresentAddress"
row = "10" cols = "50" >{{x.address}}</textarea>
<span class = "help-block"
ng-show = "logForm.address.$invalid && !logForm.address.$pristine">PresentAddress Required</span>
</div>
<div class = "form-group col-lg-6">
<label>10<sup>th</sup>-Percentage</label>
<input type = "number"
name = "ten"
ng-required = "true"
ng-model = "stdCtrl.tenth"
class = "form-control"
placeholder = "10th percentage">{{x.tenth}}</input>
<span class = "help-block"
ng-show = "logForm.ten.$invalid && !logForm.ten.$pristine">10th-percentage Required</span>
</div>
<div class = "form-group col-lg-6">
<label>12<sup>th</sup>-Percentage</label>
<input type = "number"
name = "twelve"
ng-required = "true"
ng-model = "stdCtrl.twelfth"
class = "form-control"
placeholder = "12th percentage">{{x.twelfth}}</input>
<span class = "help-block"
ng-show = "logForm.twelve.$invalid && !logForm.twelve.$pristine">12th-percentage Required</span>
</div>
<div class = "form-group col-lg-6">
<input type = "submit"
id = "btn"
ng-disabled = "!logForm.$valid"
name = "Nextpage"
class = "form-control"
value = "Update" />
</div>
<div id = "form-group" class = "col-lg-6">
<input type = "submit"
name = "Cancel"
id = "btn1"
ng-click = "CancelForm()"
ng-disabled = "!logForm.$valid"
class = "form-control"
value = "Cancel" />
</div>
</form>
</div>
<script>
var app = angular.module('MyForm',[])
app.controller('StudentControl',['$scope','$http',function($scope,$http){
this.StudentCtrl = function(){
alert("bye");
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var fType = JSON.parse(decodeURIComponent(this.StudentCtrl()['data']));
console.log(fType);
$scope.fType = fType;
}]);
$(function(){
$("#birthdayPicker").datepicker({
dateFormat: "yy-mm-dd",
yearRange: '1980:2017',
changeMonth: true,
changeYear: true
});
});
</script>
</body>
</html>
What Im trying to do is Im getting the json object data in the above code but I have no idea to how to assign to my form fields.
Please give a suggestion guys

Your variables are in $scope.stdCtrl, try to console.log that
this.StudentCtrl = function() {
console.log($scope.stdCtrl);
}
JSFiddle

Try to pass the object in ng-submit like this:
<form name = "logForm" class = "col-lg-12" novalidate ng-repeat = "x in fType" ng-submit = "stdCtrl.StudentCtrl(stdCtrl)">
Or
Why not simply define a function inside the StudentCtrl like this
$scope.submitFunc = function(stdCtrl){
console.log(stfCtrl);
}
And change your form tag like this:
<form name = "logForm" class = "col-lg-12" novalidate ng-repeat = "x in fType" ng-submit = "submitFunc(stdCtrl)">

Related

Add fileupload input fields inside multiple div at a same time according to radiobox selection

I have a input field that takes numeric inputs. Then i have a button which display the number of divs as per that input. after displaying div there is two radio-box buttons (paired end and single end) if I select paired end then i want two file upload fields in each divs. and if i select single end then i want only one file upload fields in each div.
I have tried but fileupload fields working on only first div.
function CreateText() {
var text = `<div class="row border-top py-3">
<div class="col-md-3">
<label">sample name *</label></br>
<input type="sample" id="sample" name="sample[]">
</div>
<div class="col-md-3" style="display:none" id="showsingle">
<div class="form-group">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename1[]">
</div>
</div>
<div class="col-md-3" style="display:none" id="showpair">
<div class="form-group">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename2[]">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename2[]">
</div>
</div>
<div class="col-md-3 d-grid">
<div class="form-group">
<button class="btn btn-danger remove_add_btn">Remove</button>
</div>
</div>
</div>`;
var textCount = document.getElementById('textInput').value;
var html = '';
for (var i = 0; i < $('#textInput').val(); i++) {
html = document.getElementById('divDynamicTexts').innerHTML;
document.getElementById('divDynamicTexts').innerHTML = html + text.replace('', i);
}
}
function onlyOne() {
let SradioBox = document.getElementById("singleradio"),
Sfileupload = document.getElementById("showsingle"),
PradioBox = document.getElementById("pairedradio"),
Pfileupload = document.getElementById("showpair");
if (SradioBox.checked == true) {
Sfileupload.style.display = "block",
Pfileupload.style.display = "none";
} else if (PradioBox.checked == true) {
Pfileupload.style.display = "block",
Sfileupload.style.display = "none";
} else {
Pfileupload.style.display = "none",
Sfileupload.style.display = "none";
}
};
$(document).ready(function() {
$(document).on('click', '.remove_add_btn', function(e) {
e.preventDefault();
let row_item = $(this).parent().parent().parent();
$(row_item).remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-center">
<input type="text" id="textInput" value="" />
<input type="button" id="" value="Create upload fields" onclick="CreateText();" />
<div class="col-md-4" id="filebutton">
<div class="form-group ">
<label for="form_need">Library Type *</label>
</br>
<div class="px-2">
<label for="myradio">Single end:</label>
<input type="radio" id="singleradio" name="check" onclick="onlyOne();">
<label for="myradio">Paired end:</label>
<input type="radio" id="pairedradio" name="check" onclick="onlyOne();">
</div>
</div>
</div>
</div>
<div id="divDynamicTexts"></div>
ID attributes must be unique. It would be better to remove the IDs altogether ( or change to dataset attributes perhaps ) and use a delegated event listener to process the various clicks related to the task of adding/removing dynamic elements.
In the code below all ID attributes were either removed entirely or changed to data-id type values.
To avoid the need to process different form file input fields at the server the file-input fields are named the same but have an index so can be identified more readily in PHP ( or whatever backend you have )
The delegated listener, because it is bound to the document, will work for all elements whether or not they are static or added dynamically and makes heavy use of the event.target property to help identify the element that invoked the event.
The label element was being used incorrectly previously. If the form-input is within the label then there is no need for the for="ID" syntax ( note that the ID should be the ID of the input element to which the label belongs! ) - as it was the label's appeared to have a for attribute which did not related to an element in the form!
Using querySelector and querySelectorAll you can easily identify nodes of interest within the DOM so button clicks or radio button selection can fire a query to find nodes that are relevant - thus simplifying the hiding/showing of the file input elements.
const strhtml = `
<div data-id="dynrow" class="row border-top py-3">
<div class="col-md-3">
<label>sample name *<input type="text" name="sample[]"></label>
</div>
<div class="col-md-3" style="display:none" data-id="single" data-role="file-field">
<div class="form-group">
<label>Upload file *<input type="file" name="filename[1]" /></label>
</div>
</div>
<div class="col-md-3" style="display:none" data-id="pair" data-role="file-field">
<div class="form-group ">
<label>Upload file *<input type="file" name="filename[1]" /></label>
<label>Upload file *<input type="file" name="filename[2]" /></label>
</div>
</div>
<div class="col-md-3 d-grid">
<div class="form-group">
<button class="btn btn-danger remove_add_btn" data-id='remove'>Remove</button>
</div>
</div>
</div>`;
const _radio = document.querySelectorAll('[type="radio"][data-id]');
const _bttn = document.querySelector('[type="button"][data-id="add"]');
const _div = document.querySelector('#divDynamicTexts');
const _input = document.querySelector('input[type="number"][data-id="textInput"]');
let choice = false;
let qty = false;
/*
Disable radio buttons and the "Create" button initially
and enable when changes are made in the correct sequence.
1: select quantity -> enable radio bttns
2: select single or double -> enable "create" bttn
3: click bttn, create as per radio selection
*/
_input.addEventListener('change', e => {
_radio.forEach(n => {
n.disabled = e.target.value > 0 ? false : true;
});
qty=e.target.value;
});
document.addEventListener('click', e => {
if (e.target instanceof HTMLInputElement && e.target.dataset.id != null) {
/*
set global "choice" variable
and enable "Create" bttn.
*/
if (e.target.type == 'radio') {
choice = e.target.dataset.id;
_bttn.disabled = false;
}
}
/*
If the "choice" has been made the radio
buttons will be enabled. Based on radio
button selected create new HTML and then
unhide the appropriate single/pair DIV
element
*/
if (choice && qty > 0 && e.target.type == 'button') {
_div.innerHTML = '';
for (let i = 0; i < qty; i++) _div.insertAdjacentHTML('afterbegin', strhtml);
let expr = `div[data-id="${choice}"]`;
document.querySelectorAll(expr).forEach(n => n.style.display = 'block');
}
/*
unchanged: delete DIV & contents when "Remove" bttn is clicked.
*/
if (e.target instanceof HTMLButtonElement && e.target.dataset.id != null) {
if (e.target.dataset.id == 'remove') {
_div.removeChild(e.target.closest('[data-id="dynrow"]'));
}
}
});
body {
font-family: arial;
}
label {
display: block;
}
.px-2 {
display: inline-block;
}
.px-2 label {
display: inline-block;
margin: 0.5rem;
}
h2 {
font-size: 1.1rem;
margin: 1rem 0 0 0;
display: inline-block;
width: auto;
}
.inline {
display: inline;
margin: 0 1rem 0 0;
}
#divDynamicTexts {
min-height: 1rem;
margin: 2rem auto
}
div.row {
padding: 0.5rem;
border: 1px dotted grey;
margin: 0.5rem;
}
div[data-id='single'] .form-group label {
background: aliceblue
}
div[data-id='pair'] .form-group label {
background: lightsteelblue
}
div[data-id] .form-group label {
outline: 1px solid grey;
padding: 0.5rem;
margin: 0.5rem 0
}
.bold {
font-weight: bold
}
[disabled]{
border:1px solid red;
outline:2px solid red;
background:rgba(255,0,0,0.25);
}
<div class='text-center'>
<label class='inline bold'>Quantity:<input type='number' data-id='textInput' /></label>
<div class='col-md-4'>
<div class='form-group'>
<h2>Library Type</h2>
<div class='px-2'>
<label>Single end: <input type='radio' data-id='single' name='check' disabled /></label>
<label>Paired end: <input type='radio' data-id='pair' name='check' disabled /></label>
</div>
</div>
</div>
<input type='button' data-id='add' value='Create upload fields' disabled />
</div>
<div id='divDynamicTexts'></div>

can't compare passwords in javascript

This is my code I've been working on for a couple of hours, I can't get it to compare the two passwords, it will submit the form even if the passwords don't match. It does not return any alert message either way. I've tried doing (pass1.value == pass2.value) too, it didn't work.
strong text alert ("Welcome");
function enableButton(){
if (document.getElementById("checkb").checked)
{
document.getElementById("btn").disabled = false;
}
else {
document.getElementById("btn").disabled = true;
}
}
function checkPassword() {
var pass1= document.getElementById("pw").value ;
var pass2= document.getElementById("pw2").value ;
if ( pass1 == pass2 )
{
alert ("Passwords match") ;
return true;
}
else {
alert ("Passwords do not match");
return false;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title> Sign up </title>
<link rel = "stylesheet" href = "registration.css">
<script src = "registration.js"></script>
<noscript> Sorry, your browser does not support Javascript! </noscript>
</head>
<body>
<header style = " background-color : #f0e68c" >
<div class = "logo">
<img src = "logo.png" style = "width : 130px ; height : 130px">
</div>
<ul class = "menu">
Home </li>
<li class = "menu1"> About us </li>
<li class = "menu1"> Blog </li>
<li class = "menu1"> Book an Appointment </li>
<li class = "menu1"> Contact us </li>
</ul>
<br>
</header>
<div class = "heading">
<h1> Sign Up </h1>
<div>
<div class = "form" align = "center">
<form>
<fieldset>
<div class = "left">
<label for = "fname"> First Name </label><br>
<input type = "text" id = "fname" name = "fname" required>
</div>
<div class = "left">
<label for = "lname"> Last Name </label><br>
<input type = "text" id = "lname" name = "lname" required>
</div>
<div class = "clear"> </div>
<div class = "left">
<label for = "email"> E-mail </label><br>
<input type = "email" id = "email" name = "email" required>
</div>
<div class = "clear"> </div>
<div class = "left">
<label for = "pw"> Password </label><br>
<input type = "password" id = "pw" min = "6" max = "25" pattern = "(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,25}" title="Password should contain Uppercase letters, lowercase letters, numbers, minimum 6 and maximum 25 characters " required>
</div>
<div class = "left">
<label for = "confpw"> Confirm password </label><br>
<input type = "password" id = "pw2" required>
</div>
<div class = "clear"> </div>
<input type = "checkbox" id = "checkb" name = "checkb" onclick = "enableButton()" required> I agree to the rules and privacy policy<br><br>
<input type = "checkbox"> I want to recieve updates by mail <br>
<input type = "checkbox"> Subscribe for monthly newsletter <br><br>
<div class = "clear"> </div>
<input type = "submit" id = "btn" value = "sign up">
</fieldset>
</form>
</div>
</html>
You are never calling checkPassword so the code never gets run, if you want to run that code when someone submits your form, you can use the following code.
document.querySelector('form').addEventListener('submit', function (e) {
//Prevent default behaviour
e.preventDefault();
//Check passwords
if (checkPassword()) {
this.submit();
}
});
You are calling the checkPassword function when the sign up button is clicked by user.
So you can't compare pass1 and pass2 when user information is submitted to the server.
In this case, you can solve to catch using JavaScript the event that handle by the sign up button, like this.
document.querySelector('form').addEventListener('submit', function (e) {
//Prevent default behaviour
e.preventDefault();
//Check passwords
if (checkPassword()) {
this.submit();
}
});
And you was wrong in HTML code.
<input type = "submit" id = "btn" value = "sign up">
If I fix your mistake, as allows.
<input type = "submit" id = "btn" value = "sign up">
// or
<button typpe="submit" id="btn"> sign up </button>
Good luck! see you again.

Script in jquery to valide a form not work

I made a form to insert a new product on my site, and i want to validate it with js, but it don't work and i don't know why.
I have no errors in the console but nothing of the code work. I use the same code to validate a login form and it works so i don't know why here not working.
If you can help me to find the mistakes
Here is the js
$(document).ready(function(){
const form = $('#form');
const title = $('#title');
const descr = $('#descr');
const budget = $('#budget');
form.submit(e => {
if(!checkInputs()){
e.preventDefault();
}
});
});
function checkInputs() {
const titleValue = $.trim(username.value);
const descrValue = $.trim(descr.value);
const budgetValue = $.trim(budget.value);
console.log(titleValue);console.log(descrValue);console.log(budgetValue);
let status = false;
if(titleValue === '') {
status = setErrorFor(title, 'Inserisci un titolo');
}else{
status = setSuccessFor(title);
}
if(descrValue === '') {
status = setErrorFor(descr, 'Inserisci una descrizione');
}else {
status = setSuccessFor(descr);
}
if(budgetValue === '') {
status = setErrorFor(budget, 'Inserisci un budget');
} else {
status = setSuccessFor(budget);
}
/*
if(category === '') {
status = setErrorFor(budget, 'Seleziona una categoria');
}else{
status = setSuccessFor(budget);
}*/
return status;
}
function setErrorFor(input, message) {
const formControl = $(input).parent();
const small = $(formControl).find('small');
$(formControl).prop('classList', 'form-control error');
small.append(message);
return false;
}
function setSuccessFor(input) {
const formControl = $(input).parent();
$(formControl).prop('classList', 'form-control success');
return true;
}
here is the html (i know it's long sorry):
<form action = "projects/post_project.php" method ="post" id="form">
<div class="form-control">
<div class = "legend">Scegli un titolo per il tuo progetto</div>
<div><input type="text" name="title" id="title" placeholder = "es. Sito web per una piccola impresa" rows="5"></div>
<small></small>
</div>
<div class="form-control">
<div class = "legend">Dicci di più sul tuo progetto</div>
<div><textarea rows = "5" id = "descr" type="text" name="descr" placeholder = "Descrivi il tuo progetto"></textarea></div>
<small></small>
</div>
<div class="form-control">
<div class = "legend">Qual è il tuo budget?</div>
<select name="budget" id="budget">
<option>0€ - 250€</option>
<option>250€ - 750€</option>
<option>750€ - 1500€-</option>
<option>1500€ - 3000€</option>
<option>3000€ - 5000€</option>
<option>+ 5000€</option>
</select>
<small></small>
</div>
<!-- Pulsanti per scegliere la categoria -->
<div class = "legend">In che categoria inseriresti il tuo progetto? </div>
<small></small>
<div class = "category-list">
<input type = "radio" name = "category" value = "web" id = "radio1">
<label class = "category" for = 'radio1'>
<img class = "menu-icon" src = "img/web.png">
<span>Web</span>
</label>
<input type = "radio" name = "category" value = "app" id = "radio2">
<label class = "category" for = 'radio2'>
<img class = "menu-icon" src = "img/app.png">
<span>App</span>
</label>
<input type = "radio" name = "category" value = "database" id = "radio3">
<label class = "category" for = 'radio3'>
<img class = "menu-icon" src = "img/database.png">
<span>Database</span>
</label>
</div>
<div class = "category-list">
<input type = "radio" name = "category" value = "software" id = "radio4">
<label class = "category" for = 'radio4'>
<img class = "menu-icon" src = "img/software.png">
<span>Software</span>
</label>
<input type = "radio" name = "category" value = "sistemi" id = "radio5">
<label class = "category" for = 'radio5'>
<img class = "menu-icon" src = "img/sistemi.png">
<span>Sistemi</span>
</label>
<input type = "radio" name = "category" value = "altro" id = "radio6">
<label class = "category" for = 'radio6'>
<img class = "menu-icon" src = "img/other.png">
<span>Altro</span>
</label>
</div>
<!-- Fine pulsanti categoria -->
<div class = "btn"><input type="submit" value="Pubblica"></div>
</form>
here is the css:
.form-control.success input {
border-color: #2ecc71;
}
.form-control.error input {
border-color: #e74c3c;
}
.form-control small {
color: #e74c3c;
font-size: 11pt;
bottom: 0;
left: 0;
visibility: hidden;
}
.form-control.error small {
visibility: visible;
}
As mentioned in my comment, you define status as false and then use a number of IF statements to check for empty fields. As you perform each check, status gets updated to a new value. This means that regardless of the other checks, the last check is the only one that counts. With 3 checks it might be like:
status = false;
status = false;
status = true;
So the result would be true.
Consider the following code.
$(function() {
var form = $('#form');
var title = $('#title');
var descr = $('#descr');
var budget = $('#budget');
function checkInputs() {
var titleValue = title.val().trim();
var descrValue = descr.val().trim();
var budgetValue = budget.val().trim();
var status = true;
if (titleValue === '') {
status = status && setErrorFor(title, 'Inserisci un titolo');
} else {
status = status && setSuccessFor(title);
}
if (descrValue === '') {
status = status && setErrorFor(descr, 'Inserisci una descrizione');
} else {
status = status && setSuccessFor(descr);
}
if (budgetValue === '') {
status = status && setErrorFor(budget, 'Inserisci un budget');
} else {
status = status && setSuccessFor(budget);
}
console.log("Status", status);
return status;
}
function setErrorFor(input, message) {
var formControl = $(input).parent();
var small = $("small", formControl);
$(formControl).prop('classList', 'form-control error');
small.append(message);
return false;
}
function setSuccessFor(input) {
const formControl = $(input).parent();
$(formControl).prop('classList', 'form-control success');
return true;
}
form.submit(e => {
if (!checkInputs()) {
e.preventDefault();
}
});
});
.form-control.success input {
border-color: #2ecc71;
}
.form-control.error input {
border-color: #e74c3c;
}
.form-control small {
color: #e74c3c;
font-size: 11pt;
bottom: 0;
left: 0;
visibility: hidden;
}
.form-control.error small {
visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="projects/post_project.php" method="post" id="form">
<div class="form-control">
<div class="legend">Scegli un titolo per il tuo progetto</div>
<div><input type="text" name="title" id="title" placeholder="es. Sito web per una piccola impresa" rows="5"></div>
<small></small>
</div>
<div class="form-control">
<div class="legend">Dicci di più sul tuo progetto</div>
<div><textarea rows="5" id="descr" type="text" name="descr" placeholder="Descrivi il tuo progetto"></textarea></div>
<small></small>
</div>
<div class="form-control">
<div class="legend">Qual è il tuo budget?</div>
<select name="budget" id="budget">
<option>0€ - 250€</option>
<option>250€ - 750€</option>
<option>750€ - 1500€-</option>
<option>1500€ - 3000€</option>
<option>3000€ - 5000€</option>
<option>+ 5000€</option>
</select>
<small></small>
</div>
<!-- Pulsanti per scegliere la categoria -->
<div class="legend">In che categoria inseriresti il tuo progetto? </div>
<small></small>
<div class="category-list">
<input type="radio" name="category" value="web" id="radio1">
<label class="category" for='radio1'><img class = "menu-icon" src = "img/web.png"><span>Web</span></label>
<input type="radio" name="category" value="app" id="radio2">
<label class="category" for='radio2'><img class = "menu-icon" src = "img/app.png"><span>App</span></label>
<input type="radio" name="category" value="database" id="radio3">
<label class="category" for='radio3'><img class = "menu-icon" src = "img/database.png"><span>Database</span></label>
</div>
<div class="category-list">
<input type="radio" name="category" value="software" id="radio4">
<label class="category" for='radio4'><img class = "menu-icon" src = "img/software.png"> <span>Software</span></label>
<input type="radio" name="category" value="sistemi" id="radio5">
<label class="category" for='radio5'><img class = "menu-icon" src = "img/sistemi.png"><span>Sistemi</span></label>
<input type="radio" name="category" value="altro" id="radio6">
<label class="category" for='radio6'><img class = "menu-icon" src = "img/other.png"><span>Altro</span></label>
</div>
<!-- Fine pulsanti categoria -->
<div class="btn"><input type="submit" value="Pubblica"></div>
</form>
You might also consider performing the check on blur event so the User gets feedback as they move through the form.
$(function() {
var form = $('#form');
var errs = {
title: 'Inserisci un titolo',
descr: 'Inserisci una descrizione',
budget: 'Inserisci un budget',
};
function isEmpty(el) {
return $(el).val().length === 0;
}
function showError(el) {
var formControl = $(el).closest(".form-control");
formControl.removeClass("success").addClass("error");
$("small", formControl).html(errs[$(el).attr("id")]);
}
function hideError(el) {
var formControl = $(el).closest(".form-control");
formControl.removeClass("error").addClass("success");
$("small", formControl).html("");
}
$("#title, #descr, #budget").blur(function(e) {
var formControl = $(this).parent();
var id = $(this).attr("id");
if (isEmpty(this)) {
formControl.addClass("error");
showError(this);
} else {
formControl.addClass("success");
hideError(this);
}
});
});
.form-control.success input,
.form-control.success textarea,
.form-control.success select {
border-color: #2ecc71;
}
.form-control.error input,
.form-control.error textarea,
.form-control.error select {
border-color: #e74c3c;
}
.form-control small {
color: #e74c3c;
font-size: 11pt;
bottom: 0;
left: 0;
visibility: hidden;
}
.form-control.error small {
visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="projects/post_project.php" method="post" id="form">
<div class="form-control">
<div class="legend">Scegli un titolo per il tuo progetto</div>
<div>
<input type="text" name="title" id="title" placeholder="es. Sito web per una piccola impresa" rows="5">
</div>
<small></small>
</div>
<div class="form-control">
<div class="legend">Dicci di più sul tuo progetto</div>
<div>
<textarea rows="5" id="descr" type="text" name="descr" placeholder="Descrivi il tuo progetto"></textarea>
</div>
<small></small>
</div>
<div class="form-control">
<div class="legend">Qual è il tuo budget?</div>
<select name="budget" id="budget">
<option></option>
<option>0€ - 250€</option>
<option>250€ - 750€</option>
<option>750€ - 1500€-</option>
<option>1500€ - 3000€</option>
<option>3000€ - 5000€</option>
<option>+ 5000€</option>
</select>
<small></small>
</div>
<!-- Pulsanti per scegliere la categoria -->
<div class="legend">In che categoria inseriresti il tuo progetto? </div>
<small></small>
<div class="category-list">
<input type="radio" name="category" value="web" id="radio1">
<label class="category" for='radio1'><img class = "menu-icon" src = "img/web.png"><span>Web</span></label>
<input type="radio" name="category" value="app" id="radio2">
<label class="category" for='radio2'><img class = "menu-icon" src = "img/app.png"><span>App</span></label>
<input type="radio" name="category" value="database" id="radio3">
<label class="category" for='radio3'><img class = "menu-icon" src = "img/database.png"><span>Database</span></label>
</div>
<div class="category-list">
<input type="radio" name="category" value="software" id="radio4">
<label class="category" for='radio4'><img class = "menu-icon" src = "img/software.png"> <span>Software</span></label>
<input type="radio" name="category" value="sistemi" id="radio5">
<label class="category" for='radio5'><img class = "menu-icon" src = "img/sistemi.png"><span>Sistemi</span></label>
<input type="radio" name="category" value="altro" id="radio6">
<label class="category" for='radio6'><img class = "menu-icon" src = "img/other.png"><span>Altro</span></label>
</div>
<!-- Fine pulsanti categoria -->
<div class="btn"><input type="submit" value="Pubblica"></div>
</form>

email Border style won't work for form validation in javascript?

I'm making a form validation in javascript, Everything works fine but the border style won't work for the email validation, The image validation works flawlessly but the only problem I'm having is the email part. This is my code:
function validate()
{
var email = document.getElementById('name').value;
var img = document.getElementById("image");
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if (!pattern.test(email)) {
var myDiv = document.getElementById("error");
email.style.border = "solid 3px red";
myDiv.innerHTML = '<font face = "fantasy" size="4" color = "red">Please Enter an valid Email</font>';
return false;
} else if (img.value.trim()=="") {
var myDiv = document.getElementById("error");
img.style.border = "solid 3px red";
myDiv.innerHTML = '<font face = "fantasy" size="4" color = "red">Please Select an image</font>';
return false;
}
}
EDIT: This is also my HTML code that I did.
<div class="container">
<div class="add-form">
<form method="post" enctype="multipart/form-data" id="FormID">
<div class="well well-sm"><strong>Username</strong></div>
<label for = "name" id = "LabelName"><font size = "5">
<img alt = "Fix audits" src = "https://image.flaticon.com/icons/png/512/1233/1233986.png" width = "50">
<br>
</label>
<input class = "UsernameUpload form-control" id = "name" type="text" name="user_name"></font>
<div id = "space"><br></div>
<div class="well well-sm"><strong>Image</strong></div>
<label for = "image" id = "fileLabel"
ondragover = "overrideDefault(event);fileHover();"
ondragenter = "overrideDefault(event);fileHover();"
ondragleave = "overrideDefault(event);fileHoverEnd();"
ondrop = "overrideDefault(event);fileHoverEnd();addFiles(event);">
<font face = "fantasy" size = "5">
<img alt = "Fix audits" src = "https://image.flaticon.com/icons/png/512/1180/premium/1180674.png" width = "50">
<br>
<span id = "fileLabelText">Select image to upload</font></span>
<br>
</label>
<div class = "upload-area" id = "uploadfile"><h1>Drag and Drop File Here</h1></div>
<input multiple onchange = "addFiles(event)" id = "image" type="file" onchange ="unlock()" name="profile" class="form-control2" accept="*/image">
<button class = "btn btn-info uploadButton" type="submit" value = "submit" name="btn-add" onClick = "return validate()" action = "index.php"><font face = "calibri" size = "4">upload</font></button>
<div id = "error"><font face = "fantasy">Please fill up the username and select an image</font></div>
<progress id = "progressBar" value = "0" max = "100" style = "width:300px;"></progress>
<h3 id = "status"></h3>
<p id = "loaded_n_total"></p>
</form>
</div>
<hr style="border-bottom: 5px blue solid;">
</div>
</div>
Firstly there is:
var email = document.getElementById('name').value;
Your error is here:
email.style.border = ...
email is a string, not an element, it doesn't have a style property so an error is thrown when attempting to access the border property of undefined.
A console error message should have alerted you to that.
The button[type="submit"] is used within the form tag, which will submit form values and reload the page. Use e.preventDefault, to prevent it's default action.
var email = document.getElementById('name').value;-> the email variable have value, so the statement email.style.border = "solid 3px red"; will throw error, as it is not an element.
function validate(e) {
e.preventDefault();
var email = document.getElementById('name');
var img = document.getElementById("image");
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if (!pattern.test(email.value)) {
var myDiv = document.getElementById("error");
email.style.border = "solid 3px red";
myDiv.innerHTML = '<font face = "fantasy" size="4" color = "red">Please Enter an valid Email</font>';
return false;
} else if (img.value.trim() == "") {
var myDiv = document.getElementById("error");
img.style.border = "solid 3px red";
myDiv.innerHTML = '<font face = "fantasy" size="4" color = "red">Please Select an image</font>';
return false;
}
}
<div class="container">
<div class="add-form">
<form method="post" enctype="multipart/form-data" id="FormID">
<div class="well well-sm"><strong>Username</strong></div>
<label for="name" id="LabelName"><font size = "5">
<img alt = "Fix audits" src = "https://image.flaticon.com/icons/png/512/1233/1233986.png" width = "50">
<br>
</label>
<input class="UsernameUpload form-control" id="name" type="text" name="user_name" value="" />
<div id="space"><br></div>
<div class="well well-sm"><strong>Image</strong></div>
<label for="image" id="fileLabel" ondragover="overrideDefault(event);fileHover();" ondragenter="overrideDefault(event);fileHover();" ondragleave="overrideDefault(event);fileHoverEnd();" ondrop="overrideDefault(event);fileHoverEnd();addFiles(event);">
<font face = "fantasy" size = "5">
<img alt = "Fix audits" src = "https://image.flaticon.com/icons/png/512/1180/premium/1180674.png" width = "50">
<br>
<span id = "fileLabelText">Select image to upload</font></span>
<br>
</label>
<div class="upload-area" id="uploadfile">
<h1>Drag and Drop File Here</h1>
</div>
<input multiple onchange="addFiles(event)" id="image" type="file" onchange="unlock()" name="profile" class="form-control2" accept="*/image">
<button class="btn btn-info uploadButton" type="submit" value="submit" name="btn-add" onClick="return validate(event)" action="index.php"><font face = "calibri" size = "4">upload</font></button>
<div id="error">
<font face="fantasy">Please fill up the username and select an image</font>
</div>
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</div>
<hr style="border-bottom: 5px blue solid;">
</div>
</div>
Note - id with name as value is not an appropriate name as pointed out by #RobG. If the field holds email value, the id="email" would be more appropriate.

how to check dynamically if user hasn't deleted value from textarea

I want to make buttons enable when all textboxes have values and radiobutton is checked.
It works, as long as I don't try to delete some values. Then one of textboxes is empty but buttons are still enable, while I want them to be disable. how to change it?
<body>
<h2>#ViewBag.Title.</h2>
<div class="row">
<div class="col-md-8">
<section>
#using (Html.BeginForm("Add", "Question", new {ReturnUrl = ViewBag.ReturnUrl}, FormMethod.Post, new {#class = "form-horizontal", role = "form"}))
{
#Html.AntiForgeryToken()
<h4>//</h4>
<hr/>
#Html.ValidationSummary(true, "", new {#class = "text-danger"})
#Html.TextAreaFor(m => m.QuestionContent, new {#class = "form-control", #rows = "7", #cols = "50", #id= "a", #type = "textarea" })
#Html.TextAreaFor(m => m.AnswerA, new {#class = "form-control", #rows = "7", #cols = "50", #style = "margin-top: 15px", #id = "a", #type = "input" })
#Html.TextAreaFor(m => m.AnswerC, new {#class = "form-control", #rows = "7", #cols = "50", #style = "margin-top: 15px",#id = "a", #type = "input" })
#Html.TextAreaFor(m => m.AnswerD, new {#class = "form-control", #rows = "7", #cols = "50", #style = "margin-top: 15px; margin-bottom: 30px", #id = "a", #type = "input" })
#Html.RadioButtonFor(m => m.CorrectAnswer, "a", new {#type="radio"})
#Html.RadioButtonFor(m => m.CorrectAnswer, "b", new { #type = "radio" })
#Html.RadioButtonFor(m => m.CorrectAnswer, "c", new { #type = "radio" })
#Html.RadioButtonFor(m => m.CorrectAnswer, "d", new { #type = "radio" })
<input id="addNewQuestion" type="submit" value="Dodaj nowe pytanie" class="btn btn-default" style="margin-top: 30px; margin-left: -80px !important"/>
<input id="finish" type="submit" name="AddAndFinish" value="Zakończ dodawanie testu" formaction="AddAndFinish" class="btn btn-default" style="margin-top: 30px; margin-left: 10px !important"/>
</div>
</div>
</div>
}
</section>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('input[type="submit"]').attr('disabled', true);
$('input[type="text"],textarea').on('keyup', function () {
var questionContentValue = $("#questionContentArea").val();
var answerAValue = $('input[name="ans_a"]').val();
var answerBValue = $('input[name="ans_b"]').val();
var answerCValue = $('input[name="ans_c"]').val();
var answerDValue = $('input[name="ans_d"]').val();
var clicked = false;
$('[type="radio"]').change(function() {
clicked = true;
if ((questionContentValue != '') && (answerAValue != '') && (answerBValue != '') && (answerCValue != '') && (answerDValue != '')&& clicked == true) {
$('input[type="submit"]').attr('disabled', false);
} else {
$('input[type="submit"]').attr('disabled', true);
}
});
});
});
</script>
</body>
There're also other stufs in code to make my html look good, but they're not important.
I think this will work for you. I've updated it to include radio buttons and closer match your example's selectors and what you're doing. This might be more straightforward for you to incorporate into your document ready() function.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function disableButtons() {
$("input[type='submit']").attr("disabled", true);
}
function enableButtons() {
$("input[type='submit']").attr("disabled", false);
}
$(document).ready(function() {
//start with buttons disabled.
disableButtons();
var $textInputs = $('input[type="text"],textarea');
//when any inputs/textareas change, re-evaluate all inputs and toggle buttons appropriately
$('input,textarea').on('change', function() {
//filter text inputs to the empty ones and see if there are any
var anyEmpty = $textInputs.filter(function() { return this.value == ""; }).length > 0;
//see if any radio buttons are selected
var anyClicked = $('input[type="radio"]:checked').length > 0;
if (!anyEmpty && anyClicked) {
enableButtons();
} else {
disableButtons();
}
});
});
</script>
</head>
<body>
<div><input type="text" name="input1" value="" class="input"></div>
<div><input type="text" name="input2" value="" class="input"></div>
<div><textarea name="input3" rows="8" cols="80" class="input"></textarea></div>
<div>
<input type="radio" name="radioInput" value="Radio 1">
<input type="radio" name="radioInput" value="Radio 2">
</div>
<div class="buttons">
<input type="submit" name="button1" class="button" value="Submit 1" />
<input type="submit" name="button2" class="button" value="Submit2" />
</div>
</body>
</html>

Categories