I am very new to html and javascript. I have a textbox and am trying to count the number of words, then displaying the count in real time. I do not understand what I am doing wrong in this, or how to correct it. textContent does not make much sense to me.
<html>
<head>
<style>
input[type='text'] {width:50px;}
textarea {width:500px;height:300px;}
</style>
</head>
<body>
<div>
<h2>Test</h2>
<p>The number of words is <span id="wordCount"></span></p>
<textarea id="toCount"></textarea>
</div>
<script>
document.getElementById('toCount').addEventListener('input', function () {
var text = this.textContent,
count = text.trim().replace(/\s+/g, ' ').split(' ').length;
document.querySelector('.wordCount').textContent = count;
});
</script>
</body>
</html>
The error that I get right now says
Uncaught TypeError: Cannot set property 'textContent' of null
Your selector should be #wordCount, and the textarea content can be accessed using value:
<html>
<head>
<style>
input[type='text'] {width:50px;}
textarea {width:500px;height:300px;}
</style>
</head>
<body>
<div>
<h2>Test</h2>
<p>The number of words is <span id="wordCount"></span></p>
<textarea id="toCount"></textarea>
</div>
<script>
document.getElementById('toCount').addEventListener('input', function () {
var text = this.value,
count = text.trim().replace(/\s+/g, ' ').split(' ').length;
document.getElementById('wordCount').textContent = count;
});
</script>
</body>
</html>
The reason why you are getting null is: in selection, #wordCount is by Id, and .wordCount is by class. So document.querySelector('.wordCount') is returning null as there is no element with class wordCount.
The fix would be to simply change
document.querySelector('.wordCount').textContent = count;
to
document.querySelector('#wordCount').textContent = count;
Try this one.
document.getElementById('toCount').addEventListener('input', function () {
// var text = this.textContent,
var text = this.value,
count = text.trim().replace(/\s+/g, ' ').split(' ').length;
// document.querySelector('#wordCount').textContent = count;
document.querySelector('#wordCount').textContent = count;
});
try this.
document.getElementById('toCount').addEventListener('input', function () {
var text = this.value,
count = text.trim().split(' ').length;
document.querySelector('#wordCount').textContent = count;
});
Here is the jsfiddle
Related
So I am currently trying to find out how to select text between two characters(for the example I will use a slash / )
Here is what I have so far.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var secondStartingPoint, startPointOne, startPointTwo;
if (text.indexOf("/", 0) !== -1) {
//I did -1 because indexOf returns -1 if nothing is found.
/*Also, the second argument in indexOf() acts as my starting
point for searching.*/
secondStartingPoint = text.indexOf("/") + 1;
startPointOne = text.indexOf("/") + 1;
if (text.indexOf("/", secondStartingPoint) !== -1) {
startPointTwo = text.indexOf("", secondStartingPoint) + 1;
var selectedText = slice(startPointOne, startPointTwo);
$("body").append("<p>" + selectedText + "</p>");
//but nothing happens.
}
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>/can I select and duplicate this?/</p>
</body>
</html>
But it doesn't do anything.
It could be achieved simply by using a regex like :
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var extracted = text.match(/\/(.*)\//).pop();
alert('The extracted text is :'+extracted);
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>Some text here in the start /can I select and duplicate this?/ Some extra text at the end</p>
</body>
</html>
Regex is simplest and easiest way to get your solution.
use exec() function to get text between '/';
console.log(/^\/(.*)\/$/.exec('/some text, /other example//'))
I've got a product title which I'm splitting and inserting a linebreak using javascript like this:
<script>
function myFunction() {
var str = "How are you - doing today?";
var res = str.split("-").join('<br>');
document.getElementById("demo").innerHTML = res;
}
</script>
This works for most case scenarios, however in some cases I will need to remove the second line completely. So everything after the - will need to be removed. Only within that element though, so if I've got this for example
<h3>This is a product - title</h3>
the result should be
<h3>This is a product</h3>
Again this only needs to apply to elements with a certain class. Anybody got any idea ow to do this?
Why not us a simple replace,
string = string.replace(/-/g, '<br>');
or for complete deletion, take
string = string.replace(/-.*$/g, '');
Check className of the element:
function myFunction() {
const str = `How are you - doing today?`
const first = str.split(`-`)[0]
const all = str.split(`-`).join(`<br/>`)
const el = document.getElementById(`demo`)
const el.innerHTML = el.className === `any-name` ? first : all
}
Try this:
(function() {
// For splitted titles
var split = document.querySelectorAll(".dash-split");
var splits = [];
split.forEach(function(spl) {
splits.push(spl.innerHTML.split("-").join("<br>"));
});
console.log(splits); // Outputs ["This is <br> split!"]
// For removed titles
var removedEls = document.querySelectorAll(".dash-split");
var removed = [];
removedEls.forEach(function(rem) {
removed.push(rem.innerText.split("-")[0].trim());
});
console.log(removed); // Outputs ["This is"]
})();
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<div>
<h1 class="dash-split">This is - split!</h1>
<h1 class="dash-remove">This is - removed!</h1>
</div>
</body>
</html>
This should get you what you want, provided the script runs at the end of the document. For wrapping, it keys off of the class title-wrap.
<html>
<head></head>
<body>
<h3>This is a product - title</h3>
<h3 class="title title-wrap">This is a product - with a wrapped title</h3>
<h3>This is a product - with another title</h3>
<script>
(function() {
var titles = document.querySelectorAll('h3');
titles.forEach(function(o, i) {
var title = o.innerHTML;
if (/title-wrap/ig.test(o.className)) {
o.innerHTML = title.replace(/-/g, '<br />');
} else {
o.innerHTML = title.replace(/-.*$/g, '');
}
});
})();
</script>
</body>
</html>
Why is this code not working? So far I have only got it to work as an input. I need it to work as a label or span. I need the label to count up 1 number on every click.
<html>
<head>
<script type="text/javascript">
var a = 1;
function increase () {
document.getElementById("text").value=a;
a=a+1;
}
</script>
</head>
<body>
<button type="button" onclick="increase()">show</button>
<label type="text" id="text">0</label>
</body>
Your increase() function should look like this:
function increase() {
a++;
document.getElementById("text").innerHTML = a;
}
The reason its not working is that label or span doesn't have value attribute. You should use innerHTML instead.
Value attribute is present only on <input> tags. For every other tag (like <span>, <div>, <label>) you should use innerHTML.
Edit
To add clarity, the above code is only the increment() function. The entire code should look like this:
var a = 0;
function increase() {
a++;
document.getElementById("text").innerHTML = a;
}
Considering John Hascall comment, a++ can be placed after document.getElementById("text").innerHTML = a.
var a = 0;
function increase() {
a++;
document.getElementById("text").innerHTML = a;
}
<button onclick="increase()">Click</button>
<label id="text">0</label>
try this fiddle
i have tried parseInt()
var a = parseInt(document.getElementById("text").innerHTML);
a++;
console.log(a);
document.getElementById("text").innerHTML = a;
You need to use document.getElementById("text").innerHTML=a, because the value of a <label> does not define its inside text.
Your example would then look like this:
<html>
<head>
<script type="text/javascript">
var a = 1;
function increase() {
a++;
document.getElementById("text").innerHTML = a;
}
</script>
</head>
<body>
<button type="button" onclick="increase()">show</button>
<label type="text" id="text">0</label>
</body>
im trying to change a line of text if a link is clicked, however it doesnt seem to be calling my script to change it.
<script >
var paragraphToChange = document.getElementById("q1");
paragraphToChange.innerHTML ="Quotation is by:" + Antole France
</script>
<div id="body">
<p>javascript.html - JavaScript page</p>
<a href id="q1">Quotaion is by:</a>
</div>
What you're trying to accomplish is probably something like this:
HTML
<div id="q1">
<a onClick="javascript:clickFunction()">Quotation is by</a>
</div>
JavaScript
clickFunction = function() {
document.getElementById("q1").innerHTML = "<a href='http://www.quotationspage.com/quote/1463.html'>Antole France</a>";
}
JSFiddle
Sir you have to set the value of "newValue" to the quotation.
var newValue = '"Quotation is by:" + Antole France'
paragraphToChange.innerHTML = newValue;
You are missing the click event on the Html tag. Hence, this paragraphToChange.innerHTML ="Quotation is by:" + Antole France"
never gets call.
Why don't you start with this example first:
<p id="display"></p>
<button onclick="displayBob">Bob</button>
<button onclick="displayTom">Tom</button>
<script>
displayBob = function ()
{
document.getElementById("display").innerHTML = "Hello Bob";
}
displayTom = function ()
{
document.getElementById("display").innerHTML = "Hello Tom";
}
</script>
Problem : So I have alerted the value of textarea by:
var source = document.getElementById('source').value;
alert(source);
But the value of textarea is alerted as it was at the time of page load. And I want to alert current value of the textarea. I have also tried
$("form").submit(function(){
But that also haven't helped me. So how can I do this?
This is my code.
<html>
<head>
<title>Perl WEB</title>
<script type="text/javascript" src="http://code.guru99.com/Perl1/codemirror.js"></script>
<link rel="stylesheet" href="http://code.guru99.com/Perl1/codemirror.css" type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://code.guru99.com/perl/perl.js"></script>
<style>
.CodeMirror {
border: 1px solid #eee;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
});
});
</script>
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg.CORE.warn = function(List__) {
var i;
List__.push("\n");
for (i = 0; i < List__.length; i++) {
document.getElementById('log-result').value += p5str(List__[i]);
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = document.getElementById('source').value;
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('log-result').value = "";
// document.getElementById('js-result').value = "";
document.getElementById('print-result').value = "";
try {
// compile
document.getElementById('log-result').value += "Compiling.\n";
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
document.getElementById('log-result').value += "Compilation time: " + time + "ms\n";
// document.getElementById('js-result').value += js_source + ";\n";
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
document.getElementById('log-result').value += "Running time: " + time + "ms\n";
p5pkg.CORE.print(["\nDone.\n"]);
}
catch(err) {
document.getElementById('log-result').value += "Error:\n";
document.getElementById('log-result').value += err + "\n";
document.getElementById('log-result').value += "Compilation aborted.\n";
}
}
</script>
</head>
<body>
<form>
<textarea id="source" cols="70" rows="10">
say 'h';
</textarea>
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="button" value="Run" onclick="execute()"/></br>
Output:</br>
<textarea id="print-result" disabled="true" rows="10" cols="70"></textarea></br>
Log:</br>
<textarea id="log-result" disabled="true" cols="70"></textarea>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("source"), {
lineNumbers: true,
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
</form>
</body>
</html>
So how can I get the current value of the textarea? Please help me guys.
I'm not familiar with CodeMirror, but what you exactly see on the screen, is not your original #source anymore. Instead there are several elements created by CodeMirror, and the original textarea is hidden.
When I look at the documentation, I found this:
var source = editor.doc.getValue();
alert(source);
Or, since you've constructed the editor object with fromTextArea() method, you can update the value of the the textarea before reading it:
editor.save();
var source = document.getElementById('source').value;
alert(source);
Notice also what Adam has said about submitting the form. And there are invalid </br> tags in your HTML, the correct form is <br />.
Please visit at CodeMirror User Manual for the furher information.
As you have jQuery loaded you can do as follows:
var content = $('#source').val();
alert(content);
Of course, if you do it at page load, the textarea will be empty (or even uncreated). You could extract its content on form submit, as you seem to suggest.
This code will create a button that will alert the content of your textarea when clicked:
<button onclick="alert($('#source').val())">Click me</button>
Try the following inside the submit()
var textAreaVal = $("#print-result").val();
alert(textAreaVal);
Your form does not get submitted when the button in it is pressed since this is not a submit button.
This will not submit the form, and will not alert its' contents.
<input type="button" value="Run" onclick="execute()"/></br>
Add something like this in the form:
<input type="submit" value="Submit">
if yout want the value to alert when the mouse leaves the textarea you could try to add onblur="myFunction()" to the input something like: (actually if you want it on mouse leave, you can add onmouseout="myFunction()")
<textarea id="source" cols="70" rows="10" onblur="myFunction()">
say 'h';
</textarea>
<script type="text/javascript">
function myFunction() {
var source = document.getElementById('source').value;
alert(source);
}
</script>