Jquery on keypress - javascript

I'm looking for a function that gives an alert when a certain character key (g) is pressed in the first position of a postal code, and then disables the submit button if the postal code has a letter G in the beginning.
Is this possible?
My current code to detect a key up on the postal code field at the moment is this:
$(document).ready(function() {
var someTextInputField = "#postal-code";
$(someTextInputField).on("keyup", function() {
alert('not a valid postal code');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="postal-code" />

Javascript without extra libraries
document.addEventListener("input", function(e) {
if (e.target.id === "postal-code") {
var disable = /^g/i.test(e.target.value),
submit = document.getElementById("submit");
if (disable && !submit.disabled) {
alert("You cannot start a postal code with a G");
}
submit.disabled = disable;
}
});
<input placeholder="Address" />
<input id="postal-code" placeholder="Postal Code" />
<button id="submit">Submit</button>
jQuery
$(document).on("input", "#postal-code", function (e) {
var disable = /^g/i.test(this.value),
$submit = $("#submit");
if (disable && !$submit.prop("disabled")) {
alert("You cannot start a postal code with a G");
}
$submit.prop("disabled", disable);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Address" />
<input id="postal-code" placeholder="Postal Code" />
<button id="submit">Submit</button>

Check this fiddle http://jsfiddle.net/oyc2L9sy/12/
html:
<input id="test" type="text" />
javascript:
$(document).ready(function() {
$("#test").on("keypress", function(e) {
if ((e.keyCode == '65') ||
(e.keyCode == '71')) {
alert('not a valid postal code');
return false;
}
});
});

You can use this.value[0] to get the first character of the input. Then test whether it's one of the allowed characters.
$("#input").on("keyup", function() {
if (this.value != '') {
var firstchar = this.value[0].toUpperCase();
if (firstchar != 'A' && firstchar != 'G') {
alert('not a valid postal code');
$("#submitID").prop("disabled", true);
} else {
$("#submitID").prop("disabled", false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input"/>

Related

Not able to disable comma in textarea

Below is the code where textarea will be created automatically. But i want to disable comma in this textarea,so i am using the below javascript function.
$(document).ready(function(){
var counter = 1;
var val;
$("#addButton").click(function () {
var person = prompt("Please enter the Field name:", "");
if (person == null || person == "") {
return false;
} else {
val = person;
}
if(tabid == "menu4"){
return false;
}
//alert(tabid);
var newTextBoxDiv0 = $(document.createElement('div'))
.attr("class", 'form-group row')
.attr("id",'form1ac' + counter);
newTextBoxDiv0.after().html('<div class="col-xs-1"><input type="button" value="delete" onclick= rem(form1ac'+counter+')></div><div class="col-xs-1"><button type="button" class="btn btn" name="" id="buttonl" style="width: 170px;height:45px;background-color:#dcdcdc;color:black;">'+val+'</button><input type="hidden" name="buttonl" form="form1" value='+val+'></div><div class="col-xs-2"></div><div class="col-xs-4"><div class="form-group"><textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, "2")" ></textarea></div><input form="form1" type="hidden" name="tabid" value='+tabid+'></div>');
newTextBoxDiv0.appendTo('#'+tabid);
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#form1ac" + counter).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, "2")" ></textarea>
The above jquery code will dynamically create new textarea with label option,which works perfectly. But i am trying to disable comma with the above mentioned javascript code which is not working perfectly.
Please help me!
If you want to prevent user to type a comma:
<textarea class="no-comma"></textarea>
And
$(function() {
$('textarea.no-comma').on('keydown', function(e) {
if (e.keyCode == 188 || e.keyCode == 110) { // thats a comma
e.preventDefault();
}
}).on('change input', function() {
var self = $(this);
self.html( self.html().replace(new RegExp(',', 'g'),'') ); // Remove all commas.
});
})
Your html has a syntax error "2")" >
Should be '2')" >
<textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, '2')" ></textarea>
In place of below code
<textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, "2")" ></textarea>
use below code
<textarea form="form1" name="df" id="df" oninput = 'this.value = this.value.replace(/[,]/g, "2")' ></textarea>

recheck password character by character while typing

I'm working on recheck password while typing.Can anyone help me with the code that checks while typing password that shows a notification if it doesn't match entirely character by character while typing and that checks the length too when submit button is pressed in jquery or javascript
You can do this by several ways. This DEMO will solve your problem by using Jquery validation.
HTML
<form class="validatedForm" id="commentForm" method="get" action="">
<fieldset>
<input name="user[password]" id="user_password" required/><br>
<input name="user[password_confirmation]" required/>
</fieldset>
</form>
<button>Validate</button>
JQuery
jQuery('.validatedForm').validate({
rules: {
"user[password]": {
minlength: 3
},
"user[password_confirmation]": {
minlength: 3,
equalTo : "#user_password"
}
}
});
$('button').click(function () {
console.log($('.validatedForm').valid());
});
Original answer - https://stackoverflow.com/a/9717644/7643022
That answer gives you the solution to what you need. I have just modified the answer to what you desire.
html
<div class="td">
<input type="password" id="txtNewPassword" />
</div>
<div class="td">
<input type="password" id="txtConfirmPassword" onChange = "checkPasswordMatch();" />
</div>
<div class="registrationFormAlert" id="divCheckPasswordMatch">
</div>
<div><input type="submit" id="submitbtn"/></div>
JQuery
var incorrectFlag = false;
function checkPasswordMatch() {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();
if (password != confirmPassword)
incorrectFlag = true;
else
incorrectFlag = false;
}
$(document).ready(function () {
$("#txtConfirmPassword").keyup(checkPasswordMatch);
$("#submitbtn").onclick(function(e){
e.preventDefault();
if (incorrectFlag){
alert("Password Incorrect");
} else {
$('form').submit();
}
});
});
The Actual password should be retrieved and stored somewhere, here I assumed it should be stored in the hidden input.
$(document.ready(
var actual_password = $("#hidden_input_password").val();
$( "#password_text_box" ).keyup(function(event) {
var input_Password = $(this).val();
if(input_Password.length > actual_password.length)
{
event.preventDefault();
event.stopPropogation();
return;
}
elseif(input_Password.length === actual_password.length){
if(input_Password===actual_password)
{
return;
}
else{
event.preventDefault();
event.stopPropogation();
$(this).addClass("notification");
return;
}
}
else{
if(input_Password!===actual_password.slice(0,input_Password.length))
{
event.preventDefault();
event.stopPropogation();
$(this).addClass("notification");
return;
}
}
});
);

OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript

I have a form which validates password null/blank or not using onblur. And I use a submit button to submit the form. However the submit button needs to be clicked twice before to work. It does not work on the first click after something has been filled in the password box. Below is the code.
With respect to Jquery, I require solution in pure Javascript.
I have tried onkeyup, but that is not a good solution as it will put strain on system, and server (for ajax).
<!DOCTYPE html>
<html>
<body>
<script>
var error_user_password = false;
function checkpw(){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall() {
checkpw()
if(error_user_password == false) {
return false;
} else {
return true
}
}
</script>
</body>
<form id="joinform" method="post" name="joinform" action="#hello" onsubmit="return submitall()" >
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password" onblur="checkpw()" />
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
</html>
OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript
This happens because the blur event is captured from the onblur event handler and not bubbled to the form submit button.
A full javaScript solution is based on:
addEventListener
activeElement: inside the blur event I check after 10 milliseconds if the submit button get the focus.
My snippet:
var error_user_password = false;
function checkpw(ele, e){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_password == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_password').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>

check all input values of same class is empty jquery

Here I have many input text fields with same class like
<input type="text" class="MyClass"></input>
<input type="text" class="MyClass"></input>
<input type="text" class="MyClass"></input>
My requirement is to check wheather all input fields of this class is empty or not.
I've tried this
if(!('.MyClass').val()){
alert("empty");
}
But it doesn't make any result. Can anyone help?
You can check
$('button').click(function() {
var $nonempty = $('.MyClass').filter(function() {
return this.value != ''
});
if ($nonempty.length == 0) {
alert('empty')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<button>test</button>
Or using a flag
$('button').click(function() {
var flag = false;
$('.MyClass').filter(function() {
if (this.value != '') {
flag = true;
//no need to iterate further
return false;
}
});
if (!flag) {
alert('empty')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<button>test</button>
You can compare the length of number of input with number of empty input using :
var allemptylength=$(".MyClass").filter(function() {
return this.value.length !== 0;
})});
if($('.MyClass').length== allemptylength.length){
alert("all empty");
}
Working Demo
To make sure each classes are checked, use
$.each($('.MyClass'),function() {
if ($(this).val().length == 0) {
alert('empty');
}
});
You can check it like this:
var isEmpty = !$('.MyClass').filter(function() {
return this.value.trim();
}).length;
Also remove all </input> tags. input elements are self-closable.
try this
var hasNoValue;
$('.MyClass').each(function(i) {
if ($(this).val() == '') {
hasNoValue = true;
}
});
if (hasNoValue) {
alert('All have no value');
}
try is(':checked')
$('.MyClass').each(function(){
alert($(this).is(':checked');)
});
this will alert only the checked elements.
$('input').each(function(index,value){
if($(this).val()!=''){
$(this).addClass('success');
}else{
$(this).removeClass('someClass');
$(this).addClass('warning');
$(this).css('border', '1px solid red');
//do something else...
}
});
Try this . 100% working..
var emptyLength = $(".MyClass").filter(function() {
return this.value == "";
}).length;
if (emptyLength > 0)
{
alert("Please enter all peramerter's value");
return;
}
Thanks.
Try this. It works for me
var flag = 1;
$(".MyClass").each(function(i){
if ($(this).val() == "")
flag++;
});
if (flag == 1)
alert('all have values');
else
alert('some or all doesn\'t have value');

Block enter key when less than 4 digits entered

I'm trying to implement a code in my script that will block enter key until 4 digits entered in a text field.
Here are my forms:
<div id="inputtext">
<input type="text" id="dreamtext" maxlength="45" spellcheck='false' autofocus/>
<input type="submit" id="nextstepbutton" value="next step" onclick="window.open('step3.html','_self','resizable=yes')" />
</div>
This particular script hides submit button when < 4 characters entered and shows it when 4 or more entered. It also modifies some div content.
<script type="text/javascript">
$(function(){
$("#nextstepbutton").hide();
$("#dreamtext").keyup(function() {
var val = $(this).val();
if (val.length > 3) {
$('#nextstepbutton').show();
document.getElementById("message").innerHTML = "<h1>hit return or next step</h1>";
}
else {
$('#nextstepbutton').hide();
document.getElementById("message").innerHTML = "<h1>type please</h1>";
}
});
});
</script>
This script presses submit button when enter key pressed
<script type="text/javascript">
$("#dreamtext").keyup(function(event){
if(event.keyCode == 13){
$("#nextstepbutton").click();
}
});
</script>
Now, what is the best way to block the enter key when less than 4 digits entered? Thanks
There is a method in the keydown(/up/press) event called preventDefault.
This makes any default action not happen.
$("#dreamtext").keyup(function(event) {
if ($(this).val().length < 4) {
event.preventDefault();
}
if (event.keyCode == 13) {
$("#nextstepbutton").click();
}
});
You could also connect it to the jQuery .submit() handler.
$("#someForm").submit(function(){
if ($("#dreamText").val().length < 4) {
return false;
}
})

Categories