I have a couple of inputs
<div class="row">
<div class="col-md-6 col-sm-offset-3 file-input">
<div class="input-group">
<input type="text" class="form-control" id="fileOneContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileOne" name="fileOne" class="fileGroup">
</span>
</span>
</div>
</div>
<div class="col-md-6 col-sm-offset-3 file-input">
<div class="input-group">
<input type="text" class="form-control" id="fileTwoContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileTwo" name="fileTwo" class="fileGroup">
</span>
</span>
</div>
</div>
</div>
Now I have to do my own custom validation for this within Javascript. Concentrating only on the first input for now, the rules are:
Cant be empty
Cant be larger than 2MB
Must be one of a certain file type
To handle all this, I came up with the following
var fileOne = $("#fileOne").val();
if(fileOne.length == 0) {
$(this).addClass('error');
errors.push("- Please upload a document");
} else if($("#fileOne")[0].files[0].size > 2097152) {
errors.push("- Please upload a file smaller than 2MB");
} else if( $("#fileOne")[0].files[0].type != 'image/bmp' &&
$("#fileOne")[0].files[0].type != 'image/jpeg' &&
$("#fileOne")[0].files[0].type != 'image/pjpeg' &&
$("#fileOne")[0].files[0].type != 'image/png' &&
$("#fileOne")[0].files[0].type != 'image/tiff' &&
$("#fileOne")[0].files[0].type != 'application/pdf') {
errors.push("- Please upload one of the valid document types");
}
This seems to work, although I imagine it could be improved.
Anyways, I need to now work on the second input. Initially, this input should be hidden, and only displayed when an add more button is clicked. Now I do not really want to hide it via css because this can be altered using developers tools.
The rules for the second input are pretty much the same as above, but this input is not required. This input should only have a value if the first input has a value. So you shouldnt be able to upload a file to the second input unless you have already uploaded one to the first.
What would be the best way to handle this second input to achieve the affect I am after?
Any advice appreciated.
Thanks
UPDATE
So I now have this
var fileInputs = document.querySelectorAll('.fileGroup');
for (var i = 0; i < fileInputs.length; i++) {
fileInputs[i].addEventListener('change', function(event){
error = validateFile(event);
errors.push(error);
});
};
function validateFile(event) {
var input = event.target;
var fileLength = input.files[0].length;
var fileSize = input.files[0].size;
var fileType = input.files[0].type;
if(fileLength == 0) {
$(this).addClass('error');
return("- Please upload a document");
} else if(fileSize > 2097152) {
return("- Please upload a file smaller than 2MB");
} else if( fileType != 'image/bmp' &&
fileType != 'image/jpeg' &&
fileType != 'image/pjpeg' &&
fileType != 'image/png' &&
fileType != 'image/tiff' &&
fileType != 'application/pdf') {
return("- Please upload one of the valid document types");
}
}
The problem is that I need the errors to display once the form has been submitted, not when the fileinput changes. Is there any way to do this without the change event?
Thanks
Try using accept attribute set to ".bmp,.jpeg,.jpg,.pjpeg,.png,.tiff,.pdf" , adding disabled to second input , setting disabled to false at change event handler of first input
var errors = [];
$(document).on("change", "#fileOne, #fileTwo:not(:disabled)", function() {
console.log(this.files);
if (this.files[0].size > 2097152) {
errors.push("- Please upload a file smaller than 2MB");
};
if (this.files.length) {
$("#fileTwo").prop("disabled", false)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-6 col-sm-offset-3 file-input">
<div class="input-group">
<input type="text" class="form-control" id="fileOneContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileOne" name="fileOne" class="fileGroup" accept=".bmp,.jpeg,.jpg,.pjpeg,.png,.tiff,.pdf">
</span>
</span>
</div>
</div>
<div class="col-md-6 col-sm-offset-3 file-input">
<div class="input-group">
<input type="text" class="form-control" id="fileTwoContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileTwo" name="fileTwo" class="fileGroup" accept=".bmp,.jpeg,.jpg,.pjpeg,.png,.tiff,.pdf" disabled="true">
</span>
</span>
</div>
</div>
</div>
I recommend looping through your inputs and binding an on change event listener to validate the file. That way you don't have to repeat logic and you can grab the context via the event.
function validateFile(event) {
var input = event.target;
var fileSize = input.files[0].size;
// rest of validation logic here.
}
var fileInputs = document.querySelectorAll('.fileGroup')
for (var i = 0; i < fileInputs.length; i++) {
fileInputs[i].addEventListener('change', function(event){
validateFile(event);
});
};
The above starter code should put you in the right direction.
EDIT: If you'd like to do it on submit you can write some code like this:
document.forms[index].onsubmit = function() {
validateFile();
}
The index is the index of the form on the page. If there is only one form it most likely is 0.
Here is a fiddle:
http://jsfiddle.net/dgautsch/cep7cggr/
Related
I have this logic that is in a form that some users are able to process without selecting a source. Is there a better way to do this logic so it will not fail I am unable to get it to fail so I am very limited.
html
<div id="sources">
<label id="lblSources" class="control-label">* Source</label>
<label id="lblSourcesError" class="pl-4 text-danger" style="display:none">At least one 'Source' must be selected</label>
<input type="checkbox" value=#item.Value name="chkProduct" />
</div>
Js
var checked_sourcecheckboxes = $("#sources input[type=checkbox]:checked");
if (checked_sourcecheckboxes.length == 0) {
$("#lblSourcesError").show();
additionalValidation = true
}
else {
$("#lblSourcesError").hide();
}
Consider the following example.
$(function() {
var checked_sourcecheckboxes = $("#sources input[type=checkbox]");
if (checked_sourcecheckboxes.filter(":checked").length == 0) {
$("#lblSourcesError").show();
additionalValidation = true
} else {
$("#lblSourcesError").hide();
}
checked_sourcecheckboxes.change(function() {
if (checked_sourcecheckboxes.filter(":checked").length == 0) {
$("#lblSourcesError").show();
additionalValidation = true
} else {
$("#lblSourcesError").hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sources">
<label id="lblSources" class="control-label">* Source</label>
<label id="lblSourcesError" class="pl-4 text-danger" style="display:none">At least one 'Source' must be selected</label>
<input type="checkbox" value=#item.Value name="chkProduct" />
</div>
This checks the status when the page loads and whenever the checkbox is changed.
Before clicking the button to execute, I want to verify whether the filled content meets the requirements. If there is any error message, the page cannot be redirected.
I used .preventDefault(), but it didn't work. Even error, the page was still redirected.
let btnAjtBtlCellier = document.getElementById('ajouterBouteilleCellier');
let fAjtBtlCellier = document.getElementById('form-ajouter-btl');
let inputEles = document.querySelectorAll('#form-ajouter-btl input');
let erreurAjtBtl = false;
inputEles.forEach(function(element) {
//Verify all required inputs
element.addEventListener('change', (evt) => {
quantiteValideAjt();
date_achatValideAjt();
prixValideAjt();
})
});
btnAjtBtlCellier.addEventListener('click', (evt) => {
erreurAjtBtl = false;
if (erreurAjtBtl) evt.preventDefault();
})
<div class="form-ajouter" id="form-ajouter-btl">
<p>Nom : <span data-id="" class="nom_bouteille"></span></p>
<span id="errNom_ajouter"></span>
<label for="millesime_ajouter">Millesime : </label>
<input type="text" name="millesime" id="millesime_ajouter" value="2020">
<label for="quantite_ajouter">Quantite : </label>
<input type="text" name="quantite" value="1" id="quantite_ajouter">
<span id="errQuantite_ajouter"></span>
<label for="date_achat_ajouter">Date achat : </label>
<input type="date" name="date_achat" id="date_achat_ajouter" value="">
<span id="errAchat_ajouter"></span>
<label for="prix_ajouter">Prix : </label>
<input type="text" name="prix" id="prix_ajouter" value="">
<span id="errPrix_ajouter"></span>
<label for="garde_jusqua_ajouter">Garde : </label>
<input type="text" name="garde_jusqua" id="garde_jusqua_ajouter">
<label for="notes_ajouter">Notes</label>
<input type="text" id="notes_ajouter" name="notes">
<!-- input caché avec id usager -->
<input type="hidden" name="courriel_usager" value="<?= $_SESSION[" courriel "] ?>">
</div>
<button name="ajouterBouteilleCellier" id="ajouterBouteilleCellier">AJOUTER LA BOUTEILLE</button>
You are setting the variable "erreurAjtBtl" on every click back to false, even if the input fields were validated successfully before. I would suggest to remove that line and set this variable in change-event like this:
element.addEventListener('change', (evt) => {
if (quantiteValideAjt() && date_achatValideAjt() && prixValideAjt())
erreurAjtBtl = false;
else
erreurAjtBtl = true;
})
I've assumed that validation functions return true or false.
Assuming that
quantiteValideAjt();
date_achatValideAjt();
prixValideAjt();
all return false if errors, and true if valid, you need to do
btnAjtBtlCellier.addEventListener('click', (evt) => {
const erreurAjtBtl = !quantiteValideAjt() || !date_achatValideAjt() || !prixValideAjt();
if (erreurAjtBtl) evt.preventDefault();
})
I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem
I am having a problem with a script i am programming. I am very new to AJAX, and can't figure out what i am doing wrong that makes it not to work. Any help would be highly appreciated. I have multiple forms on the page and when i separate the forms the communication between the Ajax and php works just fine. But when i put everything together, it stops working. I do believe its either a communication problem or maybe some conflicting scripts or just some bad coding.
Here is the php code:
#session_start();
if(isset($_SESSION["username"])){
header("location: home.php");
exit();
}else{
$usertitle = $_POST['ut'];
$userfname = $_POST['uf'];
$userlname = $_POST['ul'];
$useremail = $_POST['ue'];
$userloc = $_POST['uloc'];
$user_est_typ = $_POST['utp'];
$userfname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userfname);
$userlname = preg_replace("/[^A-Za-z0-9?![:space:]]/","",$userlname);
if($usertitle == "Title...."){
echo '<font color="red">Error: Please select a title.';
exit();
}else if($userfname == NULL){
exit('<font color="red">Error: You need a first name to proceed. </font>');
}else if( strlen($userfname) <= 2){
exit('<font color="red">Error: First name should be three (3) or more letters.</font>');
} else if($userlname == ""){
exit('<font color="red">Error: Giving a Surname would be nice.</font>');
}else if( strlen($userlname) <= 2){
exit('<font color="red">Error: Surname should be three (3) or more Letters.</font>');
}else if(!strpos($useremail, "#") || !strpos($useremail, "." || !filter_var($useremail, FILTER_VALIDATE_EMAIL) === true)){
exit('<font color="red">Email Address not valid</font>');
}else if($user_est_typ == "Select..."){
exit('<font color="red">Error: You must select an estimate type to proceed.</font>');
}else if($userloc == ""){
exit('<font color="red">Error: A location would be required so as to get the radiation data for the estimates</font>');
}else {
include("../../scripts/dbconect.php");
$queryuseremail = mysql_query("SELECT id FROM userdata WHERE userEmail='$useremail' LIMIT 1");
$useremail_check = mysql_num_rows($queryuseremail);
if ($useremail_check > 0){
echo "The email address ".$useremail." is already registered in ur database";
exit();
}
// More Validation and mysql insert
exit('<font color="red">signup_success</font>');
}
}
Here is my AJAX codes:
function _(x){
return document.getElementById(x);
}
function show(id){
var divelement = _(id);
if(divelement.style.display == 'none')
divelement.style.display = 'block';
else
divelement.style.display == 'none';
}
function hide(id){
var divelement = _(id);
if(divelement.style.display == 'block')
divelement.style.display = 'none';
else
divelement.style.display == 'block';
}
function emptyElement(id){
_(id).innerHTML = "";
}
function estimatetypeimg(){
var estType = _('estimatetype').value;
if (estType == 'solarpv'){
show('estimate_pv');
hide('estimate_thermal');
}
else if(estType == 'solarthermal'){
hide('estimate_pv');
show('estimate_thermal');
}
else{
hide('estimate_pv');
hide('estimate_thermal');
}
}
function newUsers() {
var title = _("salutation").value;
var fname = _("fname").value;
var lname = _("lname").value;
var email = _("email").value;
var loc = _("location").value;
var tp = _("estimatetype").value;
var url = "ajax.php";
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
_("statuscheck").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(vars);
}
And here is my html code:
<div id="startbuts" style="display:none">
<form class="pure-form" name="startbutsform" id="startbutsform" onsubmit="return false;">
<button type="submit" id="newusersbtn" onclick="show('newusers'); hide('existingusers'); hide('existingusersbtn');"class="pure-button pure-button-primary">New Estimate</button>
<button type="submit" id="existingusersbtn" onclick="show('existingusers'); hide('newusers'); hide('newusersbtn');" class="button-secondary pure-button">Load Previous Estimate</button>
</form>
<div id="existingusers" style="display:none">
<form class="pure-form" name="signupex" id="signupex" onsubmit="return false;">
<fieldset>
<legend>Existing users: login with your email and Data ID.</legend>
<input type="email" id="dataemail" placeholder="Email" >
<input type="text" id="dataid" placeholder="DataId"><br/>
<button id="signupexbtn" type="submit" onclick="signinold()" class="pure-button pure-button-primary">Sign in</button>
</fieldset>
</form>
</div>
<div id="newusers" style="display:none">
<form class="pure-form" name="signupnew" id="signupnew" onsubmit="return false;">
<fieldset>
<legend>New users start here.</legend>
<div class="pure-control-group">
<label for="salutation">Title: </label>
<select id="salutation" name="salutation">
<option>Title....</option>
<option>Prof. Dr.</option>
<option>Prof.</option>
<option>Dr.</option>
<option>Mr.</option>
<option>Mrs.</option>
<option>Miss.</option>
</select>
</div>
<div class="pure-control-group">
<label for="fname">First name:</label>
<input id="fname" name="fname" type="text" placeholder="First Name">
</div>
<div class="pure-control-group">
<label for="lname">Last name:</label>
<input id="lname" name="lname" onfocus="emptyElement('errorcheck')" type="text" placeholder="Last Name">
</div>
<div class="pure-control-group">
<label for="email">Email Address:</label>
<input id="email" name="email" type="email" onfocus="emptyElement('errorcheck')" placeholder="Email Address">
</div>
<div class="pure-control-group">
<label for="location">Project Location: </label>
<input id="location" name="location" type="text" onfocus="emptyElement('errorcheck')" placeholder="Enter City ex Buea...">
</div>
<div class="pure-control-group">
<label for="estimatetype">Type of Estimate: </label>
<select id="estimatetype" name="estimatetype" onchange="estimatetypeimg()">
<option value="Select">Select...</option>
<option value="solarpv">Solar PV</option>
<option value="solarthermal">Solar Thermal</option>
</select>
</div>
<div id="estimate_pv" style="display:none" >
<img id="solarpvimg" src="images/solarpv.png" width="250" height="109" alt="Solar PV" />
</div>
<div id="estimate_thermal" style="display:none">
<img id="solarthermalimg" src="images/solarthermal.png" width="250" height="109" alt="Solar PV" />
</div>
<hr/>
<button id="signupnewbtn" type="button" class="pure-button pure-button-primary" onclick="newUsers()" >Start Calculator</button>
<button onclick="emptyElement('errorcheck'); hide('estimate_pv'); hide(estimate_thermal);" class="pure-button pure-button-primary" type="reset">Reset </button>
</fieldset>
</form>
</div>
</div>
Thank you David Lavieri and especially Sher Kahn. Your responses got me thinking and i finally figured out why I was not getting any response from my PhP script. As Khan also mention, I am just a hobby coder and you are absolutely right my code is not very clean. I cleaned the code on JSLint and realised i had too many bad coding habits. :). Thanks also for giving me a heads up with malsup query plugins. they are very handy and will help a lot.
So finally to the problem I had. The actual problem was the link to the php file. The url was poorly defined which made it impossible for the communication between the ajax and the php file. I use Dreamweaver and when i used the browse tool it gave me a link to the file, but because my javascript was external, the link was only relative to the Javascript file, and not the main html file. Also when i double checked my data vars, i missed and "&" for my second variable in the string before "uf"
var url = "ajax.php";// i changed the path file to scripts/ajax.php and it worked like magic.
var vars = "ut="+title+"uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// before
var vars = "ut="+title+"&uf="+fname+"&ul="+lname+"&ue="+email+"&uloc="+loc+"&utp="+tp;// After
Hope this can be of help to someone else.
regards and thanks David and Khan.
i am using Bootstrap to make a webpage. I have a simple code with 1 input and 1 button. when you press the button, which contains the input is stored in the database. but if the input is empty also saves it to the database. I can do the validation with javascript but i want to know if bootstrap have an option to validate this. For example forms in bootstrap validate it, but i dont want to use a form.
<div class="row">
<div class="col-md-4 col-md-offset-1">
<div class="input-group input-group-lg"> <span class="input-group-addon"><span class="glyphicon glyphicon-fire"></span> </span>
<input type="text" class="form-control" placeholder="Nombre Marca" id="marca" required>
</div>
</div>
</div>
<div class="row">
<br />
<div class="col-md-3 col-md-offset-1" align="center" onClick="guardar_marca()"> Guardar Marca
</div>
</div>
I'm not sure if you just copied a small portion of your HTML, but in your snippet you have an extra closing </div>. You can use jQuery to test if the input value is empty:
$('.btn').click(function(e) {
if ($('input').val() === '') {
e.preventDefault();
alert('input is empty');
}
});
Bootply
I would use something like this:
$("MYINPUT").on("change",function(){
($(this).val() === "") ? false : $("MYBUTTON").prop("disabled",false);
}
The following code let's you write your click event as well as stop empty values.
$('.btn').click(function(){
if($('#marca').val() === ''){
alert('Empty field');
return false;
}
//The rest of the logic you want to execute
})
If you're looking for a vanilla JavaScript solution, here is something i made for my to-do:
window.onkeyup = function(e) {
var inputs = document.getElementsByClassName("c1"), inputsVal;
for (i = 0; i < inputs.length; i++) {
inputsVal = inputs[i].value;
if (!inputsVal || inputsVal == "" || inputsVal == " ") {
return false//if the inputsVal has 0 data, it will return false.
}
}
if (event.which == 13) {
Uilogic.saveitem();//function to actually send value to database
}
};