I have a simple first/last name form. When submitted I want to check that only letters have been used and if not, display an error div.
For example:
if ('#input-32' ) {
/* contains anything other than letters */
$("#error").show();
}
You can use Regex - Read More
const input = document.querySelector('#firstname');
input.addEventListener('input', function(e) {
const val = e.target.value;
const isLetter = /^[a-zA-Z]+$/.test(val);
console.log(isLetter);
// if( isLetter ){ ... }
})
<input type="text" id="firstname">
The following should show the error element if input contains anything other than letters:
if ($('#input-32').val().match(/[^a-zA-Z]/g)) {
/* contains anything other than letters */
$("#error").show();
}
$(document).ready(function(){
$("#error").hide();
$("#nameField").on("change", function(){
var nameSub = $('#nameField').val();
if(/^[a-zA-Z]+$/.test(nameSub)){
$("#error").hide();
}
else{
$("#error").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name" id="nameField"/>
<div id="error">error</div>
Related
The issue here is that I have designed a basic website which takes in a users input on a form, what I then intend to do is print that value out to the console.log. however, when I check the console under developer tools in Google Chrome, all I get printed out is []length: 0__proto__: Array(0)
and not the value the user has inputted.
<input type="text" name="username" value="testuser">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function error() {
var error1 = [];
var list_of_values = [];
username_error = $('input[name="username"]').val();
if (!username_error){
error1.push('Fill in the username field.');
}
console.log(error1);
if (error1.length > 0){
for(let username_error of error1){
alert(username_error);
return false;
}
}
string = $('input[name="username"]').val('');
if(string.length <= 1){
for (let list_of_values of string){
string.push();
}
console.log(string);
return true;
}
}
error();
</script>
Suggestion, you can make it actually things easier with the following code.
the function below scans all input fields under fieldset element
$("fieldset *[name]").each....
the issue above is multiple alert, what if you have a lot of inputs, it would alert in every input, which wont be nice for the users :) instead you can do this
alert(error1.toString().replace(/,/g, "\n"));
to alert the lists of errors at once.
string = $('input[name="username"]').val('');
that is actually clearing your value.. so it wont give you anything in console.log().
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<input type="text" name="name" value="" placeholder="name"/><br/><br/>
<input type="text" name="username" value="" placeholder="username"/><br/><br/>
<button onclick="error()">check</button>
</fieldset>
<script>
function error() {
var error1 = [];
var list_of_values = [];
$("fieldset *[name]").each(function(){
var inputItem = $(this);
if(inputItem.val()) {
return list_of_values.push(inputItem.val());
}
error1.push('Fill in the '+inputItem.attr('name')+' field!')
});
if(error1.length > 0) {
console.log(error1);
alert(error1.toString().replace(/,/g, "\n"));
}
if(list_of_values.length > 0) {
console.log(list_of_values);
}
}
</script>
Register the <input> to the input event. When the user types anything into the <input> the input event can trigger an event handler (a function, in the demo it's log()).
Demo
Details commented in demo
// Reference the input
var text = document.querySelector('[name=username]');
// Register the input to the input event
text.oninput = log;
/*
Whenever a user types into the input...
Reference the input as the element being typed into
if the typed element is an input...
log its value in the console.
*/
function log(event) {
var typed = event.target;
if (typed.tagName === 'INPUT') {
console.log(typed.value);
}
}
<input type="text" name="username" value="testuser">
I am working on form input field and trying to show error message when user enters any of the following text
JS01, PR03, HY79, FG36, VF42, HF23
Basically need to show error message only if user entered the above mentioned text.
<input type="text" name="prodcode" class="form-control"/>
Should we use regex to achieve this? or Any jquery/javascipt can do this?
Can anyone provide me an example?
use Jquery.inArray method to find out if the word user entered is in your defined array,
var myarray = ["JS01", "PR03","HY79","FG36", "VF42","HF23"];
var inputWord = $("input[name='prodcode']").val();
if(jQuery.inArray(inputWord , myarray) !== -1){ //if the word exits
//do what you want here
}
You can use jquery indexof method.For ex:-
a = [JS01, PR03, HY79, FG36, VF42, HF23]
var value = $('input[name="prodcode"]').val();
var indexval = a.indexOf("value" ); // this will return -1 if not found else return index
if (indexval>=0){
// code for error
}
Please Check this. The solution has been done on keydown
$(function(){
var arr = ['JS01', 'PR03', 'HY79', 'FG36', 'VF42', 'HF23'];
$('.form-control').keydown(function(){
var inputval = $('.form-control').val();
var k = $.inArray(inputval,arr);
if(k != -1){
alert('error');
}
});
});
Try with this:
var err = [ 'JS01', 'PR03', 'HY79', 'FG36', 'VF42', 'HF23' ];
$('#myInput').keyup(function (e){
console.log("ERR", err.indexOf(this.value))
if (err.indexOf(this.value) !== -1) {
$('.error').css({display: 'block'})
} else {
$('.error').css({display: 'none'})
}
})
.error{
color: red;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myInput" type="text" name="prodcode" class="form-control"/>
<div class="error">Error</div>
You can use the includes method ( MDN includes ) and check against an array which is prefilled with invalid strings.
var valuesToCheckFor = ["JS01", "PR03","HY79","FG36", "VF42","HF23"];
if( valuesToCheckFor.includes($('input[name="prodcode"]').val()) ) {
// Do what you want.
}
P.S. you will have to add this code inside the submit handler.
I'm using a at the moment in order to add a search feature to my site. I want them to enter a number that starts with 765611 and then has 11 numbers after that; if they type in a correct number, it will run the below script:
var a = document.getElementById('search');
a.addEventListener('submit',function(e) {
e.preventDefault();
var b = document.getElementById('searchbar').value;
window.location.href = 'thecopperkings.co.uk'+b;
});
If they enter a wrong number (i.e. one that does not start with 765611 and have 11 numbers proceeding it) the background of the div will flash red for two seconds (I assume the way this would be done is by adding a temporary class value which has a red background) with a transition as well, and the above code wouldn't run.
I'm pretty terrible (and new) to JS but looking at other peoples code and my basic knowledge, I assume it would have to be something along the lines of this:
var search = document.getElementByID('search');
a.addEventListener('submit',function(e) {
if document.getElementByID('searchbar').value = "765611[0-9]{11}$" {
e.preventDefault();
var b = document.getElementById('searchbar').value;
window.location.href = 'thecopperkings.co.uk'+b;
}
else {
**SET THE FORM'S CLASS TO "RED"?**
}
What is the best and most efficient way of doing this?
var a = document.getElementById('search');
a.addEventListener('submit',function(e) {
e.preventDefault();
var b = document.getElementById('searchbar').value;
window.location.href = 'thecopperkings.co.uk'+b;
});
<div>
<form class="search" id="search" method="get" action="html/player.html">
<input type="text" placeholder="What is your SteamID?" id="searchbar" name="id" maxlength="17">
<input type="submit" value="Search">
</form>
</div>
Please find the below answer.
working example can be found here jsFiddle
Add class red as .red { background-color:red !important;}
var a = document.getElementById('search');
function appendClass(elementId, classToAppend){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToAppend) == -1)
{
document.getElementById(elementId).setAttribute("class", oldClass+ " "+classToAppend);
}
}
function removeClass(elementId, classToRemove){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToRemove) !== -1)
{ document.getElementById(elementId).setAttribute("class",oldClass.replace(classToRemove,''));
}
}
a.addEventListener('submit',function(e) {
e.preventDefault();
var b = document.getElementById('searchbar').value;
//regular expression to match your criteria and test the sample value
if(/^765611[0-9]{11}$/.test(b)) {
alert('success -> '+ b );
window.location.href = 'thecopperkings.co.uk'+b;
} else {
//append the class red for searchid which is in form element
appendClass('search','red');
//remove the red class after 2sec(2000milliseconds)
window.setTimeout(function(){removeClass('search','red');},2000);
}
});
<div>
<form class="search" id="search" method="get" action="html/player.html">
<input type="text" placeholder="What is your SteamID?" id="searchbar" name="id" maxlength="17">
<input type="submit" value="Search">
</form>
</div>
var patt = new RegExp("765611[0-9]{11}$");
var searchbar = document.getElementByID('searchbar');
var searchForm = document.getElementByID('search');
if( patt.test(searchbar.value) ){
searchForm.classlist.remove('error');
// do your magic
} else{
searchForm.classlist.add('error');
// And maybe an alert or notice for the user
}
Also, check out the html5 input attribute pattern=""
I'm trying to prevent user from entering anything except numbers and letters, but my code doesn't even allow them itself. What could be the reason? Here's my code snippet:
$(document).ready(function(){
$("#txtuname").keypress(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
JSFiddle
$(document).ready(function () {
$("#txtuname").keypress(function (e) {
var validExp = /^[0-9a-z]+$/gi;
if (validExp.test(e.key)) {
$("#errmsg").html("");
return true;
}
else {
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
You can use keyup not keypress
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You can substitute input event for keypress event; adjust RegExp to /[0-9a-z]/i, use .split() with parameter "", Array.prototype.every(), RegExp.prototype.test() to check each character of input value at if condition; if each character is a digit or a letter condition is true, else false replace invalid characters of value using .replace() with RegExp /[^0-9a-z]/ig
$(document).ready(function() {
var validExp = /[0-9a-z]/i;
$("#txtuname").on("input", function(e) {
var val = this.value;
var check = val.split("").every(function(value) {
return validExp.test(value)
});
if (check) {
$("#errmsg").html("");
return check;
} else {
this.value = val.replace(/[^0-9a-z]/ig, "");
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You issue is you are not getting the value of the key that is being pressed. If you set the val variable like so, it will work as expected.
var val = String.fromCharCode(e.keyCode)
This gets the ASCII code of the key pressed, and then converting to the letter or number it represents. Then you can check against your regex.
This is because keypress events are fired before the new character is added to the value of the element (so the first keypress event is fired before the first character is added, while the value is still empty). You should use keyup instead, which is fired after the character has been added reference.
Here is the code
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
js
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(validExp.test(val))
{
$("#errmsg").html("");
return true;
}
else
{
// fix the value of input field here
$(this).val("");
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You need to use keyup so that the character is "added" already to the value if you're going to use this given technique.
Since String.prototype.match actually returns an array of the match, it won't work in the way you want it to. Not to mention that it is much more expensive than RegEx.prototype.test.
Bonus
You can use the technique of finding carret position in an input field shown in Get cursor position (in characters) within a text Input field
To actually fix the input field on keyup.
I'm trying to create a simple "search field", what it does is it searches if typed in text is equal to any data-attr of the boxes in the content and if so, hide everything but what found, something similar (this ain't working):
css:
.filter-div {
display: none;
}
html:
<label for="search">Search Input:</label>
<input type="search" name="filter" id="search" value="" />
<div class="filter-div" data-filter="one">one</div>
<div class="filter-div" data-filter="two">two</div>
<div class="filter-div" data-filter="three">three</div>
<div class="filter-div" data-filter="four">four</div>
<div class="filter-div" data-filter="five">five</div>
jquery:
// save the default value on page load
var filter = $('.input').val();
// on submit, compare
if ( $('.input').val() = $("data-filter") {
$(this).show();
}
I am also not sure if the content should be filtered with a button click or found content should pop up as click-able text in the search, or should all happen auto? Finally probably I will have to check it against more than one data-attr.
Anyone?
$('#search').on('keyup', function() {
var val = $.trim(this.value);
if (val) {
$('div[data-filter=' + val + ']').show();
} else $('div[data-filter]').hide();
});
Working sample
According to demo fiddle example in comment
var divs = $('div[data-filter]');
$('#search').on('keyup', function() {
var val = $.trim(this.value);
divs.hide();
divs.filter(function() {
return $(this).data('filter').search(val) >= 0
}).show();
});
divs.on('click', function() {
divs.not(this).hide();
var text = $.trim($(this).text());
$('#search').val(text);
});
Working sample
JavaScript:
var filter_div = $('[data-filter]');
$('#search').keyup(function(){
var val = $.trim(this.value);
filter_div.hide();
if(val.length == 0) return;
filter_div.filter(function(){
return $(this).data('filter').indexOf(val)>-1
}).show();
});
Fiddle: http://jsfiddle.net/iambriansreed/xMwS5/