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>
Related
I have some simple HTML code
<textarea id="text" placeholder="Type text...."></textarea>
<a id="button" class="button"></a>
<textarea id="result" disabled></textarea>
and I have a javascript code
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
I just want to integrate js with HTML to count each character frequency inside of textarea with id="text" and show result inside of textarea with id="result". I have tried to use
document.getElementById("text").value;
but something goes wrong and still not working. There is any way to do this in easy way?
If you want to do it while typing you can use the keyup event on the textarea, in the following way
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
window.addEventListener('load', function() {
const textbox = document.getElementById('text');
const result = document.getElementById('result');
textbox.addEventListener('keyup', function() {
const frequency = getFrequency( textbox.value );
result.value = Object.keys( frequency ).map( key => `${key}: ${frequency[key]}` ).join('\n');
});
});
<textarea id="text" placeholder="Type text...."></textarea>
<a id="button" class="button"></a>
<textarea id="result" disabled></textarea>
if you want to do it upon button click, you could change the previous code like so:
document.getElementById('button').addEventListener('click', function() {
const frequency = getFrequency( textbox.value );
result.value = Object.keys( frequency ).map( key => `${key}: ${frequency[key]}` ).join('\n');
});
This should do it.
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
document.getElementById('myButton').onclick = function(){
var str = document.getElementById('text').value;
var result = getFrequency(str);
document.getElementById('result').value = JSON.stringify(result);
}
<textarea id="text" placeholder="Type text...." ></textarea>
<button id="myButton" class="button">Count</button>
<textarea id="result" disabled></textarea>
Using spread syntax, Map, Array#reduce, and String#split
const textArea = document.getElementById("text");
const button = document.getElementById("button");
const result = document.getElementById("result");
button.addEventListener("click", function(){
const value = textArea.value.trim();
const res = getFrequency(value);
console.log(JSON.stringify([...res]));
result.innerText = `(${[...res].join("), (")})`;
})
function getFrequency(str){
return str.split("").reduce((a,c)=>a.set(c, (a.get(c) || 0) + 1), new Map());
}
div {
display: flex;
background-color: lightgrey;
flex-direction: column;
}
div > div {
flex-direction: row;
}
<div>
<textarea id="text" placeholder="Type text....">
Some text to check the count of characters
</textarea>
<div>
<button id="button" class="button">Click me</button>
<p id="result"></p>
</div>
</div>
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>
I have an array in javascript like that :
var books = ['spring','last night','sweet heart','the sky','tomorrow'] ;
I have textarea
<textarea id="text" name="textpreview" class="text"></textarea>
So what I want is when I enter letter s then I will get two suggestions books just the first word not the second word I mean not sky Just spring and sweet heart .
I will get two spans
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
<span>sweet heart</span>
If I type again after s the p letter like sp in textarea then I will get just spring
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
and so on .
If I type n I will get nothing.
If I type t I will get tomorrow and the sky
Hope it can be done . Thanks for your support .
This help you :
<html>
<head>
<title></title>
</head>
<body>
<textarea id="text" name="textpreview" class="text"></textarea>
<p id="x"></p>
<script>
var x = document.getElementById("x");
var books = ['spring','last night','sweet heart','last night','the sky','tomorrow','tomorrow'];
var txt = document.getElementById("text");
txt.onkeyup = function(event) {
var str = "";
var arr = [];
var index = (txt.value).indexOf("#");
if(index !== -1 && (txt.value).substr(index + 1).length > 0) {
var value = (txt.value).substr(index + 1);
value = value.replace(/[\.\+\*\\\?]/g,'\\$&');
var patt = new RegExp("^" + value);
for(var i=0; i<books.length; i++) {
if(patt.test(books[i]) && arr.indexOf(books[i]) === -1) {
arr.push(books[i]);
}
}
}
if (arr.length < 1 )
x.innerHTML = "";
else {
for(var i=0; i<arr.length; i++)
str+=arr[i]+"<br>";
x.innerHTML = str;
}
}
</script>
</body>
</html>
This problem consists of two parts: Reading and writing your input/output from/to the DOM, and filtering your array books.
The reading and writing part should be easy, there are plenty of guides on how to achieve this.
To filter the books array, JavaScript offers a number of helpful functions:
var books = ['spring','last night','sweet heart','the sky','tomorrow'];
var input = 'S';
var result = books.filter(function(book) {
return book.toLowerCase().indexOf(input.toLowerCase()) === 0;
}).slice(0, 2);
console.log(result); // ['spring', 'sweet heart']
#TimoSta is correct that this is a two-part problem.
I expanded on his code a bit using angular to display the results in the DOM.
http://jsfiddle.net/kcmg9cae/
HTML:
<div ng-controller="MyCtrl">
<textarea id="text" name="textpreview" class="text" ng-model="startsWith"></textarea>
<span ng-repeat="book in sortedBooks()">{{ book }}</span>
</div>
Javascript:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.books = ['spring','last night','sweet heart','the sky','tomorrow'];
$scope.sortedBooks = function () {
var sortedBooks = [];
for (var i = 0; i < $scope.books.length; i++){
if ($scope.books[i].toLowerCase().indexOf($scope.startsWith.toLowerCase()) === 0)
sortedBooks.push($scope.books[i]);
}
return sortedBooks;
}
}
I have the base of words like:
var words = [
["english_word1","german_word1"],
["english_word2","german_word2"],
["english_word3","german_word3"]
];
and I need a simple javascript for translating the words in both directions i.e. english -> german and german -> english. Something like:
<textarea id="source" onkeyup="translate();"></textarea>
<div id="result"></div>
<script type="text/javascript">
function translate() {
var source = document.getElementById('source').value;
... ???
document.getElementById('result').innerHTML = result;
}
</script>
Without changing the base
You can try this code
<html>
<head>
<script>
var words = [
["english_word1","german_word1"],
["english_word2","german_word2"],
["english_word3","german_word3"]
];
function getlang(){
var select = document.getElementById("language");
return select.options[select.selectedIndex].value*1;
}
function search(keyword){
for(var x = 0; x < words.length; x++){
var lang = getlang()
if(words[x][lang] == keyword) return words[x][(lang+1) % 2]
}
return false
}
function update(e){
var source = document.getElementById('source').value;
result = search(source);
if(result !== false)
document.getElementById('result').innerHTML = result;
}
document.addEventListener("input",function(e){
if(e.target.id == "source"){
update()
}
});
document.addEventListener("change",function(e){
if(e.target.id == "language"){
update()
}
});
</script>
</head>
<body>
<textarea id = "source"></textarea>
<select id = "language">
<option value = 0>English -> German</option>
<option value = 1>German -> English</option>
</select>
<div id = "result"></div>
</body>
</html>
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.