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!
Related
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
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);
How to find the value of text field using onblur() in next input field.
I tried:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByTagName('text1').value;
alert(inv_nrs);
}
text1 is name of input which I am trying to get value.
text2 is name of input where onblur() is triggered.
Two problems:
To get elements by their name attribute, use document.getElementsByName(), not document.getElementsByTagName.
Since these functions return a collection, not a single element, you have to index them to get a specific element.
So the function should be:
function get_value() {
var inv_nrs;
inv_nrs = document.getElementsByName('text1')[0].value;
alert(inv_nrs);
}
Here's a simple snippet which illustrates a way to do this.
(You may wish to use alert in place of console.log)
document.getElementById("text2").onblur = function() {
console.log(document.getElementById("text1").value)
}
<input type="text" id="text1" value="123" />
<input type="text" id="text2" />
Are you looking for an element with id = "text1" or real name = "text1"?
At least if it's their id try getElementById("text1"), that returns one single element. If you talking about the name-attribute, take getElementByName("text1"), this may return more than one element (if there are more then one with the same name).
i think you want this???
function get_value()
{
var inv_nrs;
inv_nrs = document.getElementById('txt1').value;
document.getElementById('txt2').value=inv_nrs;
}
<input type="text" id="txt1" >
<input type="text" id="txt2" onblur="get_value()">
If you search with tagname then you need to insert a tagname:
document.getElementsByTagName('input')[whole_number].value which also
returns a live HTMLCollection
Eg. document.getElementsByTagName("input")[0].value; ,if this is the first textbox in your page.
You can get the value of an html element also on different ways:
document.getElementsByName('text1')[whole_number].value which also
returns a live NodeList
Eg. document.getElementsByName("searchTsxt")[0].value; if this is the
first textbox with name 'searchtext' in your page.
You can also get element by Id:
document.getElementById('IDHere').value to get the value of desired
box
You can also get it by way of Classname:
Use document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollection
Good luck
This question already has answers here:
Escape quotes in JavaScript
(13 answers)
Closed 8 years ago.
this should be simple but I can't figure it out.
I want to let user edit a value. To do so, upon click, the value changes into a textbox. However, if the user puts a quote mark in the user input within the text box the value="" attribute of the text box closes prematurely and the quote mark and anything after it gets lost. Escape (deprecated) and encodeURI merely replace the quote mark with asci does which don't look good in the textbox.
Would appreciate anyone's solution to this problem:
Here is javascript:
function editText() {
var text = document.getElementById('text').innerHTML;
var edittext = '<input type="text" size=60 name="name" id="name" value="'+text+'"><input type="button" value="Save" onclick="storeText(\'name\');">';
document.getElementById('text').innerHTML = edittext
return false;
}
html:
Text: <span id="text" onclick="editText()";>He said "that's cool"</span>
jsfiddle
http://jsfiddle.net/2s9v2/6/
UPDATE:
Contrary to what those who marked this as a duplicate say, the duplicate question does not provide an answer to my question. They might want to re-read my question and the so-called duplicate and mentally register the word "programmatic" in my question and actually look at the code in the duplicate relaive to the code here.... Just saying.
I ended up changing the textbox to a textarea as a workaround as there does not seem to be a straightfoward way to programmatically escape a quote within a textbox.
The answer from Merlin below is a possible approach but calling the second function is more complex than just replacing textbox with textarea. In any case, I could not get that to work but I thank Merlin for his answer and upvoted it.
Try: text.replace(/"/g,""")
Ideally, though, you should be creating the elements with createElement, at which point you can do elem.value = text with no need for escaping.
Why not just set the value directly instead of rebuilding the input?
document.getElementById('name').value = edittext
Of course, this assumes that the input element with id=name already exists in your DOM, but I see no particular reason you could not ensure that it is already there (either writing directly in HTML or generating in Javascript on page load).
Update: It seems that the OP wants the element to be dynamically created in the onClick, by turning the text that is currently in a div into an input field with the contents of that div as its value.
I believe the following might do the trick, assuming id is unique as it should be.
function editText() {
var text = document.getElementById('text').innerHTML;
var edittext = '<input type="text" size=60 name="name" id="name" value="" /><input type="button" value="Save" onclick="storeText(\'name\');">';
document.getElementById('text').innerHTML = edittext;
document.getElementById('name').value = text;
document.getElementById('text').onclick = function() {}; //
return false;
}
Note that you will need to disable the onClick inside the above function as well, and then re-enable it inside storeText, because otherwise every click will cause extra buttons to be added.
Update 2: Here is a fully working example without parameter passing (for simplicity).
<html>
<body>
<script>
function editText() {
var text = document.getElementById('text').innerHTML;
var edittext = '<input type="text" size=60 name="name" id="name" value="" /><input type="button" value="Save" onclick="storeText();">';
document.getElementById('text').innerHTML = edittext;
document.getElementById('name').value = text;
document.getElementById('text').onclick = function() {};
return false;
}
function storeText() {
document.getElementById('text').innerHTML = document.getElementById('name').value;
document.getElementById('text').onclick = "editText();";
}
</script>
<div id="text" onclick="editText();">HelloWorld</div>
</body>
</html>