Username Length Verification jQuery - javascript

I am attempting to create jQuery form which is automatically updated every time the user clicks.
At the moment I am working on querying if the username is correct length; if it is not, it will make the input box outlined red.
This is my current code (which does not seem to function at all).
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$(document).click(function(e) {
if (!$(e.target).closest('#jq-user-getval').length) {
if ( $('#jq-user-getval').val() != '' ) {
if( $("#jq-user-getval").val() < 4) {
$("#jq-user-getval").addClass('border-force');
}
}
}
})
})
</script>
as you can see, I have made it so that when the user clicks away from the input box, it will check if the box is empty. If it is empty, it will check if the length is less than 4 characters, then it is supposed to add a class forcing the red outline. This is not working, however.
this is the HTML, I am unsure if the problem lies here or not:
<form action="" method="post">
<input id="jq-user-getval jq-user-class" type="text" name="username">
</form>
I am trying to replicate Microsoft's "Hotmail" registration form, if you can suggest any changes.

Your id value is incorrect. Technically, id cannot contain spaces. Change your <input /> to:
<input id="jq-user-getval" class="jq-user-class" type="text" name="username" />
The way you are using .val() < 4 is also wrong. You cannot compare like that with a string:
"hello" < 4; // This is meaningless.
"hello".length < 4; // You should use this.
Use .blur() function for this:
$(function () {
$("#jq-user-getval").blur(function () {
if (this.value.trim().length !== 0 && this.value.trim().length < 4)
$(this).addClass("border-force");
});
});
If you are dynamically loading the <input />, then you can delegate the event this way:
$(function () {
$(document).on("blur", "#jq-user-getval", function () {
if (this.value.trim().length !== 0 && this.value.trim().length < 4)
$(this).addClass("border-force");
});
});
I have added .trim() for extra security, like people might get away putting spaces.
There's no real reason for you to use the .click() function anywhere here. The clicking away really triggers blur event on the <input />.

You can use Jquery Validation.
Basic Example :
<input id="username" name="username" maxlength="4" type="text" required>
$("#yourFormID).validate();
if input is not valid and then you addClass red outline
you must use errorPlacement,errorClass properties in validate() function

Related

If input has value and radio button is checked remove disabled class from anchor tag

I'm trying to achieve condition, when input has value greater than 1 and radio button is checked then remove disabled class from the anchor.
This is my code
<input name="age" id="age" type="text">
<input name="education" type="radio" value="univeristy">
Calculate
$("input").keyup(function () {
if ($("#age").val().length > 1 && $('input[name=education]:checked')) {
$("#diploma").removeClass("disabled");
} else {
$("#diploma").addClass("disabled");
}
});
It is triggering after input has value without checking radio is checked.
Can anyone help me with this?
Thanks in advance.
Using :checked is fine. But it doesn't return a boolean. You need to check that it returns an element. $(':prop').length > 0 (or using prop('checked')).
Some other stuff you need to change.
The condition should not be on the $("#age").val().length but on the $("#age").val() itself.
Use checkbox, not radiobutton. radiobutton is used to choose one option from others, not to set true/false.
You need to check the values on input keyup, but also on change of the radio (or checkbox).
Try this:
$("input").keyup(function () {
if ($("#age").val().length > 1 && $("input[name='education']").is(':checked')) {
$("#diploma").removeClass("disabled");
} else {
$("#diploma").addClass("disabled");
}
});
Use prop('checked') to check radio, refer code below,
$( document ).ready(function() {
$("input").keyup(function () {
if ($("#age").val().length > 1 && $("input[name='education'][value='univeristy']").prop("checked")) {
$("#diploma").removeClass("disabled");
console.log("Removed class 'disabled'");
} else {
$("#diploma").addClass("disabled");
console.log("Added class 'disabled'");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input name="age" id="age" type="text">
<input name="education" type="radio" value="univeristy">
Calculate
</body>
Run this code and see console log.

Replace class on clicking outside div

I have some javascript which essentially removes a class which has a background image on focus, i.e clicking in the input box (which has the background image).
The code is as follows:
$(function(){
$("#ets_gp_height").focus(function(){
if(!$(this).hasClass("minbox")) {
} else {
$(this).removeClass("minbox");
}
});
});
This works well, and removes .minbox when the user clicks within the input field, however what i want to do is if the user makes no changes to the input field, it should add the class back in as per at the beginning. At the moment, once the user clicks once, the class is gone for good, i would like it to come back if the user makes no changes to the input box, so for example clicks the input field but then clicks back out again without entering anything.
Any help? Possible?
I'm assuming you don't want the class .minBox to be added if the user has entered a value, but only if they decided not to enter anything, or chose to erase what they had entered.
To do this, you can use the blur event and check if there's anything entered:
$("#ets_gp_height").blur(function()=> {
if($(this).val().length < 1) $(this).addClass('minBox');
});
This will work for TABing out of the input and CLICKing out of it.
$(document).on("blur", "#ets_gp_height", function(){
if($(this).val() == '') {
$(this).addClass('minBox');
}
});
This code will add class 'minBox' when ever user goes out of input field without entering any value.
A working example, with and without jQuery:
Note: with onblur solution, method is called each time the field is blured, even when the value hasn't changed. with onchange solution, method is called only when the value has changed. That why onchange is a better solution.
WITHOUT JQUERY
function onChange(input){
input.value.length > 0 || setClassName(input, 'minbox') ;
}
function onFocus(input){
if(input.className == 'minbox')
{
input.className = '' ;
}
}
function setClassName(o, c){ o.className = c; }
input.minbox {background-color:red;}
<input type="text" id="ets_gp_height" class="minbox" onchange="onChange(this)" onfocus="onFocus(this)">
WITH JQUERY:
$(function(){
$("#ets_gp_height").change(function(){
$(this).val().length > 0 || $(this).addClass("minbox");
})
$("#ets_gp_height").focus(function(){
if(!$(this).hasClass("minbox")) {
} else {
$(this).removeClass("minbox");
}
});
});
input.minbox {background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ets_gp_height" class="minbox">

Prevent user from entering additional characters when maximum length reached

Using angularjs, I'm not satisfied with the ng-maxlength tag. I want the input field to block the user from entering additional characters when the max length has been hit. So instead of ng-maxlength, I tried writing a directive that would validate the input on keydown/keypress:
.directive('vldMaxLength', function() {
return function (scope, element, attr) {
element.bind('keydown keypress', function (event) {
if(event.target.value.length >= 10 && (event.which !== 8 && event.which !== 46)) {
event.preventDefault();
}
});
};
})
This works decently, but the user is unable to highlight a portion of the string and replace with different characters. Maybe there's something I can add to the directive to allow for this? Or maybe there's an easier way to get this functionality instead of using a directive.
JSFiddle: http://jsfiddle.net/DwKZh/147/
You could use the straight HTML version:
<form action="demo_form.asp">
Username: <input type="text" name="usrname" maxlength="10"><br>
<input type="submit" value="Submit">
</form>

jquery each for all text boxes

I am using following script to bind a keypress event on each textbox so that on reaching the maxlength, focus will switch to next input field. Passing classname as the prarameters to the function.
function autoFocusPhoneFields(txtbox1ID,txtbox2ID) {
$('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() {
$(this).bind('keypress', function(){
if(this.value.length == $(this).attr('maxlength')) {
$(this).next('input').focus();
}
});
});
}
$(document).ready(function(){
autoFocusPhoneFields('mobileprefix','mobilecode');
});
As i have mentioned two different input ..it is runnign fine. Butis there any way around so that it will get the classnames and runs through each input box to attach keypress event.
If I understand you correctly, you want to attach the same event handler to every input field? Just use the selector:
$(':text')
(for all input type="text") fields.
So just change
$('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() {
to:
$(':text').each(function() {
If I get you correctly you just need to use type selector for input. You can also get rid of calling each to iterate thru inputs since binding event to multiply elements interates via them. So you can change your code into something like following:
var autoFocusPhoneFields = function () {
$('input:text').keypress(function() {
if(this.value.length == $(this).attr('maxlength'))
$(this).next('input').focus();
});
}
$(autoFocusPhoneFields);
This works fine.
HTML
<input id="one" class="inp" maxlength="5" />
<input id="two" class="inp" maxlength="3" />
<input id="three" class="inp" maxlength="2" />
JS Part
$(function(){
var onpress = function(){
var val = $(this).val();
var next_input = $(this).next('input');
var mx = $(this).attr('maxlength');
try {
mx = Number(mx);
if (next_input.length >= 1 && val.length >= mx){
next_input.focus();
}
} catch(x){}
}
$('input.inp').bind('keypress', onpress);
});

jquery: event for simulating live typing

Part 1:
Is there any event I can use to get a callback when the user 'change' the input field. My definition of change is to simulate the following effect. say, I want to update a label while the user typing in the input box. I tried jquery "change" event. It works, but doesn't have the live effect. Once the input field is updated, I have to click on somewhere in the screen to update the label.
Part 2:
well, if this is not a good idea, I may prevent the form being submitted on enter key. Not sure about a good way to do it either. Quick search found this answer.
<form action="" method="post" onsubmit="return false;">
not tested yet, but hopefully the submit button may still works.
EDIT: tested, and onsubmit="return false;" prevents even the submit button.
thanks,
bsr.
This should do it:
input.bind('keydown keypress', function() {
setTimeout(function() {
label.text(input.val());
}, 0);
});
Live demo: http://jsfiddle.net/simevidas/qTBxv/
Part 1
You can just update it every keyUp, but I would suggest you at least wait 1 second after the user finishes typing.
var timer;
var changeTxt = function(){
// Change label text here.
};
$("#myInput").keyup(function(){
clearTimeout(timer);
timer = setTimeout(changeTxt, 1000);
});
Part 2
That example you posted stops a form from submitting. Is that your goal?
EDIT:
I think you are trying to control the form's submission?
$("#myForm").submit(function(){
if(/* Your condition here */){
return false;
//Only if your condition is true, stop form submission
}
});
Did you try out the keydown or keypress event?
I would prefer a combination of both, form and field validation:
Find working sample here: http://jsfiddle.net/ezmilhouse/9mNc4/1/
your html:
<form method="post" action="post.php">
<input type="text" name="" value="" />
<label>Name</label>
<div></div>
</form>
your js:
// prevent form from being posted empty
$('form').live('submit', function(evt){
if ( $('input', this).val() === "" ) {
evt.preventDefault();
alert('Field is required!');
}
});
// validate form field on the fly
var min = 3;
$('input').live('keyup change', function(){
if ($(this).val().length < min) {
$('div').html('<span class="invalid">min. 3 characters.</span>');
} else {
$('div').html('<span class="valid">ok!</span>');
}
});
there is something called oninput that you can use.
<form oninput="xx.value=aa.value">
<input type="text" name="aa" value="">
<output name="xx" for="aa"> </output>
</form>

Categories