I'm trying to create a website for learning/exercise but I'm stuck at user registration validation. There's no error message and nothing happens.
Here is a JsFiddle Link.
Also I tried:
if(user_name.length < 3 && user_name!=="")
and
if(user_name.length < 3)
Code snippet:
var user_name = $('#username').val();
$('#username').on('keyup',function(){
if(user_name.length < 3 && user_name!=""){
$('#username-info').html('Username must be at least 3 characters.');
}
else if(user_name.length > 3){
$('#username_info').html('No problem');
}
});
#username-info {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info"></p>
The keyup functions need to trigger on the input field.
The keyup functions updates the username (else it will be the same).
$('#username').on('keyup',function(){
var user_name = $('#username').val();
if(user_name.length < 3 && user_name!=""){
$('#username-info').html('Username must be at least 3 characters.');
}
else if(user_name.length >= 3){
$('#username-info').html('No problem');
}
});
I think you have just put wrong ids AND your variable user_name is only initialized one time on start, so its value is always empty.
$('#username').on('keyup', function() {
var user_name = $(this).val();
if (user_name.length < 3 && user_name != "") {
$('#username-info').html('Username must be at least 3 characters.');
} else if (user_name.length > 3) {
$('#username-info').html('No problem');
}
});
#username-info {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info">
</p>
I use your code as reference and made some changes in it for better output.
You can try this, here i am changing color code as well for the error message so you will get better result.
$('#username').on('keyup',function(){
var user_name = $('#username').val();
if(user_name.length < 3 && user_name != ""){
$('#username-info').html('Username must be at least 3 characters.');
$('#username-info').addClass('username-info');
$('#username-info').removeClass('username-info-2');
}
else if(user_name.length >= 3){
$('#username-info').html('No problem');
$('#username-info').addClass('username-info-2');
$('#username-info').removeClass('username-info');
}
});
.username-info {
color: red;
}
.username-info-2 {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info"></p>
Currently, user_name is declared once at the start of your script, so it will never be updated.
Then, you attached a keyup event handler on <p#username-info>, not <input#username>, so when you input something into it, nothing will be triggered.
So, you need to update user_name at each input into <input#username>.
// Here, you need to attach the event handler of #username, not #username-info.
$('#username').on('keyup', function() {
// And here, you get the value of your input.
let user_name = $('#username').val();
// let user_name = $(this).val(); works too.
// Writing "(user_name)" in a condition is the same as "(user_name !== '')".
if (user_name && user_name.length < 3) {
$('#username-info').html('Username must be at least 3 characters.');
} else if (user_name.length >= 3) {
// You wrote "#username_info" instead of "#username-info" here.
$('#username-info').html('No problem');
}
});
#username-info {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info">
</p>
you have a lot of typos in your script and you looked for the paragraph on key up not your input field.
var user_name = "";
$('#username').on('keyup',function(){
user_name = $('#username').val();
if(user_name.length <= 3 && user_name!=""){
$('#username-info').html('Username must be at least 3 characters.');
}
else if(user_name.length > 3){
$('#username-info').html('No problem');
}
});
Related
I have some code that checks if 2 text fields match. This is using the keyup which works fine but I would like it to hide or show a div depending on result. All I have is a code that changes divCheckPasswordMatch?
So I would like it to
$('#match').hide();
$('#nomatch').show();
The js code is :
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
$("#divCheckPasswordMatch").html(password == $(this).val() ? "Passwords match." : "Passwords do not match!");
});
});
My guess is you want to have two <div> displaying different messages using show() and hide(), but I'm not sure, so I did both.
$('#match').hide();
$('#nomatch').hide();
$("#password2").keyup(function() {
var password = $("#password1").val();
if ($(this).val() === password) {
$('#divCheckPasswordMatch').html('Passwords match');
$('#match').show();
$('#nomatch').hide();
} else {
$('#divCheckPasswordMatch').html('Passwords do not match');
$('#match').hide();
$('#nomatch').show();
}
});
<form action="/action_page.php">
First input: <input id="password1" type="text" name="fname"><br>
Second input: <input id="password2" type="text" name="lname"><br>
</form>
<div id="divCheckPasswordMatch"></div>
<div id="match">Match</div>
<div id="nomatch">No Match</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Well following what you want you can do this.
HTML
<input id="password1">
<input id="password2">
<spam id="divCheckPasswordMatch"></spam>
JS
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
var password2 = $("#password2").val();
if(password!== null && password2!== null){
if(password == password2) {
$('#divCheckPasswordMatch').show();
$("#divCheckPasswordMatch").html("Passwords match.")
}
else {
$('#divCheckPasswordMatch').hide();
$("#divCheckPasswordMatch").html("Passwords do not match!")
}
}
});
});
But remember that you also need to anticipate if the password1 is changed too.
Here is working example. For learning purposes I highly suggest using pure javascript instead of jQuery. It is easy to rewrite it to jQuery. I can do it for you if you want.
You are missing blur event, I've added it. Code is not repeatable, it can be still improved. We are using one function for validation.
var field1 = document.getElementById('password1');
var field2 = document.getElementById('password2');
var result = document.getElementById('divCheckPasswordMatch');
function validateInputs() {
// If any of fields is empty then quit
if (field1.value === '' || field2.value === '') {
return;
}
if (field1.value === field2.value) {
result.innerHTML = '';
// optional hide it, clearing text gives almost the same effect, up to you
// result.style.display = 'none';
} else {
result.innerHTML = 'Passwords don\'t match';
// optional show it
//result.style.display = 'block';
}
}
document.getElementById('password1').addEventListener('keyup', validateInputs);
document.getElementById('password2').addEventListener('keyup', validateInputs);
document.getElementById('password1').addEventListener('blur', validateInputs);
document.getElementById('password2').addEventListener('blur', validateInputs);
<input type="text" id="password1">
<input type="text" id="password2">
<div id="divCheckPasswordMatch"></div>
So basically I have a button .button, which adds a number to my input #number everytime it's pressed.
Now, when I already have 7 digits in my input #number, I want the function to like 'stop working'.
Here is my code (works fine):
function nrtwo(hello){
var das = $(hello).html();
var tempNum = $("#number").val();
$("#number").val(tempNum + '' + das);
tempNum = null;
};
$(".button").click(function(){
nrtwo(this);
});
I was thinking of something like this?
if ($("#number").attr('maxlength') == '7') {
return false;
}
Thanks for the help.
Try this .length it is a Number and unblind click event when you reach 7 digits :
Working jsFiddle
$(".button").click(function(){
if ($("#number").val().length == 7) {
$(this).unbind('click');
return false;
}else{
nrtwo(this);
}
});
You need to handle this scenario in the click event itself. Please see the following example:
$(".button").click(function(){
if ($("#number").val().length <= 7) {
nrtwo(this);
}
});
This will only call the nrtwo method only when the input's length is less than or equals to 7.
If you are handling numbers only, you can also check the numeric value before adding to it.
$('#add').click(function() {
var value = parseInt($('#output').val());
if(value <= 999999) {
$('#output').val(value + 1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<input type="text" id="output" value="999995" />
$('#number').keypress(function(event){
var n = $(this).val();
if(n.length == 7){
event.preventDefault(); //stop character from entering input
}
if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
event.preventDefault(); //stop character from entering input
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input id="number"/>
One method is to use .length property.
Please try this:
if ($("#number").val().length == '7') {
return false;
}
$('#add').click(function() {
if ($("input").val().length != '7') {
$('input').val(parseInt($('input').val())+1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="999998"/>
<button type="button" id="add">Add</button>
Below is a server side and client side validation form. Here I am using div id=er> for showing error messages on failing to comply with requirements. Now the div er will be always there causing me styling problems. I want error div to appear only when there is error and not otherwise.
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var firstname = document.getElementById('fn').value;
var lastname = document.getElementById('ln').value;
var password = document.getElementById('pswd').value;
if (firstname.length < 2 || firstname.length > 11) {
$('#er').html('First name must be between 1 to 11 characters long');
return false;
}
else if (lastname.length < 2 || lastname.length > 11) {
$('#er').html('Last name must be between 1 to 11 characters long');
return false;
}
else if (password == "") {
$('#er').html('Fill your password');
return false;
}
});
});
</script>
<?php
error_reporting('E_ALL ^ E_NOTICE');
if(isset($_POST['reg'])){
$fn = ucfirst($_POST['fname']);
$ln = ucfirst($_POST['lname']);
$pswd = $_POST['password'];
if( strlen($fn) < 2 || strlen($fn) > 11 ) {
$er = 'First name should be 2 to 11 characters long';
}
elseif( strlen($ln) < 2 || strlen($ln) > 11 ) {
$er = 'Last name should be 2 to 11 characters long';
}
elseif( $pswd == "" ) {
$er = 'Enter your password';
}
else{
$pswd = password_hash($pswd, PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO users (first_name,last_name,password) VALUES (:first_name,:last_name,:password)");
$stmt->execute( array(':first_name'=>$fn,':last_name'=>$ln,':password'=>$pswd));
}
<form action="register.php" method="post" class="register">
<input type="text" name="fname" id="fn" placeholder="First Name"/>
<input type="text" name="lname" id="ln" placeholder="Last Name"/>
<input type="password" name="password" id="pswd" placeholder="Password"/>
<input type="submit" id="submit" name="reg" value="Create">
<div id='er'><?php echo $er; ?></div>
</form>
Tried something like this
<?php
if ($er!=""){
echo "<div class='er'>".er."</div>";
}
?>
But this did not work may be because javascript too shows error through same div so how to hide error div when their is no error.
If no error , hide that div. In 'er' div, write style='display:none'
<div id='er' style='display:none'><?php echo $er; ?></div>
Here, if error. Show That div. Otheriwse hide that div.
$(document).ready(function() {
$('#submit').click(function() {
var firstname = document.getElementById('fn').value;
var lastname = document.getElementById('ln').value;
var password = document.getElementById('pswd').value;
if (firstname.length < 2 || firstname.length > 11) {
$('#er').show();
$('#er').html('First name must be between 1 to 11 characters long');
return false;
}
else if (lastname.length < 2 || lastname.length > 11) {
$('#er').show();
$('#er').html('Last name must be between 1 to 11 characters long');
return false;
}
else if (password == "") {
$('#er').show();
$('#er').html('Fill your password');
return false;
}
else {
$('#er').hide();
}
});
});
Write a css selector for the element when empty, and set display : none
div {
background-color: lightblue;
margin: 10px;
display: inline-block;
height: 20px;
}
.demo:empty {
display: none;
}
<div class="demo">One</div>
<div class="demo"></div>
<div class="demo">Other</div>
You don't need to take care of anything else, when in JS you set the content to nothing, it will disappear
Support is quite good, only missing in IE8 http://caniuse.com/#feat=css-sel3
You can set the error div's display to none.
This will take the element out of the DOM as if it was never there.
CSS:
#er {
display:none;
}
Then when an error occurs, you can change the display property in JS:
$('#er').css("display","block");
and set the error message:
$('#er').html('First name must be between 1 to 11 characters long');
I have a textbox and a submit button
<input type="text" name="username" id="username"/><br/>
<input type="submit" onclick="return validate()"/>
Here is the function code:
if (document.getElementById("usernameee").value == null || document.getElementById("usernameee").value == "" ) {
document.getElementById("usernameee").style.borderColor = 'red';
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
if (document.getElementById("usernameee").value.length!=0 || document.getElementById("usernameee").value.length < 8 ) {
document.getElementById("usernameee").style.borderColor = 'red';
document.getElementById("message").innerHTML="Enter Atleast 8 Characters"
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
}
now what is want is that if the user leaves the filed empty it should only highlight the textbox with backgound color red and if the username is less than 8 characters it should show the message and highlight the backgound of textbox but now even if the textbox is empty it is displaying the message which i dont want...if the field is empty it should ol
I think your second conditional is wrong. Also you can write the code much cleaner like this:
var username = document.getElementById("usernameee");
if(!username.value) {
//There is no username
username.style.borderColor = 'red';
} else if(username.value.length < 8) {
//There is a username and the value is shorter than 8 characters
username.style.borderColor = 'red';
document.getElementById("message").innerHTML = "Enter Atleast 8 Characters";
} else {
//There is a username and it is longer than or equal to 8 characters.
username.style.borderColor = '';
document.getElementById("message").innerHTML = "";
}
What is the most efficient way to set the range for an input-field to -100.0 to 100.0? I would like to check every character. Other characters than -,0,1,2,3,4,5,6,7,8,9 and . are not allowed. Values without floating point, e.g. 78, are also possible.
UPDATE
I need a solution for IE, so html5 solution with type="range" or type="number" are useless for me.
The only code I have is the input field:
<input type="text" id="zahlenwert" value="" />
The question is: Do I have to check every character with onKeydown() or is there a smarter way?
Here is what you are looking for:
http://jeroenvanwarmerdam.nl/content/resources/javascript/jquery/spincontrol/jquery-spincontrol-1.0.zip
And here is example:
http://jeroenvanwarmerdam.nl/content/resources/javascript/jquery/spincontrol/jquery-spincontrol.html?x=31&y=10
Integration:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery-numeric.js"></script>
<script type="text/javascript" src="jquery-number-selector.js"></script>
<script type="text/javascript" src="jquery-spincontrol-support.js"></script>
<script type="text/javascript" src="jquery-spincontrol.js"></script>
<!-- SpinControl definition -->
<script type="text/javascript">
(function($) {
$(function() {
$(":number").addClass("number").spinControl({ folder: "images/" });
});
})(jQuery);
</script>
Here is your body html code:
<input type="number" max="10" min="-10" step="0.5" />
I'm partly guessing at your requirements but if you're just trying to restrict the input value to a number within a specific range you could use HTML5's range input type:
<input type="range" name="myrange" min="-100" max="100">
Or use JavaScript to validate the value like in this demo fiddle:
document.getElementById('test').onchange = isNumber;
function isNumber(){
var val = this.value;
var aNumber = !isNaN(val);
var aNumberNotOverOneHundred = (Math.abs(parseFloat(val, 10)) <= 100);
alert((aNumber && aNumberNotOverOneHundred)?"Yarp":"Narp");
}
Or use input pattern attribute to validate against a regex pattern.
This is the solution I wanted:
$(document).ready(function() {
$("input#zahlenwert").keyup(function(){
var zahlenwert= $("input#zahlenwert").val();
var status = 0;
for(i=zahlenwert.length;i>0;i--){
if(status==0){
if(zahlenwert.length == 0){
}
else if(zahlenwert.length == 1 && zahlenwert.match(/^(-|[0-9]) /)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 2 && zahlenwert.match(/^(-[0-9]|[0-9],|[1-9][0-9])/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 3 && zahlenwert.match(/^(-[1-9][0-9]|[0-9],[0-9]|100|[1-9][0-9],|-[0-9],)/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 4 && zahlenwert.match(/^(-100|100,|[1-9][0-9],[0-9]|-[0-9],[0-9]|-[1-9][0-9],)/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 5 && zahlenwert.match(/^(100,0|-100,|-[1-9][0-9],[0-9])/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 6 && zahlenwert.match(/^-100,0/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else{
zahlenwert = zahlenwert.substring(0,zahlenwert.length-1);
$("input#zahlenwert").val(zahlenwert);
console.log("Error!!!");
}
}
}
});
});