Prevent button jquery - javascript

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

Related

SetCustomValidity not working

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>

Change the colour of this input text depending on the value being entered

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>

Social Security Number input validation

I have this sample:
function ssnFormat() {
$("#ssn").on('blur change', function() {
text = $(this).val().replace(/(\d{3})(\d{2})(\d{4})/, "$3-$2-$4");
if ($(this).val() == '' || $(this).val().match(text) || $(this).val().length == 0) {
$(this).removeClass('valid').addClass('invalid');
} else {
$(this).removeClass('invalid').addClass('valid');
}
});
}
$("#ssn").on('blur change', function() {
ssnFormat();
});
.valid {
border: 1px solid blue;
}
.invalid {
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="required-input" id="ssn" maxlength="9" type="text" name="ssn" placeholder="123-45-6789">
What I want to do these things are:
If I write the following text I want to validate this format 123-12-1234
If I write 123456789 I want to transform when click outside input in this format
123-12-1234
I tried to do this by using the function below but don't work
$("#ssn").on("click", function() {
var thisVal = $(this).val();
var value = thisVal.replace(/[^\/\d]/g,''); //here is a problem
$(this).val(value);
});
Can you please help me solve this problem?
Thanks in advance!
Try this
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
.valid{
border:1px solid blue;
}
.invalid{
border:1px solid red;
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">
Also there is another way to enforce user always enters that pattern -
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()" required pattern="\d{3}[\-]\d{2}[\-]\d{4}">
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
.valid{
border:1px solid blue;
}
.invalid{
border:1px solid red;
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">

Javascript to validate only Numeric after predefined text in a textbox

I'm trying to use Javascript to make a textbox that contains some read-only text at the beginning of the text box and then allows editing following the read-only text. I need to allow only 10 digit numeric after the readonly text and need to validate for the numeric digits. The following is the Javascript code for having the readonly in textbox
var readOnlyLength = $('#field').val().length;
$('#output').text(readOnlyLength);enter code here
$('#field').on('keypress, keydown', function(event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39))
&& ((this.selectionStart < readOnlyLength)
|| ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
return false;
}
});
If you looking for solution with script then here is plain js and RegExp:
var fixedText = function(textbox, label) {
var num = textbox.value.replace(/\D/g, ''); //non numeric
num = num.substr(0, 10); //max 10 digits
textbox.value = label + num;
};
<input type="text" onkeyup="fixedText(this, 'Postal Code: ')" autofocus='' value="Postal Code: " />
<input type="text" onkeyup="fixedText(this, 'Contact No: ')" value='Contact No: ' />
With simple label ,input and script:
var numeric = function(textbox) {
var num = textbox.value.replace(/\D/g, '');
num = num.substr(0, 10);
textbox.value = num;
};
label.partial,
input.partial {
border: 1px ridge grey;
margin-bottom: 3px;
}
label.partial {
border-right: none;
cursor: text;
}
input.partial {
border-left: none;
margin-left: -4px;
top: -1px;
position: relative;
}
<label for="PostalCode" class='partial'>Postal Code </label>
<input type="text" onkeyup="numeric(this)" autofocus='' id='PostalCode' class='partial' />
<br/>
<label for="ContactNo" class='partial'>Contact No </label>
<input type="text" onkeyup="numeric(this)" id='ContactNo' class='partial' />

Check if inputs form are empty jQuery

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>

Categories

Resources