How to cancel keypress in js? - javascript

I just started learning JavaScript. I have a question. When there are more than 160 characters, I do not want to type characters. How can I solve this problem?
<body> <textarea onkeypress="olay()" id="twitter" cols="30" rows="10"></textarea> <br>
<div id="sonuc"></div>
</body>
<script type="text/javascript">
i = 0;
function olay() {
i += 1;
if (i > 160) {
document.getElementById("sonuc").innerHTML = "Warning. Over 160 character";
document.getElementById("twitter").addEventListener("onkeypress", function(event)) {
event.preventDefault();
}
} else {
document.getElementById("sonuc").innerHTML = "Numver of charecter : " + i;
}
}
</script>

You don’t need JavaScript; text inputs have a maxlength attribute.
<textarea
onkeypress="olay()"
id="twitter"
cols="30"
rows="10"
maxlength="160"></textarea>

This is with html
<textarea
id="twitter"
cols="30"
rows="10"
maxlength="160"
placeholder="Enter text here...">
</textarea>

This how you would do it with JavaScript and HTML.
<body>
<textarea id="twitter" cols="30" rows="10" maxlength="160" placeholder="Enter text here..."></textarea><br>
<div id="sonuc"></div>
<script type="text/javascript">
function olay() {
var text = document.getElementById("twitter").innerHTML;
var i = text.length;
if (i >= 160) {
document.getElementById("sonuc").innerHTML = "Warning. Reached 160 character limit.";
}
else {
document.getElementById("sonuc").innerHTML = "Number of charecter : " + i;
}
}
document.addEventListener("keypress", function(){
olay();
});
document.addEventListener("keydown", function(){
olay();
});
</script>
</body>

the best you can do is write a regex and check every time on keypress.

Related

how to append input fields to a div without clearing the values with javascript

I have this code that appends a div that contains input fields and textareas to a parent div on click of a button. when I append the div and input some values in the fields and then append a new div, the values of the input fields somehow becomes empty. how can it fix this problem?
here is the code:
let counter = 1;
let new_section = document.getElementsByClassName("addnew")[0];
document.getElementById("shownew").addEventListener("click", (e) => {
e.preventDefault();
new_section.innerHTML += ` <div class="lowerlayer2">
<input type="text" placeholder="Word Type" id="wtype${counter}" />
<input type="text" placeholder="Synonym" id="syn${counter}" />
<input type="text" placeholder="Antonyms" id="anty${counter}" />
<textarea
cols="30"
rows="10"
placeholder="History & Etymology"
id="history${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Examples"
id="example${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Definition 1"
id="def1${counter}"
></textarea>
</div>`;
counter++;
});
innerHTML += overwrites the entire HTML instead of simply adding to it. Values are not included in the overwrite.
appendChild() will add to the div as expected if you don't mind it inserting an additional node. In your case you are adding a div anyways so its ok.
var newInfo = document.createElement('div'); // this makes a node, a node is require for appendChild. You could also use 'p' or 'span' etc.
newInfo.setAttribute("class", "lowerlayer2"); // you can add your classes and id etc with setAttribute
newInfo.innerHTML = "data to be added/appended";
document.getElementById("newtestdiv").appendChild(newInfo);
Minimal example using insertAdjacentHTML:
let addedCounter = 1;
document.addEventListener("click", handle);
function handle(evt) {
if (evt.target.id === "add") {
return addStuff();
}
}
function addStuff() {
document.querySelector("#container")
.insertAdjacentHTML("beforeend", `
<p>
<input type="text" placeholder="Word Type" id="wtype${addedCounter}" />
</p>`);
addedCounter += 1;
}
<div id="container">
<button id="add">Add stuff</button>
</div>
//get the input elements
let input_one = document.getElementById('INPUT_ONE_ID');
let input_two = document.getElementById('INPUT_TWO_ID');
let input_three = document.getElementById('INPUT_THREE_ID');
let counter = 1;
let new_section = document.getElementsByClassName("addnew")[0];
document.getElementById("shownew").addEventListener("click", (e) => {
e.preventDefault();
// instead of creating new elements, append the old input elements
new_section.innerHTML += ` <div class="lowerlayer2">`+input_one+input_two+input_three+`
<textarea
cols="30"
rows="10"
placeholder="History & Etymology"
id="history${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Examples"
id="example${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Definition 1"
id="def1${counter}"
></textarea>
</div>`;
counter++;
});

how to show content in multiple classes with javascript

I am using tinymce for a textarea and i want to cout the characters inside of it.
Now i use this code:
<textarea class="tinymce" rows="2" cols="20"></textarea>
<br />
<div class="character_count"></div>
<textarea class="tinymce" rows="2" cols="20"></textarea>
<br />
<div class="character_count"></div>
<textarea class="tinymce" rows="2" cols="20"></textarea>
<br />
<div class="character_count"></div>
<script type="text/javascript">
tinymce.init({
selector: '.tinymce',
width: 400,
setup: function (ed) {
ed.on('keyup', function (e) {
var count = CountCharacters();
var x = $(".character_count");
x[0].innerHTML = "Characters: " + count;
});
}
});
function CountCharacters() {
var body = tinymce.activeEditor.getBody();
var content = tinymce.trim(body.innerText || body.textContent);
return content.length;
};
</script>
This works fine, except the number of characters is displayed only in the first div (because of x[0]
is it possible to show, whatever textarea i am typing in, to display the characters in ever div <div class="character_count"></div> ?
Yes, relace this line x[0].innerHTML = "Characters: " + count; with this
x.each( function() { $(this).text("Characters: " + count); });
const p = $("p")
$("input").on("input", function(e) {
p.each(function() {
$(this).text(e.target.value)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" />
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>

How to count number of words in a textfield

I have a user enter biograpgy in a text box html for that is
<p>Biography:
<input type="text" id="biography" name="biography" />
<span id="biographyInvalid" style="color:red; visibility:hidden"> Biography is Invalid </span>
</p>
for Javascript i have a checkme function that is called and i want to do a check inside of it
function checkme(){
var biography=document.getElementById('biography').value;
}
how can i count number of words, do i first convert it to string and then separate with spaces
<div>
<div id="count">145</div>
<div id="barbox"><div id="bar"></div></div>
</div>
<textarea id="contentbox"></textarea>
and js
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#contentbox").keyup(function()
{
var box=$(this).val();
var main = box.length *100;
var value= (main / 145);
var count= 145 - box.length;
if(box.length <= 145)
{
$('#count').html(count);
$('#bar').animate(
{
"width": value+'%',
}, 1);
}
else
{
alert(' Full ');
}
return false;
});
});
</script>
$('#contentbox').keyup(function(){} - contentbox is the ID of the textbox.
Using $(this).val() getting the textbox value.
bar is the div ID of the count meter $('#bar').animate() increasing the width.
js:
$('#biography').keyup(function () {
var words = this.value.match(/\S+/g).length;
$('#count').html('Words Count:'+words);
});
HTML:
<div id="count"></div>
This gives you correct words count
This is working example
the HTML
<form name="myform" method="post" action="">
<textarea name="inpString" cols="80" rows="4" onkeyup="countNoOfWords()" >This is a sample text that has been typed to count the number of words it contains. Click the button below to find out.</textarea>
<br />
<input name="noofwords" type="text" value="" size="6" />
</form>
The JS function
<script type="text/javascript">
function countNoOfWords(){
document.myform.noofwords.value = document.myform.post_content.value.split(' ').length;
}
</script>
reference
$('input').keyup(function() {
var cs = this.value.match(/\S+/g).length;
$('#biography').text(cs);
});
Demo - http://jsfiddle.net/hNn5b/685/

text change inHTML textarea automatically when ever there is a input change in javascript

It is working perfectly, but onmouseover, its changing only once. How can onmouseover works multiple times? I mean when ever text arrays changed
<html>
<head>
<script>
function myFunction()
{
var i;
var text = ["No Change", "No Change", "Update1", "No Change", "Update2"];
text2="";
for (i=0; i<5; i++)
{
if(text[i]=="No Change")
{
continue;
}
else
{
text2 = text2+text[i]+"\n";
}
}
document.getElementById("myTextarea").value = text2;
}
</script>
</head>
<body>
<textarea id="myTextarea" onmouseover="myFunction()" cols="100" style="color:blue;" readonly> No change </textarea>
</body>
</html>
It is little bit difficult to understand where you got stuck without seeing your code, but from your description, I developed this code. Check this and I hope it will help you.
<html>
<body>
<input type="text" id="a[0]" value="No Change"><br>
<input type="text" id="a[1]" value="No Change"><br>
<input type="text" id="a[2]" value="No Change"><br>
<input type="text" id="a[3]" value="No Change"><br>
<input type="text" id="a[4]" value="No Change"><br>
<input type="text" id="a[5]" value="No Change"><br>
<input type="text" id="a[6]" value="No Change"><br>
<input type="text" id="a[7]" value="No Change"><br>
<input type="text" id="a[8]" value="No Change"><br>
<input type="text" id="a[9]" value="No Change"><br><br>
<input type="button" onclick="change_text_area()" value="Check Now" /><br><br>
<textarea id="text_area" rows="4" cols="50" ></textarea>
<!-- JAVASCRIPT CODE BEGINS -->
<script>
function change_text_area()
{
var flag=0;
var str="";
for (i = 0; i < 10; i++)
{
var inp=document.getElementById("a["+i+"]").value;
if(inp!="No Change")
{
str=str+" "+inp;
flag=1;
}
}
if(flag==1)
{
document.getElementById("text_area").value=str;
}
else
{
document.getElementById("text_area").value="No Change";
}
}
</script>
<!-- JAVASCRIPT CODE ENDS -->
</body>
Hopefully I understood your question properly. I slightly tweaked your original code to clean it up, so now every time checkText() is called it will write any values that aren't "No Change" to the textarea.
<html>
<head>
<script>
var text = ["No Change", "No Change", "Update1", "No Change", "Update2"];
var text2=""; //don't forget to declare variables
function checkText() {
var flag = 0;
for (var i=0; i<text.length; i++) { //unnecessary to declare i outside of loop if not used elsewhere
if(text[i]!="No Change") {
text2 += text[i] + " "; //A simpler way of doing "text = text + something" | "\n" is new line
flag = 1;
}
}
if (flag == 1) {
document.getElementById("myTextarea").value = text2;
} else {
document.getElementById("myTextarea").value = "No change";
}
}
</script>
<head>
<body>
<textarea id="myTextarea" cols="100" readonly> No change </textarea>
<button onClick="checkText()">Check Text</button>
</body>
</html>
In my example the code only runs on the click of a button, but if you would like it to run at an interval, every second for example, read about the setInterval() function here.
Just a side note: remember to declare variables, and only declare them at the scope you need them (i.e. if you only need them within a for-loop, declare them within the for-loop).

Textarea count characters validation

i'm writing an asp page using vb.net and i need to count the number of characters in my textarea and display the message:"X characters Remaining."
that's my asp code:
<td valign='top'>
<textarea rows="5" id="content_txt" name="TextArea1" runat="server" maxlength="50"></textarea>
</td>
Here is a JSFiddle
HTML:
<textarea rows="5" id="content_txt" name="TextArea1" runat="server" maxlength="50"></textarea>
<p id="message"></p>
JS:
var area = document.getElementById("content_txt");
var message = document.getElementById("message");
var maxLength = 50;
var checkLength = function() {
if(area.value.length < maxLength) {
message.innerHTML = (maxLength-area.value.length) + " characters remaining";
}
}
setInterval(checkLength, 300);
I have a little but functional solution my friend, try this:
HTML CODE
<textarea name="message"placeholder="Reply message..." maxlength="155" onkeyup="counter(this);"></textarea>
<div id="counter_div">0/155</div>
JAVASCRIPT CODE
<script>
function counter(msg){
document.getElementById('counter_div').innerHTML = msg.value.length+'/155';
}
</script>
This case limit 155 characters.
this will return current length of the textarea using jquery var length = $('#content_txt').val().length; and rest of the logic you have to give it a try..
try this
function fix(dis)
{
var total=50; // ho many you want to show
var val = dis.value;
var count = val.length;
document.getElementById('remaining').innerHTML= total-count;
}
<td valign='top'>
<textarea rows="5" id="content_txt" name="TextArea1" runat="server" maxlength="50" onkeyup="fix(this)"></textarea>
</td>
<p><span id="remaining">0</span> Characters remaining</p>
<td valign='top'>
<textarea rows="5" id="content_txt" name="TextArea1" runat="server" maxlength="50"></textarea>
<span id="character-count">100</span> characters remaining.
</td>
var totallength = 100;
$('textarea#input').on('keydown, keyup', function(e) {
$('span#character-count').text((totallength - input.val().length));
});

Categories