Javascript form validation oninput - javascript

I'm trying to improve my javascript skills with some form validation. Why is my code not working?
<input type="password" id="psw" />
<p id="demo" ></p>
<script type="text/javascript" >
psw.oninput = function(event) {
myArray = ["1", "2","3","4","5","6","7","8","9"];
for(x=0; x<myArray.length; x++){
if(this.value.includes(myArray[x]){
demo.innerHTML = "password cannot include
a number";
} else{
demo.innerHTML = "";
}
</script>

There are some issues with your code
You're trying to bind the input event incorrectly
psw.oninput = function(event)
^
Get your element psw using the function getElementById
document.getElementById('psw')
^
You're assigning a String incorrectly
demo.innerHTML = "password cannot include
a number"; ^
^
Missing enclosing parenthesis
if(this.value.includes(myArray[x])
^
You need to break the loop when this this.value.includes(myArray[x]) is true.
Snippet with those fixes
document.getElementById('psw').addEventListener('input', function(event) {
var myArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
for (var x = 0; x < myArray.length; x++) {
if (this.value.includes(myArray[x])) {
demo.innerHTML = "password cannot include a number ";
break; // you need to break your loop
} else {
demo.innerHTML = "";
}
}
});
<input type="password" id="psw" />
<p id='demo'></p>

This will work.
Only when the number nine is entered does the text show up, if you type any other number it doesn't show up. Why?
If you enter 5, it inserts password cannot include a number, since it goes through the loop, and since 6 is not present in the string, it clears the alert.
<input type="password" id="psw" />
<p id="demo"></p>
<script type="text/javascript" >
var psw = document.getElementById("psw");
var demo = document.getElementById("demo");
psw.oninput = function(event) {
var isnumberpresent = false;
myArray = ["1", "2","3","4","5","6","7","8","9"];
for(var x=0; x<myArray.length; x++)
{
if(this.value.includes(myArray[x]))
{
isnumberpresent = true;
}
}
demo.innerHTML = isnumberpresent ? "password cannot include a number":"";
};
</script>

Here is a very basic improvement that works. But if you trying to improve your Javascript skills, consider using regular expressions as someone suggested.
<input type="password" id="psw" oninput="validate(this.value)" />
<p id="demo" ></p>
<script type="text/javascript" >
function validate(password) {
var demo = document.getElementById('demo');
var myArray = ["1", "2","3","4","5","6","7","8","9"];
for(x=0; x<myArray.length; x++){
if(password.includes(myArray[x])){
demo.innerHTML = "password cannot include a number";
break;
} else{
demo.innerHTML = "";
}
}
}
</script>

This code is working. Close the if bracket. Use a proper editor for writing code like notepad++.
<!DOCTYPE html>
<html>
<body>
<p>Write something in the text field to trigger a function.</p>
<input type="text" id="psw"/>
<p id="demo"></p>
<script>
var x;
psw.oninput = function myfunc(){
var myArray = ["1", "2","3","4","5","6","7","8","9"];
var ele=document.getElementById("psw").value;
for(x=0; x<myArray.length; x++){
if(myArray.includes(ele)){
demo.innerHTML = "password cannot include a number";
}
else { demo.innerHTML = ""; }
}
}
</script>
</body>
</html>

Related

Javascript .innerHTML fuction output only flashes

I have written a JS code to find if a string is palindrome or not. But the output only stays on for less than a second then disappears.
I know this type of question has been asked before and I tried the solution which said to add "return false" but its not working for me.
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
function checkpalin() {
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
if (flag === 0)
document.getElementById('demo').innerHTML = "Given number is a palindrome";
else
document.getElementById('demo').innerHTML = "Not palindrome";
return false;
}
<form>
Please enter a string:<br>
<input type="text" name="str" id="pform" onchange="return checkpalin()"><br>
</form>
<p id="demo"></p>
It's because you have it in a form. Try this
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
function checkpalin() {
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
if (flag === 0)
document.getElementById('demo').innerHTML = "Given number is a palindrome";
else
document.getElementById('demo').innerHTML = "Not palindrome";
return false;
}
<!DOCTYPE html>
<html>
<body>
Please enter a string:<br>
<input type="text" name="str" id="pform" onchange="return checkpalin()"><br>
<p id="demo"></p>
</body>
</html>
You can also use oninput instead of onchange to make it update while you are typing in the textbox.
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
function checkpalin() {
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
if (flag === 0)
document.getElementById('demo').innerHTML = "Given number is a palindrome";
else
document.getElementById('demo').innerHTML = "Not palindrome";
return false;
}
<!DOCTYPE html>
<html>
<body>
Please enter a string:<br>
<input type="text" name="str" id="pform" oninput="return checkpalin()"><br>
<p id="demo"></p>
</body>
</html>
The default event when hitting enter in a single field in a form is to submit the form.
In your code the return is only interesting on the submit event.
Just preventDefault on the submit or remove the form tags
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
document.getElementById("myForm").onsubmit = function(e) {
e.preventDefault();
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
document.getElementById('demo').innerHTML = flag ? "Not palindrome" : "Given string is a palindrome";
}
<form id="myForm">
Please enter a string and hit enter:<br>
<input type="text" name="str" id="pform"><br>
</form>
<p id="demo"></p>

JS or jQuery to compare two texts character by character

It should compare the texts and update it. I am using onkeyup for each time text is updated.
$(document).ready(function() {
$("#color").keyup(validate);
});
function validate() {
var password1 = $("#color").val();
var pass = $('#coltext').text();
var length = $("#color").val().length;
for (int i = 0; i < length; i++) {
if (pass[i] == password1[i]) {
$("#coltext").css("color", "green"); //make only correct character green
} else {
$("#coltext").css("color", "red");
}
}
}
<input id="color" type="text" />
<p id="coltext">This</p>
So what I want to do is whenever I type the "This" written should update character by character, green for correct and red for wrong. You can say like what typing tutor does.
You have to break the password into spans in order to style them seperately, then to compare then use $("#coltext span").eq(i).text() instead of pass[i];
$(document).ready(function() {
$("#color").keyup(validate);
});
function validate() {
var password1 = $("#color").val();
// put each of your password chars in a span
var pass = "<span>"+$('#coltext').text().split("").join("</span><span>")+"</span>";
$('#coltext').html(pass);
var length = $("#color").val().length;
for (var i = 0; i < length; i++) {
if ($("#coltext span").eq(i).text() == password1[i]) {
$("#coltext span").eq(i).css("color", "green"); //make only correct character green
} else {
$("#coltext span").eq(i).css("color", "red");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="color" type="text" />
<p id="coltext">This</p>
<!DOCTYPE html>
<html>
<body>
<script>
var x = "Cancelled";
var y = "Cancelled";
if(x==y)
{
alert("equal");
}
else
{
alert("not equal");
}
</script>
</body>
</html>

How to skip converting element text

i want output text oldnames not changes if user insert text 'false'
for example:
user input text "false toni" in textbox.
and i want output still "false toni"
why my code still changes text "toni" with "rina"?
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (oldNames== 'false ' + oldNames){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
UPDATE:
Improve the question:
Trying enter text "My name is rian and my name is false toni" .
Posible to make output "rian" still change to "susi"?
use includes x.includes(value) to check whether the text area value contains a word that you want to replace . if it contains false then your oldnames not get changed.
If you are using IE then use x.indexOf(value)>0 instead of x.includes(value)
http://www.w3schools.com/jsref/jsref_includes.asp
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni', 'rian'];
var newNames = ['rina', 'susi'];
oldNames.forEach(function(value, index) {
/*if (x.includes('false '+value)){
var oldNames1=['false '+value];
x = x.replaceArr(oldNames1, oldNames1);
}*/
if (x.includes(value)) {
var oldNames1 = [value];
x = x.replaceArr(oldNames1, newNames[index]);
newNames1 = ['false ' + newNames[index]];
oldNames1 = ['false ' + value];
x = x.replaceArr(newNames1, oldNames1);
}
});
document.getElementById("check").innerHTML = x;
}
</script>
<body>
ENTER TEXT:
<br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
You false checking condition is wrong, you can do it using substr:
if (x.substr(0, 6) === 'false ') {
// The string starts with false
} else {
}
You can find more details on the substr from MDN.
UPDATE: As mentioned in the comment same can be done via startsWith and this is a better approach.
if (x.startsWith('false ')) {
// The string starts with false
} else {
}
try this. Compare array values instead of array.
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (x.indexOf('false') > -1 ){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>

Limiting character in textbox input

please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.

How to remove characters in a field javascript

I tried using the following code to format a text field value from (N50,000.00 NGN) to (50000) but the result instead of producing 50000 is producing 5000000.
Can someone please help?
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
var str = amount[0].value;
var temp = '';
for (i = 0; i < str.length; i++) {
if (!isNaN(str[i]))
temp += str[i];
}
amount[0].value = temp;
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
The simplest method to get what you want might be to just add another condition in your for loop:
if (str[i] === '.')
break;
Let's take a look at the value you are trying to format.
In N50,000.00 NGN all digits are not NaN. So your result is 5000000 (50 000 00). The solution is to stop at dot symbol, e.g.
function doWork() {
var amount = document.getElementsByName('amount');
var str = amount[0].value;
var temp = '';
for (i = 0; i < str.length; i++) {
if (str[i] === '.') break; // there it is
if (!isNaN(str[i]))
temp += str[i];
}
amount[0].value = temp;
}
Here's one way to do it with a regex. Note, that if the user has multiple decimal points in the input field it may act oddly.
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
amount[0].value = amount[0].value.replace(/[^0-9.]/g, "");
amount[0].value = amount[0].value.replace(/[.][0-9]*/g, "");
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
The first line removes all characters except numbers and decimal points.
The second, removes all decimal points and any numbers to the right of them.
Using parseInt and toFixed may be better, though:
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
amount[0].value = parseInt(amount[0].value.replace(/[^0-9.]/g, "")).toFixed(0);
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
You're skipping over the decimal. Use:
if (!isNaN(str[i]) || str[i]=='.')

Categories