Remove last character on input field jQuery - javascript

I know this kind of question has been asked several times but none of the answers worked for me. I want to make my own spell-checker which compares words letter by letter and checks the correctness.
As user types letters one by one, the content is checked. If it is correct, goes on, if it is wrong: I want the last letter to be deleted.
Here is my code:
var word = [];
word = "beautiful".split('');
var i =0;
$(document).ready(
function()
{ $('#txtword').keyup(
function() {
var value = document.getElementById('txtword').value;
if (value[i] == word[i]){
alert("Right letter!");
i++; }
else
{ alert("Wrong letter");
value.slice(0,-1);
/*value.substr(0,value.length-1);*/
}
});
})
I tried both options value.slice(0,-1); and value.substr(0,value.length-1); but they are not working. Can someone help me find the mistake!

You need to assign new value back to value property of the element
this.value = value.substr(0,value.length-1);
Note: You can use this.value instead of document.getElementById('txtword').value;

Related

jquery regex continuous space [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 5 years ago.
I want to check input and want to show error if input is empty or entered continuous space. just one space allowed between words. e.g:
Test ok test
var pattern = /\s\s+/g;
$('a').click(function() {
if ($('input').val().length <= 2 || pattern.test($('input').val())) {
alert('error');
} else {
alert('ok go');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>check</a>
<input type="text"/>
It seems working, but it have issue, do this to find this issue:
Enter 5 space continuously, then click on check, it alert error but click again on check, it alert ok.
should error when user entered more than 2 space continuously.
you can use trim method which will work better than your code in the if statement .
The trim() method removes white space from both ends of a string which in this case the value of the input , after that you can check if its equal to the empty string and will work fine
see the example below
var pattern = /\s\s+/g;
$('a').click(function() {
if ($('input').val().trim()==='') {
alert('error');
} else {
alert('ok go');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>check</a>
<input type ="text" />
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test:
If the regex has the global flag set, test() will advance the lastIndex of the
regex. A subsequent use of test() will start the search at the substring of str
specified by lastIndex (exec() will also advance the lastIndex property).
The problem is after your regex is matched against the string, the lastIndex property will cause the next match to start after the previous match. You can verify this by outputting the value of pattern.lastIndex after each click.
You can fix this by manually setting lastIndex back to zero after each match, like
$('a').click(function() {
pattern.lastIndex = 0;
if ($('input').val().length <= 2 || pattern.test($('input').val())) {
alert('error');
} else {
alert('ok go');
}
});
You can also fix by getting rid of pattern all together and writing
$('a').click(function() {
if ($('input').val().length <= 2 || /\s\s+/g.test($('input').val())) {
alert('error');
} else {
alert('ok go');
}
});
Note that you can change your pattern to /\s{2,}/g matching whitespace two or more times.

Having problems with regex in Javascript

I am currently making a senior memory book my English class, and because I'm a nerd I am going to put a bit of code in it. Well, I'm having a bit of trouble with regex in my code.
My entire code:
//For future reference, "alert(*parametes*)" will make an alert box with the parameters inside it.
//Asks you to enter a phrase and stores your answer.
var phrase = prompt("Enter a phrase to be checked for palindrome.").toLowerCase()
//Creates the entered phrase backwards.
var phraseBackwards = ""
for (var x in phrase) {
phraseBackwards += phrase[(phrase.length - 1) - x]
}
//Checks to see if the new phrase is a palindrome.
if (phraseBackwards == phrase) {
alert("The phrase you entered was a palindrome.")
}
//This happens if the preavious condition was false.
else {
//Checks if the new phrase is a palindrome without spaces.
if (phraseBackwards.replace("/\s+/g", '') == phrase) {
alert("The phrase you entered would have been a palindrome, had it not had spaces")
} else {
//Checks to see if the phrase you entered, even without spaces, is not a palindrome.
if (phraseBackwards.replace(/\s+/g, '') != phrase) {
alert("The phrase you ented was not a palindrome.")
}
}
}
The particular portion that is not functioning correctly:
//Checks if the new phrase is a palindrome without spaces.
if (phraseBackwards.replace(/\s+/g, '') == phrase) {
alert("The phrase you entered would have been a palindrome, had it not had spaces")
}
I realize that some of my code may not be optimal but I'm trying to hurry and finish because I procrastinated until last minute.
So there are a few points to note in my edit.
First of all, you need to remove all non word characters from the initial phrase using this: replace(/\W/g, "")
Then reverse the string: phrase.split("").reverse().join("")
Then check if phraseBackwards == phrase.
Note: The code you used to used to reverse the string was valid. But given your use for this, I thought you might want to make it shorter.
//For future reference, "alert(*parameters*)" will make an alert box with the parameters inside it.
//Asks you to enter a phrase and stores your answer.
var phrase = prompt("Enter a phrase to be checked for palindrome.").toLowerCase().replace(/\W/g, "");
//Creates the entered phrase backwards.
var phraseBackwards = phrase.split("").reverse().join("");
//Checks to see if the new phrase is a palindrome.
if (phraseBackwards == phrase) {
alert("The phrase you entered was a palindrome.");
}
//This happens if the previous condition was false.
else {
alert("The phrase you ented was not a palindrome.");
}
phraseBackwards without spaces can't be == to the original phrase, because the original has spaces. Remove spaces from the original phrase as well. – Jeremy Thille

Checking textfield values if they are matching

Im making a little form where you can pick your value.
If the value is not filled in correctly(I have given some example answers)
I want an alertbox to pop-up which indicates the incorrectly filled in textfields.
Cant seem to make it work...
This is what I tried
if(document.getElementById("BS").value.match ("thin","thick","medium")
{
alert("Fill in the correct values");
}
Here is the fiddle.
http://jsfiddle.net/vuc8Z/
Here is my suggestion:
var val = document.getElementById("BD").value;
if (!(val == "thin" || val =="thick" || val =="medium")) {
alert("Vul een geldige waarde in bij de aangegeven velden");
}
Demo here
Notice that you were using getElementById("BS"), but you wanted BD i think. I changed your match function to a triple || (or) if statement.
I moved your if statement to inside the "go" button click handler so it is fired when the button is clicked.
The match() function expects a regex, you can read more here (MDN: .match()).
EDIT:
To check if the color text input is in the right format you can use this:
var filter = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
if (!color.match(filter)) {
alert('Color code Error!');
}
Updated demo here
If you want to use match method then you can use like :
var str = document.getElementById("BD").value;
if(str.match('thin') || str.match('thick') || str.match('medium'))
{
alert("Fill in the correct values");
}
As per my knowledge match takes regular expression as parameter and don't take multiple values.

indexOf() function to return a -1 value

I have a script that I'm trying to get working. Basically, what I'm trying to do is prevent someone from entering in special characters in to a field.
the function I have is as follows:
var iChars = "!##$%^&*()+=[];,./{}|<>?;";
if (field1.value.indexOf(iChars) !=-1)
{
alert ("problem")
}
The issue I'm having is that the field is searching for the exact match to the iChars var instead of matching any single value. For example if I create a var test ="one" and enter "one" into the field, it returns with the error, but if I enter "o" into the field, it does not return anything and just passes through to the next portion of the script - but if i entered "none" or "oneeee" it would push the error through.
Any help on fixing this? I tried looking into arrays for indexOf but didn't really understand it, so if you are going to suggest it can you please explain in as much detail as possible.
Thanks
You could use...
var value = field1.value;
for (var i = 0, length = value.length; i < length; i++) {
if (iChars.indexOf(value.charAt(i)) != -1) {
alert('Problem!');
break;
}
}
The problem is you are looking for the index of the entire iChars string in the user input. What you actually want to do though is see if any char in iChars is in the input string. To do this use a for loop
var iChars = "!##$%^&*()+=[];,./{}|<>?;";
var i;
for (i = 0; i < iChars.length; i++) {
if (field1.value.indexOf(iChars[i]) !== -1) {
alert("problem");
break;
}
}
You can also just check against a regular expression:
var iChars = /[!##$%^&*()+=[\];,./{}|<>?;]/;
if (iChars.test(field1.value)) {
alert("problem");
}
This route should be a little more efficient than iterating over each character in the string yourself, and to the regex-trained eye (or at least in my obviously-biased opinion) is simpler to read.

How can I limit a textbox to have less than 3 commas in it?

For example we have a textbox which is for tags for a blog. What I want is I want to limit number of tags to be limited.
For instance, "web hosting,php,windows8".
When the user tries to type another one to textbox which he will start with comma, the textbox won't let him write it.
In your keypress handler, capture the event object and do;
if (event.which == 44 && $(this).val().split(",").length > 2) {
event.preventDefault();
}
See it in action here; http://jsfiddle.net/5L7mU/
We can split this problem into 3 smaller problems.
First, we need a way to stop the user from writing stuff into the textbox. When you hook a callback on keypress, the event passed has a method called preventDefault which should do the job. So to block all input:
$("input").keypress(function(event) {
event.preventDefault();
});
Now, to check how many comas there already are in the textbox, we can use regex. The match function will return null instead of an empty array if there are no matches so we gotta check for that.
$("input").keypress(function(event) {
var matches = $(this).val().match(/,/g);
var count = 0;
if (matches)
count = matches.length;
console.log(count);
});
Finally, we need to be able to check if the user typed in a coma. The event objectwill have a property called which that contains the key code of the character entered. With a little bit of exploring, you can find out that the key code for coma is 44.
$("input").keypress(function(event) {
if (event.which == 44)
event.preventDefault();
});
So if we put it all together:
$("input").keypress(function(event) {
var matches = $(this).val().match(/,/g);
var count = 0;
if (matches)
count = matches.length;
if (count >= 2 && event.which == 44)
event.preventDefault();
});
http://jsfiddle.net/4wn5W/
$(document).ready(function(){
$('#textbox').keypress(function(e){
var text = $(this).val();
if(text.split(',').length>3){
return false;
}else if(e.which==44&&text.split(',').length>2){
return false
}
});
});
Fiddle:
http://jsfiddle.net/L4X4C/

Categories

Resources