I am creating an onlineshop and I want to use Javascript ( I think) or JQuery, in order when the user is entering details for adding a new product into the database, like:
-Title (TEXT)
-Price (FLOAT)
-Description (TEXT)
-Quantity Available (INT)
How to set a check to occur and inform the user that he has an incorrect data type for a specific field? Because now my database lets the user add whatever he wants, and at the preview of the product the field price shows "£0". Also, if the check completes for all the fields and is okay, a message will be shown that it okay.
code below
<div id="addForm">
<div id="formHeading"><h2>Add Product</h2></div><p>
<p>
<form id = "additems" action="../cms/insert.php" enctype="multipart/form-data" method="post"/>
<div id="formContents">
<label for="title">Title of your product:
<div id="formContents"> </label><input type="text" name="title" style="width: 180px" onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue"
value=" title of your product here" maxlength="19" /><p>
</div>
<div id="formContents">
<label for="description">Description of your product:
<div id="formContents"> </label><input type="text" name="description" style="width: 180px" onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue"
value="description of the product" maxlength="19" /><p>
</div>
<label for="price">Price: £ </label><input type="INT" name="price" style="width: 40px" /><p>
<label for="stock">Quantity:</label><input type="text" name="stock" style="width: 40px" />
<p>
</div>
you can do it two ways:
prevent him from entering anything other than intended characters :
for example , for fields that would have INT values :
$('.nonly').bind('keyup blur',function(){$(this).val($(this).val().replace(/[^0-9]/g,''));});
validate after entering :
var intRegex = /^\d+$/;
var cellphone = $('#register_phonenum');
if ((cellphone.val()=='')||(!intRegex.test(cellphone.val()))) {
/* do something*/
return false;
}
Related
The problem
I use a form on a webpage where users fill in all sorts of details. There are 3 fields which generate the input for another field. That field gets generated like this: Firstname + Lastname + Date of birth. However, when a validation error is thrown on the form and the page reloads, the generated input isn't the expected format anymore. Only the Date of birth is then in that input.
It looks like it isn't initializing the Firstname + Lastname field anymore after a validation error is thrown on the page. Any suggestions on how to make it so that the fields gets initialized constantly? Or is there maybe a better way to handle this?
This is the code I use for the generated input
window.onload = function() {
let studentNoField = document.getElementById('input_7_9');
let enteredDetails = {
name: '',
lastname: '',
date: ''
};
/* set value in the third input: Studentnummer */
function generateInput() {
let studentNumber = Object.values(enteredDetails).join('').toLowerCase();
studentNoField.value = studentNumber;
}
/* event listener for first input: Voornaam */
document.getElementById('input_7_1').addEventListener('input', function(event) {
enteredDetails.name = event.target.value.replace(/\s/g, '').slice(0, 8);
generateInput();
});
/* event listener for second input: Achternaam */
document.getElementById('input_7_25').addEventListener('input', function(event) {
enteredDetails.lastname = event.target.value.replace(/\s/g, '').slice(0, 8);
generateInput();
});
/* event listener for second input: Date */
document.getElementById('input_7_3').addEventListener('input', function(event) {
enteredDetails.date = event.target.value.replace(/-/g, '').slice(0, 4);
generateInput();
});
/* Get selected training and format it properly for the PDF */
jQuery('#input_7_23').change(function(e) {
var optionChange = jQuery('#input_7_23 option:selected').text().toUpperCase();
jQuery('#input_7_58').val(optionChange);
});
}
<html>
<body>
<form method="post" enctype="multipart/form-data" id="gform_7" action="/budget/" _lpchecked="1">
<div>
<div id="gform_fields_7">
<div id="field_7_9">
<label for="input_7_9">Studentnummer
<input name="input_9" id="input_7_9" type="text" value="" maxlength="20" aria-required="true" aria-invalid="false">
</div>
</div>
<div id="field_7_1">
<label for="input_7_1">Voornaam</label>
<div><input name="input_1" id="input_7_1" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_25">
<label for="input_7_25">Achternaam</label>
<div><input name="input_25" id="input_7_25" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_3">
<label for="input_7_3">Geboortedatum</label>
<div>
<input name="input_3" id="input_7_3" type="text" value="" placeholder="dd-mm-yyyy" aria-describedby="input_7_3_date_format" aria-invalid="false" aria-required="true">
<span id="input_7_3_date_format">DD dash MM dash JJJJ</span>
</div>
</div>
</div>
</div>
<div>
<input type="submit" id="gform_submit_button_7" value="Versturen" onclick="if(window["gf_submitting_7"]){return false;} window["gf_submitting_7"]=true; " onkeypress="if( event.keyCode == 13 ){ if(window["gf_submitting_7"]){return false;} window["gf_submitting_7"]=true; jQuery("#gform_7").trigger("submit",[true]); }">
</div>
</form>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Any help or suggestions is appreciated.
There were a few non-existing ids referenced in your code. In the following snippet I have tried to "correct" these errors, but I also went further: I removed all repetitions, thereby following the DRY principle "Don't repeat yourself". The "input"-event listener now works for all elements of the inps array. There is, however one differentiation: the first two elements are limited to 8 characters while the date is limited to 4: .slice(0,i<2?8:4).
const [stNr, ...inps]=[9, 1, 25, 3].map(n=> document.getElementById(`input_7_${n}`));
inps.forEach(inp=>inp.addEventListener("input",()=>
stNr.value=inps.map((el,i)=>
el.value.replace(/[\s-]/g,"").slice(0,i<2?8:4).toLowerCase()
).join(""))
)
<form method="post" enctype="multipart/form-data" id="gform_7" action="/budget/" _lpchecked="1">
<div>
<div id="gform_fields_7">
<div id="field_7_9">
<label for="input_7_9">Studentnummer</label>
<input name="input_9" id="input_7_9" type="text" value="" maxlength="20" aria-required="true" aria-invalid="false">
</div>
</div>
<div id="field_7_1">
<label for="input_7_1">Voornaam</label>
<div><input name="input_1" id="input_7_1" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_25">
<label for="input_7_25">Achternaam</label>
<div><input name="input_25" id="input_7_25" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_3">
<label for="input_7_3">Geboortedatum</label>
<div>
<input name="input_3" id="input_7_3" type="text" value="" placeholder="dd-mm-yyyy" aria-describedby="input_7_3_date_format" aria-invalid="false" aria-required="true">
<span id="input_7_3_date_format">DD dash MM dash JJJJ</span>
</div>
</div>
</div>
</div>
<div>
<input type="submit" id="gform_submit_button_7" value="Versturen">
</div>
</form>
I removed your jQuery statements at the end of your script, as they referred to non-existent ids. These statements can definitely also be re-written in Vanilla JS, if necessary.
And, as #CherryDT already mentioned: there is no validation code visible here. If it happens on the server then it is the server's responsibility to produce a suitable response that allows the client to render the page with the previously (possibly annotated) content.
I am developing a system for equipment rental in PHP.
I need to send a form that contains the id, quantity, time and value fields of the selected equipment.
Each rent can have N equipments, consequently N amount of fields.
How do I do this? Do I generate the fields by javascript? To send, an array for each piece of equipment?
It would be something like that:
<input type='text' name='equipment[]'>
<input type='text' name='quantity[]'>
<input type='text' name='time[]'>
But how would I do it like this:
array(array[0](equipment=>1,quantity=>2,time=>4),array[1](equipment=>2,quantity=>2,time=>4),array[2](equipment=>1,quantity=>2,time=>4));
I think you could group by rental doing like this:
<div id="rental_group_1">
<input type="text" name="rent_1[]" id="equipment_1">
<input type="text" name="rent_1[]" id="quantity_1">
<input type="text" name="rent_1[]" id="time_1">
</div>
<div id="rental_group_2">
<input type="text" name="rent_2[]" id="equipment_2">
<input type="text" name="rent_2[]" id="quantity_2">
<input type="text" name="rent_2[]" id="time_2">
</div>...
This way you will get on Post an array per group so:
$rent_1[0] = equipment_1
$rent_1[0] = quantity_1
$rent_1[0] = time_1
...
Adding this to #Blesson Christy solution will create a good UI/UX for what you want.
Hope it helps! :D
A small example :
HTML:
<div id="content">
<input type="text" class="fieldone" id="fields_1" name="fields[]"/>
</div><input type="button" id="addmore" />
Jquery:
counter=1;
$(document).on('click','#addmore',function(){
counter++;
var htmltoadd='<input type="text" class="fieldone" id="fields_"'+counter+' name="fields[]"/>';
$("#content").append(htmltoadd);
});
You need to include jquery in this example.
I have optin popup of two steps, first step is to capture email and name, when user click submit the data is captured, and another popup appears, the new popup has a form with more fields to get more info, plus email and name field.
what I want to do is to automatically populate the email and name field from first popup and hide them with display:none so user can't see them, after submit the data is captured again (all goes to activecampaign).
the two forms works just fine, what is not working is saving the data and calling it when needed
here is the js I'm using
jQuery(function($){
// PART I: Saving user details locally
$('#arlington-field-submit').on('click', function(){
// check if the user's browser has localStorage support
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// store the full name in localStorage
var fullname = document.querySelector("input[name=arlington-name]");
localStorage.user_name = fullname.value;
// save the email in localStorage
var email = document.querySelector("input[name=arlington-email]");
$("input[name=fullname]").val(localStorage.getItem("server"));
localStorage.user_email = email.value;
}
});
// PART II: Pre-filling forms forms with locally saved values
if (typeof(Storage) !== "undefined") {
// check if the user has a name field stored
if (localStorage.user_name) {
name_field = document.querySelector("._form input[name=fullname]");
name_field.value = localStorage.user_name;
}
// check if the user has an email field stored
if (localStorage.user_email) {
email_field = document.querySelector("._form input[name=email]");
email_field.value = localStorage.user_email;
}
}
});
first form html:
<div id="arlington-element-form" class="arlington-element-form arlington-element" data-element="form">
<div id="arlington-form" class="arlington-form arlington-has-name-email arlington-has-buttons">
<div class="arlington-form-wrap"><input id="arlington-field-comments" name="arlington-comments" type="text" data-selectable="true" data-target="#builder-setting-comments_value" class="arlington-field-comments" placeholder="" value="" style="" autocomplete="off"><input id="arlington-field-name" name="arlington-name" type="text" data-selectable="true" data-target="#builder-setting-name_value" class="arlington-field-name" placeholder="Enter your name here..." value="">
<input id="arlington-field-email" name="arlington-email" type="email" data-selectable="true" data-target="#builder-setting-email_value" class="arlington-field-email" placeholder="Enter your email address here..." value="" >
<input id="arlington-field-submit" name="arlington-submit" type="submit" data-selectable="true" data-target="#builder-setting-submit_value" class="arlington-field-submit" value="JOIN NOW" >
</div>
<div class="arlington-yesno-wrap">
<button id="arlington-button-yes" type="button" name="arlington-yes" data-selectable="true" data-target="#builder-setting-yes_value" data-action="form" data-type="yes" class="arlington-button-yes arlington-button-yesno">Submit!</button>
</div></div></div>
second form html:
<form method="POST" action="xxxxxx" id="_form_8_" class="_form _form_8 _inline-form _dark" novalidate> <input type="hidden" name="u" value="8" /> <input type="hidden" name="f" value="8" /> <input type="hidden" name="s" /> <input type="hidden" name="c" value="0" /> <input type="hidden" name="m" value="0" /> <input type="hidden" name="act" value="sub" /> <input type="hidden" name="v" value="2" />
<div class="_form-content">
<div class="_form_element _x72304349 _full_width "> <label class="_form-label"> Full Name </label>
<div class="_field-wrapper"> <input type="text" name="fullname" placeholder="Type your name" /> </div>
</div>
<div class="_form_element _x10201592 _full_width "> <label class="_form-label"> Email* </label>
<div class="_field-wrapper"> <input type="text" name="email" placeholder="Type your email" required/> </div>
</div>
<div class="_form_element _x29901314 _full_width "> <label class="_form-label"> Phone </label>
<div class="_field-wrapper"> <input type="text" name="phone" placeholder="Type your phone number" /> </div>
</div>
<div class="_button-wrapper _full_width"> <button id="_form_8_submit" class="_submit" type="submit"> Submit </button> </div>
<div class="_clear-element"> </div>
</div>
</form>
Since the input which is being clicked is a submit button, chances are that the page is navigating before the JS within the click handler gets a chance to fire.
Try and replace
$('#arlington-field-submit').on('click', function(){
with:
$('#_form_8_').on('submit', function(event){
Then you can prevent the form from actually submitting so your JS can run:
$('#_form_8_').on('submit', function(event){
event.preventDefault();
// Do localStorage stuff
$(this).submit(); // submit the form normally after localStorage is saved
});
The way you look for elements is wrong, because you forgot quotes wrapping attribute values:
var fullname = document.querySelector("input[name=arlington-name]");
should be:
var fullname = document.querySelector('input[name="arlington-name"]');
And so on...
BTW I'm surprised you don't report an error like "An invalid or illegal string was specified".
I have a row in my form for a user to enter a 6 digit unique ref. This is split up into 3 fields which each only allow 2 characters. What i'm after is that when the user has entered 2 characters, I want the focus to automatically move to the next field.
The functionality though also needs to support the use of tab back in case the user has entered an incorrect digit so they don't need to manually click in the field.
HTML
<div class="col-sm-5 form-inline">
<input name="RefBox1" type="text" class="form-control" id="RefBox1" style="width: 40px;" type="text" maxlength="2" ng-model="updateRef1" restrictinput="[^0-9\s]" required> -
<input name="RefBox2" type="text" class="form-control" id="RefBox2" style="width: 40px;" type="text" maxlength="2" ng-model="updateRef2" restrictinput="[^0-9\s]" required> -
<input name="RefBox3" type="text" class="form-control" id="RefBox3" style="width: 40px;" type="text" maxlength="2" ng-model="updateRef3" restrictinput="[^0-9\s]" required>
</div>
As I don't know how to do this I don't have any code in my controller.
This method of moving to the nextElementSibling on maxLength works with plain-old-javascript. I'm guessing that you could adapted it to your AngularJS controller. And to support older browsers (IE<9) see: Portability of nextElementSibling/nextSibling
<html>
<body>
<input onKeyup="autoTab(this)" maxlength=2>
<input onKeyup="autoTab(this)" maxlength=2>
<input onKeyup="autoTab(this)" maxlength=2>
<script type="text/javascript">
function autoTab( obj ) {
if ( obj.value.length >= obj.maxLength && obj.nextElementSibling )
obj.nextElementSibling.focus();
}
</script>
</body>
</html>
I have the following code written in angular JS
<html lang="en" ng-app="person_info">
<head>
<meta charset="utf-8">
<title>Person info</title>
<script src="../angular.min.js"></script>
<script src="controller_class2.js"></script>
<style type="text/css">
.forms{width:200px;height:300px;padding:75px;float:left;background:#CCC;}
.deatils{width:200px;height:auto;padding:100px;float:left;background:#CCC;margin- left:10px;}
.fields {background:#999999;float: left;height:120px;padding: 20px;width:260px;}
</style>
</head>
<body ng-controller="info">
<div class="forms"> Name:</br>
<input type="text" value="name" ng-model="person.name">
</br>
</br>
First Name :</br>
<input type="text" value="fname" ng-model="person.firstname">
</br>
</br>
Phone Number :</br>
<input type="number" value="number" ng-model="person.number">
</br>
</br>
Email :</br>
<input type="email" value="email" ng-model="person.email">
</br>
</br>
Address :</br>
<input type="text" value="address" ng-model="person.address">
</br>
</br>
<input type="submit" value="submit" name="submit" ng-click="test()">
</div>
<div class="deatils">
<p>Name : {{person.name}}</p>
<p>First Name : {{person.firstname}}</p>
<p>Phone Number: {{person.number}}</p>
<p>Email : {{person.email}}</p>
<p>Address :{{person.address}}</p></br></br>
<p>Details in json format : </br>{{ person | json }}
</div>
<div class="fields">
Submit the persons serial number to display his details
</br>
</br>
<input type="number" >
</br>
</br>
<input type="submit" value="submit number">
</div>
</body>
</html>
Controller code
var person_info = angular.module('person_info', []);
person_info.controller('info', function($scope) {
$scope.test = function () {
console.log($scope.person);
}
});
When the user fills the form and click on submit button i want the details to be saved into a array and clear all the field so that the next users details can be filled. each user details will be stored in the array.
i have also created a text field where user can enter the serial number of the user whose detail have to be displayed. for example when i enter the value 3 and submit this. the 3rd person's details in the array have to be displayed.
you can define a function like your test() function in your controller to save current model into an array and clear it, here is example function,
$scope.savePerson = function () {
$scope.personList.push($scope.person);
//clear person model/form
$scope.person = {};
};
and here is html form,
<div class="forms">
Name: <input type="text" value="name" ng-model="person.name">
First Name : <input type="text" value="fname" ng-model="person.firstname">
Phone Number : <input type="number" value="number" ng-model="person.number">
Email : <input type="email" value="email" ng-model="person.email">
Address : <input type="text" value="address" ng-model="person.address">
<input type="submit" ng-click="savePerson()">
</div>
and define another function to retrieve data from your personList[] array like this,
$scope.getPerson = function (index) {
//selected person details
$scope.personDetail = $scope.personList[index];
};
of course you shoudl make few changes in your html as well, here is full PLUNKER of my solution...
you can try extracting the value using .serialize() like this
var count=0;
var formArr={};
$('.forms input[type=submit]').on('click',function () {
formArr[count++]=$( "form" ).serialize(); //this would serialize the form data
// clear the form data for next client details entry
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
});
$('.fields input[type=submit]').on('click',function () {
var serNo=$(this).find ('input[type=text]').val();
var formData= formArr[serNo];
formData=formData.split("&");
for(i=0;i<formData.length;i++)
{
$('input[name='+ formData[i]+']').val(formData[++i]);
}
});
Note: this is untested code, it may require few code tunings
Happy Coding :)