i'm trying to make script which will replace all unwanted characters (from regexp) in input on keyup event. I tried everything but nothing works for me...
My code:
$('#form_accomodation_cell').on('keyup', 'input[name="accomodation_cell[]"]', function() {
var value = $(this).val();
var regex_cell = /^[0-9 \+]+$/g;
if (!isNumeric(value, regex_cell))
{
var new_value = value.replace(regex_cell, '');
alert(new_value);
}
function isNumeric(elem, regex_cell) {
if(elem.match(regex_cell)){
return true;
}else{
return false;
}
}
});
Try this:
$('#form_accomodation_cell').on("keyup", function () {
var value = $(this).val();
var regex_cell = /[^[0-9 +]]*/gi;
var new_value = value.replace(regex_cell, '');
alert(new_value);
});
See it here in action.
I think you should try to catch the event and finaly write this way !
function validateNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /^[0-9 \+]+$/g;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Related
I don't know why there is a warning of "Move variable declaration to top of function or script."
Although I move the variable "myName" to other places, the variable below will be the new one having the same warning. I have input "window, document" in the "Options" section in JSlint.
window.onload = function() {
"use strict";
var myLogin = document.forms.submitForm;
myLogin.onsubmit = processForm;
var myName = document.getElementById("result__username");
var myPassword = document.getElementById("result__password");
var myMessage = document.getElementById("output");
myMessage.classList.add("displaynone");
function processForm() {
var in_username = myLogin.username;
var in_password = myLogin.password;
if (in_username.value === "") {
in_username.classList.add("changered");
in_username.focus();
return false;
}
in_username.classList.add("changewhite");
if (in_password.value === "") {
in_password.classList.add("changered");
in_password.focus();
return false;
}
in_password.classList.add("changewhite");
myName.innerHTML = in_username.value;
myPassword.innerHTML = in_password.value;
myMessage.classList.add("displayblock");
return false;
}
};
If you are going to use a linter, you need to follow what ever rules you have applied. You need to move the vars before you touch the variables. You need to indent right. Set up your IDE with plug ins that will format your code for you.
window.onload = function () {
"use strict";
var myLogin = document.forms.submitForm;
var myName = document.getElementById("result__username");
var myPassword = document.getElementById("result__password");
var myMessage = document.getElementById("output");
myMessage.classList.add("displaynone");
myLogin.onsubmit = processForm;
function processForm() {
var in_username = myLogin.username;
var in_password = myLogin.password;
if (in_username.value === "") {
in_username.classList.add("changered");
in_username.focus();
return false;
}
in_username.classList.add("changewhite");
if (in_password.value === "") {
in_password.classList.add("changered");
in_password.focus();
return false;
}
in_password.classList.add("changewhite");
myName.innerHTML = in_username.value;
myPassword.innerHTML = in_password.value;
myMessage.classList.add("displayblock");
return false;
}
};
This regular expression is a white list for allowable characters in a text field. However, it doesn't catch the invalid characters when autocomplete is used to fill a field.
The shim at the end is used so IE and Edge can catch numpad invalid chars.
How can I get this regex to catch invalid chars when autocomplete fills?
var validChars = /^[ 0-9a-z\s.#,-]*$/i;
var textareas = document.querySelectorAll('.txt');
for(let i = 0; i < textareas.length; i++){
textareas[i].addEventListener("paste", function(e){
var clipboardData, pastedData;
// Get pasted data via clipboard API
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
var inputOk = scrub(pastedData);
if(!inputOk){
e.preventDefault();
}
});
textareas[i].addEventListener("keypress", function(e){
var inputOk = scrub(e.key);
if(!inputOk){
e.preventDefault();
}
});
}
function scrub(contents)
{
if(contents.match(validChars))
{
return true;
}
else
{
alert("Invalid special character entered: " + contents + " ");
return false;
}
}
// KeyboardEvent shim needed for Internet Explorer and Edge. These browsers return non-standard 'key'
// property values from the numberpad.
(function() {
var event = KeyboardEvent.prototype
var desc = Object.getOwnPropertyDescriptor(event, "key")
if (!desc) return
var keys = {
Multiply: "*",
Add: "+",
Divide: "/",
}
Object.defineProperty(event, "key", {
get: function() {
var key = desc.get.call(this)
return keys.hasOwnProperty(key) ? keys[key] : key
},
})
})()
You can use add an input event listener to the textarea and only allow the input if it matches the regular expression.
<textarea></textarea>
<script>
var validChars = /^[ 0-9a-z\s.#,-]*$/i;
var prevInput = null;
document.querySelector('textarea').addEventListener("input", function(e){
if(!this.value.match(validChars)){
alert("Invalid Input!");
this.value = prevInput? prevInput: '';
}
prevInput = this.value;
});
</script>
Here is the js code which i am trying to use. I don't like the same code repeating again and I couldn't help myself to do this in a better way.
$(function(){
$('[data-behavior~=quick-reject]').on("click", function(){
var form = $(this).closest("[data-behavior~=modal-footer]").find("form");
var some_action = form.find("#some_actions").val();
var some_reasons = form.find("[data-behavior~=escalation-reason-select-box]");
if((some_reasons.val() === "") && ( some_action === "reject")){
var errorReason = "Please select a reason";
form.addClass("error").
parent().
find("div.error").
html(errorReason);
}else{
form.submit();
}
});
$(document).on("change", "#some_actions", function (){
var form = $(this).closest("[data-behavior~=modal-footer]").find("form");
var some_action = form.find("#some_actions").val();
var some_reasons = form.find("[data-behavior~=escalation-reason-select-box]");
if(some_action === "verify"){
some_reasons.hide();
}else{
some_reasons.show();
}
});
});
You could just make a little utility function, something like.
function getVars(that) {
var form = $(that).closest("[data-behavior~=modal-footer]").find("form");
return {
form: form,
some_action: form.find("#some_actions").val(),
some_reasons: form.find("[data-behavior~=escalation-reason-select-box]")
}
}
$('[data-behavior~=quick-reject]').on("click", function(){
var v = getVars(this);
if((v.some_reasons.val() === "") && ( v.some_action === "reject")){
var errorReason = "Please select a reason";
v.form.addClass("error").
parent().
find("div.error").
html(errorReason);
}else{
v.form.submit();
}
});
$(document).on("change", "#some_actions", function (){
var v = getVars(this);
if(v.some_action === "verify"){
v.some_reasons.hide();
}else{
v.some_reasons.show();
}
});
I can't turn searchBox to a .toLowerCase and my code is case sensitive because of this. I want the code to scan on both upperCase and lowerCase letters.
I wasn't able to find a solution to my problem.
<script>
$("#searchBtn").keyup(function () {
var searchBox = $("#searchBtn").val();
var returnRows = [];
$('tr').not('.headerRow').each(function () {
var addRow = true;
var $currentRow = $(this);
$currentRow.find('td').each(function () {
var $td = $(this);
var word = $td.text();
if (word.indexOf(searchBox) > -1) {
addRow = false;
return false;
// console.log("KOMT IN IF STATEMENT"); //sla deze rij op in een tijdelijke array
}
});
if (addRow) {
returnRows.push($currentRow)
}
});
if (true)
{
$('tr').show();
}
$.each(returnRows, function (i, v) {
$(v).hide();
});
});
</script>
I am not sure but you are making it a bit more complicated. Try something like this:
$("#searchBtn").keyup(function() {
var word = $("#searchBtn").val(),
timer;
if(timer){ clearTimeout(timer); }
timer = setTimeout(function(){
$('tr').not('.headerRow').filter(function(){
var txt = $(this).find('td').text();
return txt.indexOf(word) !== -1 && txt === word;
}).hide();
},900);
});
=== lets you compare strictly. So, in such case T !== t would result in true.
In my application i want display the suggestion names based on the character that user types in that input box. I get the user input using keyup event and i have a array of names from that i want to select the names that matches with the user input only from the starting letters. For Example if the user types A the suggestion show the name start with A,(For Ro-Root Valuation) How to do this?
$( document ).ready(function() {
var usernames = ["Abisi","Bentaven", "Root Valuation", "Leidos Health", "Visante", "vendor1", "yest1", "example"];
var displayname = [];
$('#input-text').keyup(function(event){
var $textValue = $(this).val();
jQuery.each( usernames,function( i, val ) {
*** find that matching name ***
if($textValue == val){
displayname.push(val);
}
});
});
You can try something like this:
JSFIDDLE: http://jsfiddle.net/bqkobo79/1/
var length= $textValue.length;
displayname=jQuery.grep(usernames, function( element, i ) {
if(element.toLowerCase().substr(0,length)===$textValue.toLowerCase())
return element;
});
You have to make sure that the text typed matches the name:
$textValue = $textValue.toLowerCase();
val = val.toLowerCase();
var is_matched = ($textValue.substr(0, ($textValue.length)) == val.substr(0, ($textValue.length)))
To make sure that you get suggestions you need to send after checking if it is true:
if (is_matched == true) {
displayname.push(val);
} else {
return false;
}
Final Code:
$( document ).ready(function() {
var usernames = ["Abisi","Bentaven", "Root Valuation", "Leidos Health", "Visante", "vendor1", "yest1", "example"];
var displayname = [];
$('#input-text').keyup(function (event) {
var $textValue = $(this).val();
jQuery.each(usernames, function (i, val) {
$textValue = $textValue.toLowerCase();
val = val.toLowerCase();
var is_matched = ($textValue.substr(0, ($textValue.length)) == val.substr(0, ($textValue.length)))
if (is_matched == true) {
displayname.push(val);
} else {
return false;
}
});
});
String.prototype.indexOf can tell you if a string contain another string and the index of the first match of that substring.
"Abisi".indexOf("A") == 0
In your case you can use it to retrieve a set of strings that start with the value of the text input
var usernames = ["Abisi","Bentaven", "Root Valuation", "Leidos Health", "Visante", "vendor1", "yest1", "example"];
var displayname = [];
$('#input-text').keyup(function(event){
var $textValue = $(this).val();
displayname = [];
if ($textValue.length > 0){
jQuery.each( usernames,function( i, val ) {
if(val.indexOf($textValue) === 0){
displayname.push(val);
}
});
}
console.log(displayname);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="input-text"/>