I am very new to html, css, and javascript so please go easy on me. I am working on an activity that requests: Register the updateCount event handler to handle input changes for the textarea tag. Note: The function counts the number of characters in the textarea.
The Javascript so far is as follows -
var textareaElement = document.getElementById("userName");
function updateCount(event) {
document.getElementById("stringLength").innerHTML = event.target.value.length;
}
// Write code here
I have absolutely no idea what it is asking of me for this problem. Both online resources and textbooks have not been very helpful.
The HTML cannot be changed in any way, forcing me to solve it with just changes the the javascript.
The HTML is as follows -
<label for="userName">User name:</label>
<textarea id="userName" cols="40" rows="3"></textarea><br>
<p id="stringLength">0</p>
Any help would be much appreciated, I'm just trying to learn.
Try this. Add onkeyup event on the <textarea> tag then replace event.target to textareaElement to get the value
var textareaElement = document.getElementById("userName");
function updateCount() {
document.getElementById("stringLength").innerHTML = textareaElement.value.length;
}
<label for="userName">User name:</label>
<textarea id="userName" onkeyup="updateCount()" cols="40" rows="3"></textarea><br>
<p id="stringLength">0</p>
When you have a reference to a DOM node (e.g, <textarea>), you can bind event handlers for the various events that it supports. In this case, we consult the HTMLTextAreaElement docs and learn that the following piece of JS would give the text length
const textarea = document.getElementById('userName');
const length = textarea.value.length; // textarea.textLength;
Then, we will consult the docs to determine that it is the input event that we want to bind to.
textarea.addEventListener('input', updateCount);
Your updateCount gets as its input the input event that also contains a reference to the event target, which is the textarea.
var textareaElement = document.getElementById("userName");
function textSize(event) {
document.getElementById("stringLength").innerHTML = event.target.value.length;
}
textareaElement.addEventListener("input", function(event){
document.getElementById("stringLength").innerHTML = event.target.value.length;
});
I know the post is old but I just had to figure this one out for myself so for anyone else that has trouble in the future here is the line you need.
textareaElement.addEventListener("blur", updateCount);
Related
I'm trying to find a way to trigger JavaScript when writing on an input
Thanks to everyone can help me
<input id="tophead-searchbar" class="searchbar" placeholder="Cerca" onfocus="mostraanteprimericerca();" onchange="Result1InnerHTML();">
Anyone that can help me?
function Result1InnerHTML() {
document.getElementById("Result1").innerHTML = "Cerca" + document.getElementById("tophead-searchbar").innerHTML + "su Nevent";
}
This is the function I want to call
To get the input as the user types, use the input event. This will also catch content which the user pastes in using
the mouse.
Also note that using onX attributes in your HTML is no longer good practice and should be avoided. Use unobtrusive event handlers attached within your JS code. This can be done using the addEventListsner() method.
Finally, input elements don't have any innerHTML, you need to read the value of the control instead.
const input = document.querySelector('#tophead-searchbar');
const output = document.querySelector('#result');
input.addEventListener('input', e => output.innerHTML = `Cerca ${input.value} su Nevent`);
<input id="tophead-searchbar" class="searchbar" placeholder="Cerca" />
<div id="result"></div>
You can use oninput event instead of onchange
Let me preface this by saying that I am currently a JavaScript beginner, and would really appreciate it if someone could point me in the right direction, as I am currently at a bit of a loss.
I found this pen written in Vue.js. It does a few things, but I am interested in the function wherein text appears in plain html as you type data in the field.
I was wondering how this could be accomplished with JavaScript?
https://codepen.io/mitchell-boland/pen/NVZyjX
computed: {
// Think of this as live updates
reverseString: function() {
if(this.task) {
return this.task.split('').reverse().join('')
}}}})
It's relatively straightforward. You can listen for the "input" event on the textbox and copy the current value of the textbox into another element.
In the case of your example, the text is also being reversed at the same time, for which you need a little bit of extra code.
Here's a runnable demo:
var input = document.getElementById("textIn");
var output = document.getElementById("output");
//listen to the "input" event and run the provided function each time the user types something
input.addEventListener("input", function() {
//this line reverses the typed value
var textOut = this.value.split("").reverse().join("")
//write the output to another element
output.innerText = textOut;
});
<input type="text" id="textIn" />
<div id="output"></div>
P.S. You didn't mention the reversing of text in your question, so if you don't want it you can simplify the above by removing that line and writing the value of the input box directly into the div element, e.g.
var input = document.getElementById("textIn");
var output = document.getElementById("output");
//listen to the "input" event and run the provided function each time the user types something
input.addEventListener("input", function() {
//write the output to another element
output.innerText = this.value;
});
I'll post this as answer:
If you're wondering how the input text turns to a reversed text in the pen, then you might need this:
function reverseText(txt){
document.getElementById("#output").innerText = txt.split("").reverse().join("");
}
<input type="text" onkeyup="reverseText(this.value)" />
<p id="output"></p>
I was wondering if there is any way to make a bootstrap textbox that only accepts one word, or if not any way to show an error message if more than one word is put into the text box.
You could use simple regexp like this /^\w+$/ to check if the value is only one word. To check the value, bind to onkeyup or onchange event on that input:
var input = document.getElementById('text');
var error = document.getElementById('error');
input.onkeyup = function() {
if (!input.value.match(/^\w+$/)) {
error.innerText = 'fill in only one word!';
} else {
error.innerText = '';
}
};
<input type="text" id="text">
<div id="error"></div>
no, there isnt.
if you want it, I would suggest you to use the keyup event and take your event.target.value.trim().split(' '), if more than 1 position, then it has more than 1 word.
You could handle the value when it changes.
$(document).ready(function() {
$('#txt-one').change(function() {
if (/ /g.test($.trim(this.value))) {
console.log('You have entered more than one word!')
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input id="txt-one" type="text" class="form-control" />
Well bootstrap doesn't provide this functionality by default but you can write a small script for it. Please refer the link below, I have written a small script it should be able to give you a basic idea of implementation.
JS BIN Code
https://jsbin.com/duzevuleye/edit?html,output
Here is one I just had come up and the solution baffled me and no search here at SO revealed anything.
Standard input field:
<input type="input" name="fName" placeholder="Your First Name">
But let us say I would like to update the placeholder text when somebody clicks on the field or when the field is onfocus via pressing the Tab key.
So it would become:
<input type="input" name="fName" placeholder="Your First Name Goes Here">
Just a very basic example of what it would do, by adding the "Goes Here" to the placeholder text.
Doable? Even possible to modify placeholder? Unknown to me.
If so and it is possible via pure JS or via jQuery, I would be entertained in seeing how.
This should do it (edit:added blur reset):
$('input[name=fName]').on("click focus",function(){
$(this).attr("placeholder","Your First Name Goes Here");
}).on("blur",function(){
$(this).attr("placeholder","Your First Name");
});
Updated Fiddle: http://jsfiddle.net/6tb8v/1/
To do it in pure JS, you should use addEventListener() to get the click/focus event and setAttribute() to set the placeholder attribute.
var elem = document.getElementsByName("fName")[0];
function appendPlaceholder () {
elem.setAttribute ("placeholder", "Your First Name Goes Here");
}
elem.addEventListener("click", appendPlaceholder);
elem.addEventListener("focus", appendPlaceholder);
elem.addEventListener("blur", function () {
elem.setAttribute ("placeholder", "Your First Name");
});
Here's a JS answer. I tend to dislike JQuery.
var myInpt = document.getElementsByTagName('input');
var key;
for(key in myInpt)
{
myInpt[key].addEventListener('click', updateInpt, true);
}
function updateInput(evt)
{
this.inpt = evt.srcElement;
var plchldrText = this.inpt.getAttribute('placeholder');
this.inpt.setAttribute('placeholder', plchldrText + ' Goes Here');
}
Of course, this attaches the click event to every input element on your page, as well as every time you click it, it adds the string ' Goes Here'. Haha. If you want to do it this way, maybe you should add an id to the input and collect it in JS that way. Just a thought and a simple example! Hope it helps!
I have this text box in HTML:
<script src="../js/writeTo.js"></script>
<form>
<div class="post-title">
<input type="text" placeholder="Post Title">
</div>
<div class="post-content">
<textarea type="text" placeholder="Post Content"></textarea>
</div>
<button type="submit" class="submit">Submit</button>
</form>
and my js file called writeTo.js contains this code:
var url = "https://blog-posts.firebaseio.com/";
var firebaseRef = new Firebase(url);
function funct1()
{
var title = $('#post-title').val();
var post = $('#post-content').val();
var date = Date();
firebaseRef.set({Title: +title, Content: +post, Date: +Date()});
}
submit.onclick = funct1();
When I type something in my text box and click submit, I look at my Firebase and there is no new data (I'm also new to using Firebase).
It does not work, can anyone see the problem? (There are probably a few, I am new to JavaScript)
There are a few problems with your script. I've solved them in this jsfiddle, but will also explain below.
Getting the text content of your inputs
Your HTML for the inputs looks like this:
<div class="post-title">
<input type="text" placeholder="Post Title">
</div>
The JavaScript you use to read the value is:
var title = $('#post-title').val();
If you read the documentation for val, you'll see that it is meant to be invoked on the input element itself. You are invoking it on the wrapping div.
The simplest change is to get the value like this:
var title = $('#post-title').text();
Associating the handler with the form
You hook up your event handler with the form like this:
submit.onclick = funct1();
Unfortunately this will not work as you expect it to.
What is does is:
Invoke funct1
Assign the return value of funct1 to onclick
What you instead want to do is:
submit.onclick = funct1;
So this will assign funct1 to onclick.
You might want to read up on more modern approaches of assigning event handlers btw.
Passing the values to Firebase
Your code for passing the values to Firebase seems a bit off. Use this instead
firebaseRef.set({Title: title, Content: post, Date: date});
Cancel the regular browser handling of the form submit
The browser normally handles clicks on a form's submit button by posting the form's values to a URL.
But in your application you are handling this yourself, so you should tell the browser to ignore the submit.
You can do this by returning false from your function:
return false;
Note that this will give the following warning in Chrome:
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
So you should indeed consider using event.preventDefault() instead of returning false. See the total code below for how to do that.
Complete code
var url = "https://blog-posts.firebaseio.com/";
var firebaseRef = new Firebase(url);
function funct1(evt)
{
var title = $('#post-title').text();
var post = $('#post-content').text();
var date = Date();
firebaseRef.set({Title: title, Content: post, Date: date});
evt.preventDefault();
}
var submit = document.getElementsByTagName('button')[0];
submit.onclick = funct1;
Adding a new post, instead of overwriting the existing one
Your code will now replace the blog post that lives at your Firebase. I imagine that you'll probably prefer to add a new post, when pressing the submit button.
To accomplish this, you'll need to call Firebase's push function. Firebase has some great documentation on managing lists.
The gist of it is this though:
var postRef = firebaseRef.push(); // create a new post
postRef.set({Title: title, Content: post, Date: date});
So you create a new post and then set your values on that, instead of on the top-level Firebase ref.