How can I check in jQuery if inputs with name denominationcomune_{{loop.index}} and denominationcomune_{{loop.index}} are empty not all inputs ?
I have a twig like this:
<form action="" method="post">
{% for mat in mat_temp_array %}
<input type="text" name="nomentite_{{loop.index}}"/>
<input type="text" name="denominationcomune_{{loop.index}}" value="{{ mat.denominationcommun }}"/>
<input type="text" name="denominationcomerce_{{loop.index}}" value="{{ mat.denominationcomerce }}"/>
{% endfor %}
<input type="submit" class="btn" value="save"/>
</form>
var empty = true;
$('input[type="text"]').each(function() {
if ($(this).val() != "") {
empty = false;
return false;
}
});
This should look all the input and set the empty var to false, if at least one is not empty.
EDIT:
To match the OP edit request, this can be used to filter input based on name substring.
$('input[name*="denominationcomune_"]').each(...
You could do it like this :
bool areFieldEmpty = YES;
//Label to leave the loops
outer_loop;
//For each input (except of submit) in your form
$('form input[type!=submit]').each(function(){
//If the field's empty
if($(this).val() != '')
{
//Mark it
areFieldEmpty = NO;
//Then leave all the loops
break outer_loop;
}
});
//Then test your bool
You can do it using simple jQuery loop.
Total code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;
$(".bs-example input").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("highlight");
isFormValid = false;
$(this).focus();
}
else{
$(this).removeClass("highlight");
}
});
if (!isFormValid) {
alert("Please fill in all the required fields (indicated by *)");
}
return isFormValid;
}
</script>
</head>
<body>
<div class="bs-example">
<form onsubmit="return test()">
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="text" class="form-control" id="inputEmail" placeholder="Email">
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
Define a helper function like this
function checkWhitespace(inputString){
let stringArray = inputString.split(' ');
let output = true;
for (let el of stringArray){
if (el!=''){
output=false;
}
}
return output;
}
Then check your input field value by passing through as an argument. If function returns true, that means value is only white space.
As an example
let inputValue = $('#firstName').val();
if(checkWhitespace(inputValue)) {
// Show Warnings or return warnings
}else {
// // Block of code-probably store input value into database
}
I'd suggest to add an class='denominationcomune' to all elements that you want to check and then use the following:
function are_elements_emtpy(class_name)
{
return ($('.' + class_name).filter(function() { return $(this).val() == ''; }).length == 0)
}
$('input[type="text"]').get().some(item => item.value !== '');
$(document).ready(function () {
$('input[type="text"]').blur(function () {
if (!$(this).val()) {
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
});
});
<style>
.error {
border: 1px solid #ff0000;
}
</style>
Related
I have the following code, and I was wondering instead of making it so that if any variable inside the array is entered it will bring you to index.php, I want it so if the first is entered it will bring you to 1.html, if 2 is entered it will bring you to 2.html etc.
I
s this possible?
The HTML code:
<center>
<form
name="myForm"
onsubmit="return validateForm()"
method="post"
>
<h1 style = "color:white;">Enter code </h1>
<input type="text" name="value" style="padding: 5px; border-radius: 6px; border: 0px solid transparent;"/>
<br><br>
<input type="submit" class = "ex" value="Enter/submit" style="border-radius: 6px; font-size: 18px;display: inline-block; padding: 20px; border: none; background-color: royalblue; color: white;"/>
</form>
</center>
The JavaScript code:
var cars = ["Saab", "Volvo", "BMW"];
function validateForm() {
var x = document.forms["myForm"]["value"].value;
if (cars.indexOf(x) == -1) {
alert("no car entered");
return false;
}
var x = document.forms["myForm"]["value"].value;
if (cars.indexOf(x) != -1) {
window.location.href = "index.php";
return false;
}
}
Something like this?
Just replace the console.log with the redirect you want.
const cars = ["Saab", "Volvo", "BMW"]
function validateForm() {
const inputValue = document.forms["myForm"]["value"].value;
if (inputValue === cars[0]) {
console.log("Redirect to 1.html");
} else if (inputValue === cars[1]) {
console.log("Redirect to 2.html");
} else if (inputValue === cars[2]) {
console.log("Redirect to 3.html");
} else {
console.log("no car entered")
}
return false;
}
<form name="myForm" onsubmit="return validateForm()" method="post">
Enter code
<input id="formInput" type="text" name="value" /><br>
<input type="submit" class="ex" value="Enter/submit" />
</form>
To redirect to a URL of the form 1.html, 2.html and so on we notice that the digit required is the index of the car make within the array. So thw place we want to redirect to is this index.html
Here is code which implements this.
<center>
<form name="myForm" onsubmit="return validateForm()" method="post">
<h1 style = "color:black;">Enter code </h1><input type="text" name="value" style="padding: 5px; border-radius: 6px; border: 1px solid red;"/>
<br><br><input type="submit" class = "ex" value="Enter/submit" style="border-radius: 6px; font-size: 18px;display: inline-block; padding: 20px; border: none; background-color: royalblue; color: white;"/>
</form>
</center>
<script>
var cars = ["Saab", "Volvo", "BMW"];
function validateForm() {alert(document.forms);alert(document.forms["myForm"]["value"].value);
var x = document.forms["myForm"]["value"].value;
if(cars.indexOf(x) == -1){
alert("no car entered");
return false;
}
else{
window.location.href = cars.indexOf(x) + ".html";
}
}
</script>
Notes:
center is deprecated - use CSS instead
the code in the question declared x twice
if...else is used above instead of testing the condition twice
there seems no point in the final return statement since the user is being redirected
the border of the input element was set to 0. For this test it has been put at 1px and color red so it can be seen
I have been trying to make a simple HTML form validation via Javascript
I have been struggling with this for a while now over a few examples, And no matter what I follow, My index page keeps loading after the button click on the form, I believe that I have put return false in the correct locations to break the rest of code execution, Any ideas why this is so? "My" code is below
Note: I have tried the novalidate attribute with the form, this deactivates the browser's validation but still sends me through to my index page, The ideal functionality should not load the index page and stay on the register page with warnings below the correct input fields
index.php
<?php
if (isset($_POST["register"]))
{
$user = $_POST["username"];
echo "Welcome ".$user;
}
?>
register.php
<!DOCTYPE html>
<html>
<head>
<title>Form validation with javascript</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="wrapper">
<form novalidate method="POST" action="index.php" onsubmit="return Validate()" name="vform">
<div>
<input type="text" name="username" class="textInput" placeholder="Username">
<div id="name_error" class="val_error"></div>
</div>
<div>
<input type="email" name="email" class="textInput" placeholder="Email">
<div id="email_error" class="val_error"></div>
</div>
<div>
<input type="password" name="password" class="textInput" placeholder="Password">
</div>
<div>
<input type="password" name="password_confirmation" class="textInput" placeholder="Password confirmation">
<div id="password_error" class="val_error"></div>
</div>
<div>
<input type="submit" value="Register" class="btn" name="register">
</div>
</form>
</div>
</body>
</html>
<!-- Adding javascript -->
<script type="text/javascript">
// GETTING ALL INPUT TEXT OBJECTS
var username = document.forms["vform"]["username"];
var email = document.forms["vform"]["email"];
var password = document.forms["vform"]["password"];
var password_confirmation = document.forms["vform"]["password_confirmation"];
// GETTING ALL ERROR DISPLAY OBJECTS
var name_error = document.getElementId("name_error");
var email_error = document.getElementId("email_error");
var password_error = document.getElementId("password_error");
// SETTING ALL EVENT LISTENERS
username.addEventListener("blur", nameVerify, true);
email.addEventListener("blur", emailVerify, true);
password.addEventListener("blur", passwordVerify, true);
// Validation Function
function Validate(){
// Username Validation
if (username.value == ""){
username.style.border = "1px solid red";
name_error.textContent = "Username is required";
username.focus();
return false;
}
// Email Validation
if (email.value == ""){
email.style.border = "1px solid red";
email_error.textContent = "email is required";
email.focus();
return false;
}
// Password Validation
if (password.value == ""){
password.style.border = "1px solid red";
password_error.textContent = "password is required";
password.focus();
return false;
}
// check if the two passwords match
if (password.value != password_confirmation.value)
{
pasword.style.border = "1px solid red";
pasword_confirmation.style.border = "1px solid red";
password_error.innerHTML = "The two passwords dont match";
return false;
}
}
// event handler functions
function nameVerify(){
if (username.value != "")
{
username.style.border = "1px solid #5E6E66";
name_error.innerHTML = "";
return true;
}
}
function emailVerify(){
if (email.value != "")
{
email.style.border = "1px solid #5E6E66";
email_error.innerHTML = "";
return true;
}
}
function passwordVerify(){
if (passwprd.value != "")
{
passwprd.style.border = "1px solid #5E6E66";
passwprd_error.innerHTML = "";
return true;
}
}
</script>
style.css
#wrapper{
width: 35%;
margin: 50px auto;
padding: 20px;
background: #EFFFE0;
}
form{
width: 50%;
margin: 100px auto;
}
form div{
margin: 3px auto;
}
.textInput{
margin-top: 2px;
height: 28px;
border: 1px solid #5E6E66;
font-size: 16px;
padding: 1px;
width: 100%;
}
.btn{
padding: 7px;
width: 100%;
}
.val_error{
color: #FF1F1F;
}
Thanks a bunch for any help you can provide!
Assign an id to your form, attach form submit event to it and if validations get fails then you can use event.preventDefault(); to stop the submission of form.
Try the code below.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form action="your_file_name.php" method="post" id="myForm">
First name:<br>
<input type="text" name="firstname" id="firstname">
<br>
Last name:<br>
<input type="text" name="lastname" id="lastname" >
<br><br>
<input type="submit" value="Submit">
</form>
$( "#myForm" ).submit(function(event) {
if($("#firstname").val()== "" || $("#lastname").val()== "") //Your validation conditions.
{
alert("Kindly fill all fields.");
event.preventDefault();
}
//submit the form.
});
</script>
</html>
I am trying to create a custom error message when a number which is too high or low is entered in the "size" element. However, I am unable to make this work. I am a beginner so a solution which involves the least changes to my existing code would be most appreciated.
function autoFillcost() {
var size = document.getElementById("size").value;
if (size <= 25)
document.getElementById("cost").value = "£100";
else if (size >= 26 && size <= 50)
document.getElementById("cost").value = "£200";
else
document.getElementById("cost").value = "£300";
}
function sizeValidate() {
var size = document.getElementById("size");
if (!size.checkValidity()) {
size.setCustomValidity("ERROR!");
} else {
size.setCustomValidity("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<form>
Group Size:<input type="number" min="6" max="200" id="size" onblur="autoFillcost();sizeValidate();" required>
<p>Cost:<input type="text" id="cost"></p>
<p id="demo"></p>
</form>
</body>
</html>
Sorry for digging, but it is possible, just report it after you set it.
Hopefully this helps others.
if (!size.checkValidity()) {
size.setCustomValidity("ERROR!");
size.reportValidity();
}
The problem with setCustomValidity is, that it does only work once you submit the form.
function autoFillcost() {
var size = document.getElementById("size").value;
if (size <= 25)
document.getElementById("cost").value = "£100";
else if (size >= 26 && size <= 50)
document.getElementById("cost").value = "£200";
else
document.getElementById("cost").value = "£300";
}
function sizeValidate() {
var size = document.getElementById("size");
if (!size.checkValidity()) {
size.setCustomValidity("ERROR!");
} else {
size.setCustomValidity("");
}
}
button {
padding:6px;
cursor:pointer;
}
input {
padding:5px;
border:1px solid #aaa;
box-shadow: 0px 0px 3px #ccc, 0 10px 15px #eee inset;
border-radius:2px;
}
input:valid {
background-color: white;
}
input:invalid {
background-color: lightpink;
}
<form>
Group Size:<input type="number" min="6" max="200" id="size" onblur="autoFillcost();sizeValidate();" required />
<p>Cost:<input type="text" id="cost"></p>
<p id="demo"></p>
<button type="submit">Submit</button>
</form>
I have this input text:
<div class="form-group">
<label for="newPrice">New Price</label>
<input type="text" class="form-control" id="newPrice" name="newPrice" placeholder="New price">
</div>
I would like to change the border of the input dynamically as the user is typing depending what the value is.
This value will be a percent based on an earlier defined amount that will change depending on the value the user is adding.
So if the value is under 5% it's red between 5-10% it's amber and over 10% is green etc.
Any JavaScript whizzes out there know the best way to do this?
I'll go with 2 events. The first is input, but contenteditable elements won't fire an input event on IE11, so I'll go for keypress with a timeout too.
input will be fired right after a user inputs something and the value is changed. keypress will fire after a user inputs something but right before the value is changed, in between.
This way you will keep all modern and older browsers covered (to a limit, because of addEventListener):
var tim = null;
var el = document.getElementById("newPrice");
el.addEventListener("keypress", function() {
tim = setTimeout(input, 0);
});
el.addEventListener("input", function input() {
clearTimeout(tim);
// do whatever you want with el.value
if (el.value == "BLAH") {
el.style.backgroundColor = "red";
} else if (parseInt(el.value) > 10) {
el.style.backgroundColor = "green";
} else if (parseInt(el.value) < -12) {
el.style.backgroundColor = "whizzeblue";
}
});
<input id="txt" type="number" onkeyup="changeborder(this.id, this.value)" />
<script type="text/javascript">
function changeborder(id, value){
if(value < 5){
document.getElementById(id).style.border = "2px solid red";
}
else if(value > 5 && value < 10 ){
document.getElementById(id).style.border = "2px solid yellow";
}
}
</script>
Use focusout . In snippet validation is not applied.
$("#newPrice")
.focusout(function() {
var price = $(this).val();
if (parseInt(price) <= 5) {
$(this).removeClass('green');
$(this).removeClass('blue');
$(this).addClass('red');
}
if (parseInt(price) > 5 && parseInt(price) <= 10) {
$(this).removeClass('red');
$(this).removeClass('blue');
$(this).addClass('green');
}
if (parseInt(price) > 10) {
$(this).removeClass('green');
$(this).removeClass('red');
$(this).addClass('blue');
}
});
.red {
border: solid 2px red;
}
.green {
border: solid 2px green;
}
.blue {
border: solid 2px blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="newPrice">New Price</label>
<input type="text" class="form-control" id="newPrice" name="newPrice" placeholder="New price">
</div>
I am using jQuery for min and maxlength. I want here to prevent button if minlength is not correct. I mean if user not entered minimum 8 digit, then prevent button.
jQuery:
var minLength = '8';
var maxLength = '13';
$("input[name=354]").keypress(function(){
if(this.value.length > maxLength) {
this.value = this.value.slice(0, maxLength);
}
if(this.value.length < minLength) {
$(this).css('border','1px solid #f00');
} else {
$(this).css('border-color','#cfdadd');
}
});
HTML button code:
<button type="button" class="btn next">Next</button>
You can add disabled attribute to button if length of input isn't valid.
var minLength = "5";
var maxLength = "10";
$("input").on("keydown change", function(){
var value = $(this).val();
// length is short
if (minLength > value.length){
$("button").attr("disabled", true);
$(this).addClass("error");
} else {
$("button").attr("disabled", false);
$(this).removeClass("error");
}
// length is long
if (value.length > maxLength)
this.value = value.slice(0, maxLength);
});
.error {
border: 2px solid rgba(255, 0, 0, 0.48);
box-shadow: 0px 0px 2px -1px red;
outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" class="error" />
<button type="submit" disabled>Submit</button>
</form>
I think you need to use disabled.
And it would be better to use input instead of keypress.
var minLength = '8';
var maxLength = '13';
$('input[name=354]').on('input', function() {
if (this.value.length > maxLength) {
this.value = this.value.slice(0, maxLength);
}
if (this.value.length < minLength) {
if (!$(this).hasClass('invalid')) {
$(this).addClass('invalid');
}
$('.btn').attr('disabled', true);
} else {
$(this).removeClass('invalid');
$('.btn').attr('disabled', false);
}
});
.invalid {
border:1px solid #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="invalid" name="354" type="text">
<button type="button" class="btn next" disabled>Next</button>
Here's a fiddle