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>
Related
I am trying to create a typing game that allows users to input the correct alphabets for the word displayed on the screen. If any wrong alphabet is used as input the game won't show a new word until all the alphabets are correctly provided as input. What I am not able to figure out is how I do match multiple characters with Array elements. Here is my code sample.
var p = document.getElementById('word');
document.addEventListener('keyup', keyboardEventsHandle , false);
var wordsList = ['america','japan','italy','jordan','turkey'];
function keyboardEventsHandle(e){
p.append(e.key);
if(e.key=='a')
{
alert('You typed A');
}
}
<html>
<head>
<title>Simple Typing Tutor</title>
</head>
<body>
<p id="word"></p>
<h3> america </h3>
<script src="javas.js"></script>
</body>
</html>
var p = document.getElementById('word');
var word = document.getElementById("toType")
document.addEventListener('keyup', keyboardEventsHandle , false);
var wordsList = ['america','japan','italy','jordan','turkey'];
var gameRunning = true
var charIndex = 0;
var wordIndex = 0;
function keyboardEventsHandle(e){
// If you use append here. Every character gets printed out
// p.append(e.key);
if(e.key==wordsList[wordIndex].charAt(charIndex) && gameRunning)
{
// If you use append here only correct characters get printed out
p.append(e.key)
alert('Correct!');
if (wordsList[wordIndex].length == charIndex + 1) {
// Defines which word should get controlled
if (wordsList.length == wordIndex + 1) {
gameRunning = false;
alert('Done');
} else {
wordIndex++;
charIndex = 0;
word.innerHTML = wordsList[wordIndex];
p.innerHTML = "";
}
} else {
// Defines which character of the word should get controlled
charIndex++;
}
}
}
<html>
<head>
<title>Simple Typing Tutor</title>
</head>
<body>
<p id="word"></p>
<h3 id="toType"> america </h3>
<script src="javas.js"></script>
</body>
</html>
You can create a list of elements to match and then do something like this:
const wordsList = ['america','japan','italy','jordan','turkey'];
const listToMatch = ['america','japan'];
let trueOrFalse = listToMatch.every(i=> wordsList.includes(i));
console.log(trueOrFalse) //true
var anotherList = ['america', 'India'];
trueOrFalse = anotherList.every(i=> wordsList.includes(i));
console.log(trueOrFalse) //false
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>
I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}
I am having a tough time with this javascript code to change the background color of a text input if the input is empty.
Here is the code:
function checkFilled() {
var inputVal = document.getElementById("subEmail").value;
if (inputVal == "") {
inputVal.style.backgroundColor = "yellow";
}
}
Example: http://jsfiddle.net/2Xgfr/
I would expect the textbox to come out yellow at the beginning.
DEMO --> http://jsfiddle.net/2Xgfr/829/
HTML
<input type="text" id="subEmail" onchange="checkFilled();">
JavaScript
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "yellow";
}
else{
inputVal.style.backgroundColor = "";
}
}
checkFilled();
Note: You were checking value and setting color to value which is not allowed, that's why it was giving you errors. try like the above.
You didn't call the function and you have other errors, should be:
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "yellow";
}
}
checkFilled();
Fiddle
You were setting inputVal to the string value of the input, but then you tried to set style.backgroundColor on it, which won't work because it's a string, not the element. I changed your variable to store the element object instead of its value.
on body tag's onLoad try setting it like
document.getElementById("subEmail").style.backgroundColor = "yellow";
and after that on change of that input field check if some value is there, or paint it yellow like
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "yellow";
}
}
Try this:
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal == "") {
inputVal.style.backgroundColor = "yellow";
}
}
Don't add styles to value of input so use like
function checkFilled() {
var inputElem = document.getElementById("subEmail");
if (inputElem.value == "") {
inputElem.style.backgroundColor = "yellow";
}
}
<! DOCTYPE html>
<html>
<head></head>
<body>
<input type="text" id="subEmail">
<script type="text/javascript">
window.onload = function(){
var subEmail = document.getElementById("subEmail");
subEmail.onchange = function(){
if(subEmail.value == "")
{
subEmail.style.backgroundColor = "red";
}
else
{
subEmail.style.backgroundColor = "yellow";
}
};
};
</script>
</body>
You could have the CSS first style the textbox, then have js change it:
<input type="text" style="background-color: yellow;" id="subEmail" />
js:
function changeColor() {
document.getElementById("subEmail").style.backgroundColor = "Insert color here"
}
// program to change color of txtbox if empty string submitted
function chgColor() {
let x = document.getElementById("txt").value;
if (x == "") {
document.getElementById("txt").style.backgroundColor = "yellow";
}
}
<input type="email" name="hi" value="hi" id="txt">
<button type="button" onclick="chgColor();">ok</button>
You can style it using javascript and css. Add the style to css and using javascript add/remove style using classlist property.
addRemoteImage = function(event) {
var textbox = document.querySelector("input[name='input-image']"),
imageUrl = textbox.value,
errorDiv = document.querySelector("div[name='input-image-error']");
if (imageUrl == "") {
errorDiv.style.display = "block";
textbox.classList.add('text-error');
setTimeout(function() {
errorDiv.style.removeProperty('display');
textbox.classList.remove('text-error');
}, 3000);
} else {
textbox.classList.remove('text-error');
}
}
.no-image-url-error {
color: red;
display: none;
}
.text-error {
border: 1px solid red !important;
}
<div class="div-image-background">
<div class="div-image-text">
<input class="input-image-url" type="text" placeholder="Add text" name="input-image">
<input type="button" onclick="addRemoteImage(event);" value="Submit">
</div>
<div class="no-image-url-error" name="input-image-error">Textbox empty</div>
</div>
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.