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>
Related
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
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);
I'm trying to make a simple mad libs type game. To do so I need to do the following:
Have space that user can input text
Retrieve text that user inputted
Assign text to variables using Javascript
Place variables in Mad libs
I know how to do this using something like:
var userAnswer = prompt("Give me an answer");
However, I want to get the input from a text input field. I was trying to do the following but I got stuck:
Have input area with id="input1"
Create function that takes content of #input1 and assign to a variable.
Use button to run the function
I will then later use these variables in my story
<label for='input1'>Verb + ing</label><input id='input1'>
<script>
var setInputs = function() {
var space1 = document.getElementById("input1").innerHTML;
}
</script>
<button onclick="setInputs">Click me</button>
I'm I going about this the correct way?
Fiddle: http://jsfiddle.net/6rjf5k9n/
Try This
<label for='input1'>Verb + ing</label><input id='input1'>
<script>
var setInputs = function() {
var space1 = document.getElementById("input1").value;
alert(space1);
}
</script>
<button onclick="setInputs()">Click me</button>
.value gives you the currently-set value of a form element (input, select, textarea), whereas
.innerHTML builds an HTML string based on the DOM nodes the element contains.
My first SO question! Here's what I am trying to do:
I'm rewriting a tool that generates some code a user can paste directly into Craigslist and other classified ad posting websites. I have created a list of websites (they populate from a database with PHP) the user can choose from with a radio button, and I want their choice to populate as bare text (not a link) between some <p></p> elements in a textarea. I'm using jQuery for this.
Textarea before the user chooses:
<p id="thing"></p>
Textarea after the user chooses:
<p id="thing">www.somewebsite.com</p>
HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<textarea>
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
JS
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
alert(website);
$("#thing2").html(website);
});
});
JS Fiddle (With comments)
If you see the JS Fiddle, you can see that I put another p element on the page outside the textarea, and it updates just fine, but the one inside the textarea does not. I have read many other like questions on SO and I'm starting to think that I can't change an element that's between textarea tags, I can only change the entire textarea itself. Please, lead me to enlightenment!
You actually can fairly easily manipulate the text contents of the textarea like it is part of the DOM, by transforming its contents into a jQuery object.
Here is a jsFiddle demonstrating this solution: http://jsfiddle.net/YxtH4/2/
The relevant code, inside the input change event:
// Your normal code
var website = $(this).val();
$("#thing2").html(website);
// This turns the textarea's val into a jQuery object ...
// And inserts it into an empty div that is created
var textareaHtml = $('<div>' + $("#textarea").val() + '</div>');
// Here you can do your normal selectors
textareaHtml.find("#thing").html(website);
// And this sets the textarea's content to the empty div's content
$("#textarea").val(textareaHtml.html());
The empty div wrapping your HTML is so that you can easily retrieve it as a string later using jQuery's .html() method, and so the parse does not fail if additional text is entered around the p element inside the textarea.
The real magic is $($("#textarea").val()), which takes your textarea's text and parses it into an HTML node contained in a jQuery object.
It can't do it the way that you are thinking (i.e., manipulate it as if it were a DOM element), but it is still accessible as the value of the textarea, so you can retrieve it like that, use basic string manipulation to alter it, and then set the updated string as the new value of the textarea again.
Something like this . . . first give the <textarea> an id value:
<textarea id="taTarget">
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
Then alter your script like this:
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
var currentTAVal = $("#taTarget").val();
$("#taTarget").val(currentTAVal.replace(/(<p id="thing">)([^<]*)(<\/p>)/, "$1" + website + "$3"));
});
});
Unless you need the <p> element in there, you might consider using a more simple placeholder, since it won't actually act as an HTML element within the textarea. :)
EDIT : Fixed a typo in the .replace() regex.
I know that this answer is a little bit late, but here it goes =)
You can do exactly the way you want to do. But for that, you need to implement a small trick.
by having this HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com
<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<p id="thing2"></p>
<textarea id="textarea">
<p id="thing"></p>
</textarea>
you can edit textarea content, as a DOM by implementing something like the function changeInnerText
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val(); // Gets value of input
changeInnerText(website);
//$("#thing").html(website); // Changes
//$("#thing2").html(website); // Does not change
});
var changeInnerText = function(text) {
var v = $("#textarea").val();
var span = $("<span>");
span.html(v);
var obj = span.find("#thing")[0];
$(obj).html(text);
console.log(obj);
console.log(span.html());
$("#textarea").val(span.html());
}
});
As you can see, I just get the information from the textarea, I create a temporary variable span to place textarea's content. and then manipulate it as DOM.
Instead of attempting to insert the text into the <p> element, insert the text into <textarea> element and include the <p> tag. Something like this should do the trick:
Change:
$("#thing").html(website);
to:
$("textarea").html('<p id="thing">'+website+'</p>');
And here is a fiddle: http://jsfiddle.net/nR94s/
I am trying to setup an interchange using two texts boxes with a command button in between.
The idea is you type a reference/code in the left hand text box, click the button and it generates an alternative reference/code in the right hand text box.
The point being the user can check alternate bearing references if they can't find what they are looking for with the one they have.
The code I use so far is:
<script type="text/javascript">
oldRef = new Array ("Z582","T608","A173");
newRef = new Array ("C850","S708","X449");
function convert()
{
document.getElementById("v2").value = "";
for (index=0 ; index < oldRef.length ; index++)
{
if ( document.getElementById("v1").value == oldRef[index] )
document.getElementById("v2").value = newRef[index];
}
}
</script>
V1 and V2 refer the the text box ID.
This works with the text boxes but I don't know how to incorporate the command button into this so that they need to click the button in the middle for it to generate.
Any suggestions would be much appreciated.
Best
Will
Its pretty Easy stuff what you need to do is to use onclick of the button like this
document.getElementById('button').onclick = function () {
document.getElementById("v2").value = "";
for (var index=0 ; index < oldRef.length ; index++) {
if (document.getElementById("v1").value == oldRef[index])
document.getElementById("v2").value = newRef[index];
}
}
Here is a demo
I hope this is waht you want....
So essentially there are two things that you need to accomplish what you asked. You need to create a element within your HTML, in this case a button. You then need to catch the event that you want to catch from that element and then execute you convert function.
This is one example of accomplishing this:
So create an button within your HTML
<button id="btn_command">Command</button>
Then in Javascript you want to target that button and add an event listener to that button. In the example the below the variable var btnCommand is set to the html button by using the getElementById method to get that button with that id. Then we add and event listener to that element that when clicked it executes your convert function.
var btnCommand = document.getElementById ("btn_command") ;
btnCommand.addEventListener("click", convert, false) ;
If you want to use jQuery you would do something like this.
$('#btn_command').on('click', function() { convert(); });
Here is another quick and dirty way to just test you button with your function. It is not a best idea to mix your javascript inline with your html but just to test your button and if your convert function is doing that you think you could just say
<button onClick="convert()">Command</button>
Well there are few ways to accomplish what you asked. Happy Coding!