Bootstrap single word textbox - javascript

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

Related

Dynamic text entry with JavaScript

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>

Event Driven Programming: Registering input changes

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);

Input field with attached text to the right

I'm doing a fancy comment list on my project, structured like this:
As you see, there's a comments list and at his bottom there's an input field (textarea) to submit a comment. Note that there's the current username attached to the right (let's call it a simple static appended text).
I just found this little JS to make an input field resize automatically by adapting it to the content.
function resizeInput() {
$(this).attr('size', $(this).val().length);
}
$('input[type="text"]').keyup(resizeInput).each(resizeInput);
But it's not enough. I need it for a textarea and I want it to behave correctly when a comment is long enough to wrap on another line. By definition, the input field is a box, and it obviously acts badly compared to what I want:
Instead, this should be the right behavior:
I looked everywhere and I can't think any way to implement this. Can somebody help me?
Here is a good plugin for textarea. But it using jQuery.
usage simple as always.
$(document).ready(function(){
$('textarea').autosize();
});
You could use the contenteditable attribute:
<span contenteditable="true">comment</span> by <span class="userName">someone</span>
It is supported in practically all browsers. Using the right CSS, you can underline the content and also limit the width.
I think you mean this
NOTE: No check for selection and bound to document. Exercise for the reader to bind to a specific field and swap it for a span
FiDDLE
$(document).keypress(function(e) {
var char = String.fromCharCode(e.which);
if (e.which==13) char = '<br/>'; // needs to handle backspace etc.
$("#textfield").append(char);
$("#hiddenfield").val($("#textfield").text()); // or .html if you want the BRs
e.preventDefault();
});
using
<span id="textfield"></span> - by My Username
If you make the field contenteditable you will get this in Chrome so some additional CSS may be needed
Use a <span> with contenteditable (supported in IE too). Here is a fiddle: http://jsfiddle.net/goabqjLn/2/
<span contenteditable>Insert a comment...</span> by My Username
Then, using JavaScript, attach an event listener that mirrors the inner text of the span into a hidden input field, so it gets submitted with your <form>.
Edit: I have updated the fiddle to also include the JS code. Here is the updated code:
<span class="editor" id="editor" contenteditable data-placeholder="Insert a comment...">Insert a comment...</span> by My Username
<!-- Hide this textarea in production: -->
<textarea type="text" id="comment"></textarea>
And the JS:
function mirror() {
var text = $('#editor').html().trim()
.replace(' ', ' ')
.replace(/<br(\s*)\/*>/ig, '\n') // replace single line-breaks
.replace(/<[p|div]\s/ig, '\n$0') // add a line break before all div and p tags
.replace(/(<([^>]+)>)/ig, ""); // remove any remaining tags
$('#comment').val(text);
}
$('#editor').focus(function () {
var editor = $(this);
if (editor.text() == editor.attr('data-placeholder')) {
editor.text('');
}
}).blur(function () {
var editor = $(this);
if (editor.text() == editor.attr('data-placeholder')) {
editor.text(editor.attr('data-placeholder'));
}
}).blur(mirror).keyup(mirror);

Update placeholder text with new text onClick/onFocus

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!

Javascript for mobile HTML form

I am having some problems with Javascript :(
This is an HTML form for a mobile webpage. To save space I put the names of the text fields inside the boxes. The name disappears when you focus on the box, but I am not able to make it reappear if the user didn't write anything.
Here is the Script (in head tag):
<script type="text/javascript"> resetDefault();{if (this.value.length==0); this.value="default";} </script>
Here is the HTML code:
<input onfocus="this.value=''" onblur="resetDefault()" name="nom" type="text" value="Nom complet" default="Nom complet"/><br><input onfocus="this.value=''" onblur="resetDefault()"name="courriel" type="text" value="Courriel" default="Courriel"/><br>
I keep getting a "resetDefault is not defined" error. I don't know if default is an accepted attribute for input, but I can't set it to "value" because value becomes 0 once someone has focused on the text field, right?
There are several problems with your javascript code. First, it is not syntactically correct. You should first change this code
resetDefault();
{if (this.value.length==0);
this.value="default";}
so that it has valid syntax, like this:
function resetDefault(){
if(this.value.length == 0){
this.value = "default";
}
}
The second problem is that this refers to the global object, instead of the DOM node you want. You need to pass in a value so it knows which input to change.
Change the onblur javascript so that it passes in a parameter to the function:
onblur="resetDefault(this);"
and change the function so it accepts a parameter:
function resetDefault(that){
if (that.value.length == 0){
that.value="default";
}
}
The third problem is that "default" will just change the value of the input box to the string, "default". I doubt that is what you want. Make the value match the default attribute you gave the input:
that.value = that.getAttribute("default");
Try it out on JSFiddle
The semicolon after resetDefault() in the script in the head needs to be removed - now it's a function call of a function that's not defined.
<script type="text/javascript">function resetDefault() { if (this.value.length==0) this.value="default";} </script>
You need to define the resetDefault() function like so:
function resetDefault() {
// Function stuff here
}

Categories

Resources