Text Box validation through onkeyup event Jquery without using alert - javascript

I have the following text box in my html page .
The code which I am using so far is .
<input type="text" id = "points" onkeyup="Validate()">
function Validate(){
var text_value = document.getElementById("points").value;
alert(text_value);
if (!text_value.match(/^[56789]$/) && document.getElementById(called_id).value !="")
{
document.getElementById("points").value="";
// document.getElementById("points").focus();
alert("Please Enter only between 5 and 10 ");
}
}
Accepted values are 5 , 6 , 7 , 8 , 9 and 10 .
I have found the way based on onkeyup event to accept only 5 , 6 , 7 , 8 and 9 .. I want to know how to include 10 there .
Also I want to know the onkeyup event validation for the same using jquery .
If the user gives any other value apart from these it should be given to the right of the text box as "The value should be between 5 and 10 " (not as an alert) .
If the first entered value is 1 , it should wait for the next key pressed . Accept if it is 0 or raise the same error message as in previous case .

Working Jsfiddle
I would prefer without regex:
function validate() {
var num = document.getElementById("points2").value;
var num = parseInt(num, 10);
alert(num);
if (num < 5 || num > 10) {
document.getElementById("points2").value = "";
alert("Please Enter only between 5 and 10 ");
}
}
change your regex to :
/^([5-9]|10)$/
you should use onchange event:
<input type="text" id = "points" onchange="Validate()">
function Validate(){
var text_value = document.getElementById("points").value;
alert(text_value);
if (!text_value.match(/^([5-9]|10)$/) && document.getElementById(called_id).value !="")
{
document.getElementById("points").value="";
// document.getElementById("points").focus();
alert("Please Enter only between 5 and 10 ");
}
}

$('#textbox').keyup(function() {
var value = $('#textbox').val();
if(value != ''){
if(!value.match(/^[5678910]$/))
textboxError();
else{
var length = value.length;
if(value.charAt(length-1) == 0 && value.charAt(length-2) != 1)
textboxError();
}
}
};
$('#textbox').change(function() {
var value = $('#textbox').val();
if(value != '')
textboxError();
}
};
function textboxError(){
$('#textbox').val('');
$('#textbox').focus();
alert("Please Enter only between 5 and 10 ");
}
What we are doing is,
Check if value is empty (If empty don't perform anything)
If not empty check if the value matches to defined set
If it match, now we do check for 10. What we do is if last entered item of field is 0, than the previous field must be 1 so it makes a 10. If not we throw error.
But here is a problem, the user might enter 1 and leave the field without entering another char. So, u can extend this by onchange field.
Onchange, now we check for count of 1 and that should match count of 10. It fixes our problem. You don't have to worry of 0 because we already check it in keyup block.
I Didn't check the code. So if any typos or errors, u can replace them.

As Zaheer Ahmed stated, /^([5-9]|10)$/ will catch 10 as well. For the event listener, you can use
$('#textbox')[0].addEventListener('input', function(event) {
var value = $(event.target).val();
// we already have a reference to the element through the event object,
// crawling the DOM again is expensive.
if(value != '') textboxError();
});
This bypasses jQuery, which may be frowned upon by some, but the 'input' event fires immediately and also works if the text was pasted in or entered by some other method.

Related

How to correctly store original value from masked textbox to another textbox

I wanted to mimic the way password fields are hidden/shown by clicking an eye icon. The difference is that my input shouldn't be completely hidden and instead of the usual asterisk(*) symbol on password fields, the characters should be changed to 'x'. The format should be like Rxxxx4921 wherein the first character is shown, the next four characters are hidden, and the rest afterwards are normally shown.
I have two textboxes. One is where the original text should appear and the other one should show the masked text.
Reason for this is to show the unmasked textbox if 'show' is chosen and show the masked textbox if 'hide' is chosen.
My current code correctly masks the text when I input something on the unmasked textbox. However, when I try to input something inside the masked textbox, it will get the 'x' characters.
<input type="text" name="masknumber" maxlength="9">
<input type="text" name="number" maxlength="9">
$("input[name='masknumber']").on("keyup", function() {
$("input[name='number']").val(destroyMask(this.value));
this.value = createMask($("input[name='number']").val());
})
$("input[name='number']").on("keyup", function() {
$("input[name='masknumber']").val(destroyMask(this.value));
$("input[name='masknumber']").val(createMask($("input[name='number']").val()));
})
$(document).ready(function() {
var firstpart = "";
})
function createMask(string) {
console.log(string)
var len = string.length;
if (len == 1)
firstpart = string;
var stars = len > 1 ? len > 2 ? len > 3 ? len > 4 ? firstpart + 'XXXX' : firstpart + 'XXX' : firstpart + 'XX' : firstpart + 'X' : firstpart,
result = stars + string.substring(5);
return result;
}
function destroyMask(string) {
console.log(string)
//return string.replace(/\D/g,'').substring(0, 8);
return string;
}
https://jsfiddle.net/0dj8t6ga/
How do you successfully store the original value to the unmasked textbox? What if the user inserts a character in between the string, what should be added to the code to deal on that matter as well?

JS->Form validation on inputs. Using for loop to get all the inputs index

I have a form with 4 inputs and I want to show an alert on submit. What I have done is that I have already created the warnings that goes under every input with display:none; in CSS.
After this I have created a for loop in JS to get the index of every input and apply my if statement of showing the the alert if === null || === ""
using a variable to make the querySelector("THE CLASS").style.display="block";
Also on my form I have this line
<form method="post" class="q-form" name="form" onsubmit="return validate()">
My problem is when I submit my form the only alert that is shown is the one under the Username and after it appears it also disappears because I think that the for loop goes to the next input.
Let me know if there is something more to clarify.
Here you have all the code: https://jsbin.com/kazopahuga/1/edit?html,js,output
If you want to see the alert showing press Run with JS
Thank You!
I suggest a few modifications to your validare() function:
Add a flag indicating whether the whole form is valid, assume it's true until you find an input that is invalid. Return the value of this flag.
var isValid = true;
Capture your validation messages too so you can access them by index like your inputs:
messages = document.getElementsByClassName(' alert alert-danger custom');
When you find an invalid input, display the associated message and update the valid flag to false.
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
Here is the updated function:
function validare() {
var inputs, messages, index;
var isValid = true;
inputs = document.getElementsByTagName('input');
messages = document.getElementsByClassName(' alert alert-danger custom');
for (index = 0; index < inputs.length; ++index) {
var currentInputValue = inputs[index].value;
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
}
return isValid;
}
Updated jsbin here
Here is an updated solution: jsbin
You used querySelector which return only the first element it finds with the same class, you should have used querySelectorAll which return all the selectors.

Comparing the value in JavaScript

I am using Javascript/Jquery and I have a dropdownlist. My first index is: "Please select an id". I want to submit the page (return true will submit it) if something is selected, else do not submit it.
<script type="text/javascript">
function Type() {
var id = $("[id$='ddl1']").val();
alert(id); // If something is selected i get the value else I get "Please select an id"
var valid = false;
if (id < 0) {
$("#Type-span").text("*"); //A Span to represent the * if page not submitted
}
else {
valid = true;
$("#Type-span").text("");
}
alert(valid);
}
</script>
It always returns true here, even if i select "Please select an id"
Please, try the below
var id = parseInt($("[id$='ddl1']").val(), 10);
To handle the NaN situation, you need to evaluate that too
if(id != id || id < 0)
and you should have value of element 'Please select an answer' as a blank.
Your issue is that the value attribute of is a string, so, if you are trying to compare it to 0, I'm assuming that it is a number and you will need to convert it to one, before doing the compare.
Change this:
var id = $("[id$='ddl1']").val();
. . . to this:
var id = parseInt($("[id$='ddl1']").val(), 10);
And, if the values of the <options> are not all numbers (with the default being < 0), then you need to make sure that they are. :)

issue in disabling submit button using jquery

i am iterating a list , and displaying its values in textboxes.
there is two textboxes with name checkquantity & quantity whose values i am iterating from a list.
Now users have to enter the quantity values, if they enter the quantity values more then the allocated quantity. Then i have to disable the submit button.
This is my problem:
From my below code , submit button is diasabling for first time only. i.e. if i enter invalid values for first time then my code is working fine but if again i enter valid values in another text-box then my button is enabling. But it should not enable since in first textbox invalid values are entered.
Note: Users can only enter values in textbox name quantity and this textbox will be validated from the textbox checkquantity.
Please check my below code and suggest me a solution for this.
$('input[name="quantity"]').keyup(function() {
var $tr = $(this).closest("tr");
var q = +$tr.find('input[name^="quantity"]').val();
var cq = +$tr.find('input[name^="checkquantity"]').val();
if (q > cq) {
$('#submtbtnId').attr('disabled', 'disabled');
}
else {
$('#submtbtnId').removeAttr('disabled');
}
});
----------------------------------- in
while loop my list is iterating
{
<tr>
<td width = "10%">
<input type = "text" name = "quantity"values = "" id = "quantity" / >
<input type = "text" name = "checkquantity" disable = "disable"
values = "random values coming from my list
eg. 5 or 9 ..." / > < /td>
</tr >
}
-------------------------
< input type = "submit" id = "submtbtnId" / >​
If that's the case every time in the keyup event check all the textboxes by iterating over them..
UPDATE
Looks like the issue is with the attribute named values .
If you are trying to access the value using .val() then it is supposed to be value.
Added the return false; condition to make sure it breaks out of the loop when the condition fails.
Secondly there was one more issue.. Lets say the input is empty .. So when you convert that to a number then it is 0 and the comparison always fails..
So i have added a check condition if the field is not empty , only then convert to the number
$('input[name="quantity"]').on('keyup', function() {
var check = false;
$('tbody tr').each(function() {
var $tr = $(this);
var q = $tr.find('input[name^="quantity"]').val();
if(q != ''){
q = +q;
}
var cq = +$tr.find('input[name^="checkquantity"]').val();
if (q !== '' && q > cq) {
check = true;
return false;
}
});
if (check) {
$('#submtbtnId').prop('disabled', true);
}
else {
$('#submtbtnId').removeAttr('disabled');
}
});​
Check Fiddle

Focus on first invalid text field after form validation

I have a pretty standard HTML form in which I collect user input. I have a submit button that will run a JavaScript function (onClick) that in turn validate the data entered by the users.
The function looks like this:
function validateForm()
{
var isValid = true;
var txtFirstname = document.getElementById("firstName").value;
var txtLastname = document.getElementById("lastName").value;
(etc...)
/*Validate First Name*/
if(txtFirstname.length <= 0){
document.getElementById("lblFirstName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblFirstName").innerHTML="";
document.getElementById("firstName").value = txtFirstname;
}
/*Validate last Name*/
if(txtLastname.length <= 0){
document.getElementById("lblLastName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblLastName").innerHTML="";
document.getElementById("lastName").value = txtLastname;
}
(etc...)
if(isValid){
document.formX.submit();
}
else{
return false
}
}
My question is: how can I set the focus on the first "invalid" textbox after the function has validated the form?
Thanks,
Eric
i search 4 it & find a better popular solution :
`$("#"+document.querySelectorAll(":invalid")[1].id).focus();`
it's work for me. note that index of first invalid input in Firefox is 1 not 0. because of in FF the form is invalid and count, when an invalid input exist.
It would be cleaner if you functionally decomposed your validation. Then you could have a variable called "firstInvalidField" which is initially set to null. Upon invalidation of a field, check to see if firstInvalidField is null, if it is, set it to the textBox in question. If it is not null, skip over the code.
After the validation is complete, if the firstInvalidField variable is not null, call .focus() on it.

Categories