call a JS function inside an event method - javascript

I hope I'm not repeating a question but I've searched around and couldnt find help so I thought I should ask directly, I'm still a beginner and this is an assignment for my class so please be as thorough as possible
I'm trying to create a form where as the user clicks on another field, it checks if the input he put in the first one is as required by the website, without having to click enter or a submit button.
this is the HTML file.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="test.js"></script>
<script>
$(document).ready(function(){
$("div.ID").focusin(function(){
$(this).css("background-color", "#FFFFCC");
});
$("div.ID").focusout(function(){
$(this).css("background-color", "#FFFFFF");
userid_validation(userid,5,12);
});
});
</script>
</head>
<body>
<div class="ID" >
User ID: <input type="text" name="userid" size="12" />
</div>
<div class="pass">
Password: <input type="text" name="psw" size="12" />
</div>
</body>
</html>
and this is the JS file
function userid_validation(userid,mx,my)
{
var uid_len = userid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty / length be between "+mx+" to "+my);
//uid.focus();
return false;
}
return true;
}
I'm most probably doing something completely wrong but I don't know what. thanks in advance !

You need to apply focusin and foucsout on input elements. Currently you have applied it on div. Also you have code error on calling following function,
userid_validation(userid, 5, 12); // userid not defined.
Please check if this works.
function userid_validation(userid, min, max) {
var uid_len = userid.length;
if (uid_len == 0 || uid_len > max || uid_len < min) {
alert("User Id should not be empty / length be between " + min+ " to " + max);
//uid.focus();
return false;
}
return true;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="test.js"></script>
<script>
$(document).ready(function() {
$("div.ID").find('input').focusin(function() {
$(this).css("background-color", "#FFFFCC");
});
$("div.ID").find('input').focusout(function() {
$(this).css("background-color", "#FFFFFF");
userid_validation($(this).val(), 5, 12);
});
});
</script>
</head>
<body>
<div class="ID">
User ID:
<input type="text" name="userid" size="12" />
</div>
<div class="pass">
Password:
<input type="text" name="psw" size="12" />
</div>
</body>
</html>

Related

Show Popover when keydown and keyup on input

How Can I Copy Number entered by the user and show on a Popover via javascript or jquery?
I mean when user typed numbers biger than zero, forexample: 1000, popover Show 1000.
$(document).ready(function() {
//this calculates values automatically
getPriceAndPopUp();
$("#price").on("keydown keyup", function() {
getPriceAndPopUp();
});
});
function getPriceAndPopUp() {
var price = document.getElementById('price').value;
if (!isNaN(price) && price > 0) {
alert(price);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form>
Price:<br>
<input type="number"
name="price"
id="price"
class="form-control"
min="0"
required />
</form>
</body>
You need to wait for the user to finish typing before you show the number, to do that you need to delay the alert show using a timeout function
$(document).ready(function() {
var timeout;
//this calculates values automatically
getPriceAndPopUp();
$("#price").on("keydown keyup", function() {
clearTimeout(timeout);
timeout = getPriceAndPopUp();
});
});
function getPriceAndPopUp() {
var price = document.getElementById('price').value;
return setTimeout(function() {
if (!isNaN(price) && price > 0) {
$('[data-content]').attr('data-content',price);
$('[data-toggle="popover"]').popover('show');
}
}, 400);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<body>
<form>
Price:<br>
<input type="number" name="price" id="price" class="form-control" min="0" required data-toggle="popover" data-placement="bottom" data-content="0"/>
</form>
</body>
You can do it on blur event.
$(document).ready(function() {
//this calculates values automatically
getPriceAndPopUp();
$("#price").on("blur", function() {
getPriceAndPopUp();
});
});
function getPriceAndPopUp() {
var price = document.getElementById('price').value;
if (!isNaN(price) && price > 0) {
alert(price);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form>
Price:<br>
<input type="number" name="price" id="price" class="form-control" min="0" required />
</form>
</body>

match GSTIN number with PAN number

I have two numbers GSTIN and PAN
I want to match GSTIN number Starting later 3 to 12 it would equal to PAN Number.
it should generate an alert, if it doesn't match
For example
My PAN is : 1234567891
My GSTIN is : aa1234567891bbb
Then it is correct
BUT
My PAN is : 1234567891
My GSTIN is : aa7894561239bbb
Then it is wrong
I searched on google but cant find any solution, It is possible? Please guide me in right direction.
i tried below code with substr, but i cant able to get that value
var pan = document.getElementById("pan");
var unino = document.getElementById("gstin");
var res = unino.substr(2, 11);
document.getElementById("button").addEventListener("click", function() {
alert( pan.value+'&'+res.value );
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<style type="text/css">
</style>
<body>
<div class="container">
<form method="post">
<div class="form-group">
<label>PAN</label>
<div class="input-group">
<input pattern=".{10,10}" maxlength="10" required="" type="text" class="form-control" name="pan" id="pan" placeholder="PAN No 10 digist" value="" title="PAN Number must be 10 character"/>
</div>
</div>
<div class="form-group">
<label>gstin</label>
<div class="input-group">
<input required="" type="text" class="form-control" name="gstin" id="gstin" placeholder="gstin" value=""/>
</div>
</div>
<input type="submit" name="submit" value="submit" class="btn btn-primary" id="button">
</form>
</div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
This is the updated js chunk which would work for you. But this would only validate the lengths and if GSTIN contains PAN.
var pan = document.getElementById("pan");
var unino = document.getElementById("gstin");
document.getElementById("button").addEventListener("click", function() {
if (!(unino && unino.length == 15 && unino.indexOf(pan) == 2)){
alert( pan.value+'&'+res.value );
}
});
There should be regex validations also I suppose for the correct format of both in HTML.
The pattern for pan should be - "[A-Za-z]{5}[0-9]{4}[a-zA-Z]"
That for GSTIN should be - "[0-9]{2}[A-Za-z]{5}[0-9]{4}[a-zA-Z][0-9]{1}[a-zA-Z]{1}[0-9]{1}"
Just search for PAN string in GST string. if it finds PAN string in GST and index is 2 then there is a match. Otherwise NOT.
Hope that helps.
You can use search method as below
GST.search(PAN);
I found my answer.
document.getElementById("button").addEventListener("click", function() {
var pan = document.getElementById("pan").value;
var unino = document.getElementById("gstin").value;
var res = unino.substr(2, 10);
if(pan!=res){
alert("Wrong GSTIN Number...!");
}else{
alert("GST Number is matched.");
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<style type="text/css">
</style>
<body>
<div class="container">
<form method="post">
<div class="form-group">
<label>PAN</label>
<div class="input-group">
<input pattern=".{10,10}" maxlength="10" required="" type="text" class="form-control" name="pan" id="pan" placeholder="PAN No 10 digist" value="" title="PAN Number must be 10 character"/>
</div>
</div>
<div class="form-group">
<label>gstin</label>
<div class="input-group">
<input required="" type="text" class="form-control" name="gstin" id="gstin" placeholder="gstin" value=""/>
</div>
</div>
<input type="button" name="submit" value="submit" class="btn btn-primary" id="button">
</form>
</div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
Pass Value To Function
//get value of StateCode / PAN Number / GST Number
var chkGstNum = checkGstNumber(stateCode, panNum, gstNum);
if(chkGstNum == 0) // Error Code
else // Success Code
Function
function checkGstNumber(stateCode, panNum, gstNum)
{
var GstateCode = gstNum.substr(0, 2);
var GpanNum = gstNum.substring(2, 12);
var GEnd = gstNum.substring(12,14);
if(stateCode != GstateCode)
{
alert("Invalid GST Number.");
return false;
}
if(panNum != GpanNum)
{
alert("Invalid GST Number.");
return false;
}
if(GEnd != '1Z')
{
alert("Invalid GST Number.");
return false;
}
if(gstNum.length != 15)
{
alert("Invalid GST Number.");
return false;
}
return true;
}

validation for dynamically created input without using form

i am newbie. i want to validate my dynamically created text fields.
unfortunately i couldnt use <form> as i am using it in django. i could have used jquery validator if i had used <form>. now how do i validate these fields.
my simple code looks like
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$(".errMsg").hide();
var data = "";
for(var i =0;i<5;i++){
data = data + "Name : <input type='text' id='name"+i+"' class='required' > Age : <input type='text' id='age"+i+"' class='required' ><br>";
}
$("#mytable").html(data);
$("#clickbtn").click(function(){
for(var j=0;j<5;j++){
if($("#name"+j).val() == ""){
alert(j);
$("#name"+j).focus();
$(".errMsg").show();
}
if($("#age"+j).val() == ""){
$("#age"+j).focus();
$(".errMsg").show();
}
if(isNan($("#age"+j).val())){
$("#age"+j).focus();
$(".errMsg1").show();
}
}
});
});
</script>
</head>
<body>
<h1>Register here</h1>
<div id="mytable"></div>
<button id="clickbtn">click</button>
<div class="errMsg">This is required</div>
<div class="errMsg">Invalid age</div>
</body>
</html>
i want to validate all the fields and if field is empty i want to highlight everything and display error msg under that texbox.
in this code i could focus only last textbox. how to do it for all.
Please help me.. thank you
isNan is typo error. It should be isNaN.
And please return false in every condition so the script execution will stop there and that particular element will focused.
Please check below snippet for more understanding.
$(document).ready(function(){
$(".errMsg").hide();
var data = "";
for(var i =0;i<5;i++){
data = data + "Name : <input type='text' id='name"+i+"' class='required' > Age : <input type='text' id='age"+i+"' class='required' ><br>";
}
$("#mytable").html(data);
$("#clickbtn").on('click', function(){
for(var j=0;j<5;j++){
if($("#name"+j).val() == ""){
$("#name"+j).focus();
$(".errMsg").show();
return false;
}
if($("#age"+j).val() == ""){
$("#age"+j).focus();
$(".errMsg").show();
return false;
}
if(isNaN($("#age"+j).val())){
$("#age"+j).focus();
$(".errMsg1").show();
return false;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mytable"></div>
<button id="clickbtn">click</button>
<div class="errMsg">This is required</div>
<div class="errMsg">Invalid age</div>
Try this,
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$(".errMsg").hide();
var data = "";
for(var i =0;i<5;i++){
data = data + "Name : <input type='text' id='name"+i+"' class='required' > Age : <input type='text' id='age"+i+"' class='required' ><br>";
}
$("#mytable").html(data);
$("#clickbtn").on('click', function(){
for(var j=0;j<5;j++){
if($("#name"+j).val() == ""){
alert(j);
$("#name"+j).focus();
$(".errMsg").show();
}
if($("#age"+j).val() == ""){
$("#age"+j).focus();
$(".errMsg").show();
}
if(isNan($("#age"+j).val())){
$("#age"+j).focus();
$(".errMsg1").show();
}
}
});
});
</script>
</head>
<body>
<h1>Register here</h1>
<div id="mytable"></div>
<button id="clickbtn">click</button>
<div class="errMsg">This is required</div>
<div class="errMsg">Invalid age</div>
</body>
</html>
Try below code this will may be help you out
$(document).on('click', '#clickbtn',function (){
//Write your code
})

How do i get rid of the NaN in the text box in my JavaScript and HTML code?

I'm trying to make a triangle Hypotenuse calculator. First you put one leg, then the other leg, then you will get the Hypotenuse. But, if you fill in the second box first, It will say NaN. I know its not that important, but is there a way to get rid of it so it says "0" until both boxes are filled? And here is the code:
<html>
<head>
<script type="text/javascript">
function hypotenuse(a,b){
return Math.sqrt(a*a + b*b);
}
</script>
</head>
<body>
<input type="button" value="Hypoteneuse";" />
A:<input type="text" id="leg1" size="2";" />
B:<input type="text" id="leg2" size="2" onChange="document.getElementById('result').value=hypotenuse(parseInt(document.getElementById('leg1').value),parseInt(document.getElementById('leg2').value));" />
Hypotenuse:<input type="text" placeholder="0" id="result" size="2" />
</body>
</html>
You could set a default value on the first input:
<input type="text" id="leg1" size="2" value="0" />
Or you could bind your function to the click of a button and do some validation before you attempt the calculation (fiddle):
var leg1 = document.getElementById('leg1');
var leg2 = document.getElementById('leg2');
function hypotenuse(a,b){
return Math.sqrt(a*a + b*b);
}
document.getElementById('submit').addEventListener('click', function() {
// Check both fields are populated. This validation could
// be more sophisticated if you needed it to be.
if (leg1.value !== '' && leg2.value !== '') {
document.getElementById('result').value = hypotenuse(parseInt(leg1.value),parseInt(leg2.value));
} else {
// You could display an error message here
console.log('Please fill out both fields');
}
});
You can use isNaN() to check whether your values exist or not:
<script type="text/javascript">
function hypotenuse(a,b){
if (isNaN(a) || isNaN(b)) {
return 0;
}
return Math.sqrt(a*a + b*b);
}
</script>
You could do something like this:
Javascript:
function hypotenuse(){
var angleA = document.getElementById['leg1'].val;
var angleB = document.getElementById['leg2'].val;
if(angleA != '' && angleB != ''){
var angleC = Math.sqrt(a*a + b*b);
document.getElementById['result'].val = angleC;
}
}
Your HTML would look like
A:<input type="text" id="leg1" size="2" onblur="hypotenuse()" />
B:<input type="text" id="leg2" size="2" onblur="hypotenuse()" />
Hypotenuse:<input type="text" placeholder="0" id="result" size="2" />

Jquery select NEXT text field on Enter Key Press

I have made a page using jquery, and on load it selects the first text field automatically. I want it to then move to the next field when the ENTER key is pressed.
$('.barcodeField input').bind('keyup', function(event) {
if(event.keyCode==13){
$("this + input").focus();
}
});
I can't find anything that works on the net. And I've scoured the forums.
I've created a little function which can do what you need. This is the version I use so you may need to change the class names but you should get the idea.
<script type="text/javascript">
$(document).ready(function(){
$(".vertical").keypress(function(event) {
if(event.keyCode == 13) {
textboxes = $("input.vertical");
debugger;
currentBoxNumber = textboxes.index(this);
if (textboxes[currentBoxNumber + 1] != null) {
nextBox = textboxes[currentBoxNumber + 1]
nextBox.focus();
nextBox.select();
event.preventDefault();
return false
}
}
});
})
</script>
So basically:-
Get all the input fields matching .vertical
Find which is the current text box
Find the next one
Set the focus on that one
You should use:
$(this).next('input').focus();
try this:
(function($){
$.fn.enterNext = function(){
var _i =0;
$('input[type=text], select',this)
.each(function(index){
_i = index;
$(this)
.addClass('tab'+index)
.keydown(function(event){
if(event.keyCode==13){
$('.tab'+(index+1)).focus();
event.preventDefault();
}
});
})
$( "input[type=submit]",this ).addClass('tab'+(_i+1));
}})(jQuery);
for use:
$('form.element').enterNext();
in my case this is the best solution in that I got because the function .next() is strict with elements outside their branch DOM.
The best way is to force an index.
and sorry for my bad English...
Basically, you just need top have the DOM elements in some structure so that you can select the next one. I'd suggest exploiting tabindex, but anything that let's you have a defined order will work.
Here is the solution I came up with. The issue I had was that I needed to maintain tabindex, i.e. it had to function exactly that same as hitting tab. It uses both underscore and jquery.
I've left in my debugging code:
try {
var inputs = $("input[id^=tpVal-]");
var sortedInputs = _.sortBy(inputs, function(element){
var tabIndex = $(element).attr('tabindex');//debugging
var id = $(element).attr('id');//debugging
console.log(id +" | "+ tabIndex +" | "+ $(element));//debugging
return parseInt($(element).attr('tabindex'));
});
$(sortedInputs).each(function (index, element) {
$(element).keyup(function(event){
if(event.keyCode==13) {
var $thisElement = $(element);//debugging
var nextIndex = index+1;//debugging
var $nextElement = $(sortedInputs[nextIndex]);
var thisId = $thisElement.attr('id');//debugging
var nextId = $nextElement.attr('id');//debugging
console.log("Advance from "+thisId+" to "+nextId);//debugging
if($nextElement!=undefined) {
$(sortedInputs[index + 1]).focus();
}
}
});
});
} catch (e) {
console.log(e);
}
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input id="122" class='TabOnEnter' tabindex="1" /><br>
<input id="123" class='TabOnEnter' tabindex="2" /><br>
<input type="text" name="abc" /><br>
<input type="text" name="abc1" /><br>
<input type="text" name="abc2" /><br>
<input type="text" name="abc3" class='TabOnEnter' tabindex="3" /><br>
<input class='TabOnEnter' tabindex="4" /><br>
<input class='TabOnEnter' tabindex="5" /><br>
<input class='TabOnEnter' tabindex="6" /><br>
<!-- <textarea class='TabOnEnter' tabindex="6">Hi, I am a test area</textarea>-->
<input type="submit" value="submit" class='TabOnEnter' tabindex="7">
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).on("keypress", ".TabOnEnter", function (e)
{
//Only do something when the user presses enter
if (e.keyCode == 13)
{
var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
console.log(this, nextElement);
if (nextElement.length)
nextElement.focus()
else
$('[tabindex="1"]').focus();
}
});
//Hidden inputs should get their tabindex fixed, not in scope ;)
//$(function(){ $('input[tabindex="4"]').fadeOut(); })
</script>
</body>
</html>
This code works for me
HTML:
<div class="row">
<div class="col-md-3"> Name </div>
<div class="col-md-3"> <input type="text" /> </div>
</div>
<div class="row">
<div class="col-md-3"> Email</div>
<div class="col-md-3"> <input type="email" /> </div>
</div>
Jquery code:
$(document).on('keypress', 'input,select', function (e) {
if (e.which == 13) {
e.preventDefault();
$(this).parent().parent().next('div').find('input').focus();
}
});

Categories