How to put the text from text area in paragraph? - html

More exactly I want when I press enter to put my line in <p> for example:
<p>HELLO</p>
<p>Another line</p>
<p>Line 3</p>
To upload like this in database
Here is my code where I want to do this
<div class="form-group">
<label for="phone-pin">Text</label>
<textarea type="text" class="form-control" id="text-area-first" name="text-area-first" required placeholder="text"></textarea>
</div>

Here is a solution.
function store() {
var txt = document.getElementById("text-area-first").value;
var txttostore = '<p>' + txt.replace(/\n/g, "</p>\n<p>") + '</p>';
console.log(txttostore);
}
<div class="form-group">
<label for="phone-pin">Text</label>
<br>
<textarea type="text" class="form-control" id="text-area-first" name="text-area-first" required placeholder="text"></textarea>
<br>
<button id="store" onclick="store()">Store</button>
</div>

You can do this by using javascript onkeypress event.
As we know Enter has keycode 13 then match that keycode and do your work.
Assign the value to a variable and store that variable into database.
<html>
<body>
<textarea name="text" id="texta" onkeypress="myFunction(event)"></textarea>
<p id="demo"></p>
<script>
function myFunction(event) {
var x = event.keyCode;
var res;
if(x==13){
res="&ltp&gt" + document.getElementById("texta").value +"&lt/p&gt";
document.getElementById("demo").innerHTML = res;
}
}
</script>
</body>
</html>
Hope it will help.

Just out of curiosity, are you trying to get new line to save to your database?
If so and you using php. You could just do
$a=nl2br($_POST('text-area-first'));
That will save the <br> tag in your db
So every time you hit enter in your textarea it will also save the <br> tag.

Hrk! A couple of these are close, but consider that you need three different components.
Put an ID in the p tag where you want to put the text and the input which will be the source of the text. This is necessary because in the Javascript you will need to find each of them.
<p id="waitingForText"></p>
<input type="text" id="textSource"></input>
You need to have an event which will trigger the process of storing the text in the paragraph. I think Pirate has a great suggestion using the enter key. Pugazh suggested a button. I have included both here. Please note that I have added the onkeypress event to the same input tag described in step 1.
<button onclick="TextEvent()">Click</button>
<input type="text" id="textSource" onkeypress="KeyEvent(event)"></input>
The final step is the script which ties it all together. In this case we will have a function to catch the enter key (per Pirate's idea) and then unify that with the function called by the button. It is important to do this because we will only have one function with code which stores the text.
<script>
function TextEvent()
{
var destination = document.getElementById("waitingForText");
var source = document.getElementById("textSource")
destination.innerHTML = source.value;
}
function KeyEvent(event)
{
if(event.keyCode==13)//as Pirate suggests or any other char
{
TextEvent();//call the same method to move text
}
}
</script>
That's it.

Related

Regex pattern for preventing leading whitespace in HTML input

<input type="text" pattern="^[a-zA-Z1-9].*">
How can I restrict the following input element from having leading whitespace, ie, it should always start with a character except a whitespace.
This answer suggested I use pattern="^[a-zA-Z1-9].*" but it doesn't seem to work.
EDIT:
It works only if I wrap it in a form tag and a submit button. Clicking the button triggers the error. But I want to be able to restrict users from entering whitespace on the input box itself.
To achieve this without a form-tag we can use a JavaScript live input filter like this:
var noLeadingSpace = /^\w.*$/;
$("input")
.data("oldValue", "")
.bind("input propertychange", function() {
var $this = $(this);
var newValue = $this.val();
if (!noLeadingSpace.test(newValue))
return $this.val($this.data("oldValue"));
return $this.data("oldValue", newValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
It does work, but it will be validated if you try to send a form.
function myValidator(v){
var input = document.getElementById('uglyWay')
if(input){
input.value = input.value.replace(/ /g, '')
}
}
<form>
<input id="uglyWay" oninput='myValidator()' type="text" pattern="^[a-zA-Z1-9].*">
<button type="submit">Send</button>
</form>
The Following Regex mentioned in question Works without wrapping inside form tag
input[type="text"]:valid{
background:green;
}
input[type="text"]:invalid{
background:red;
}
<input type="text" pattern="^[a-zA-Z1-9].*">

How do I reset a form including removing all validation errors?

I have an Angular form. The fields are validated using the ng-pattern attribute. I also have a reset button. I'm using the Ui.Utils Event Binder to handle the reset event like so:
<form name="searchForm" id="searchForm" ui-event="{reset: 'reset(searchForm)'}" ng-submit="search()">
<div>
<label>
Area Code
<input type="tel" name="areaCode" ng-model="areaCode" ng-pattern="/^([0-9]{3})?$/">
</label>
<div ng-messages="searchForm.areaCode.$error">
<div class="error" ng-message="pattern">The area code must be three digits</div>
</div>
</div>
<div>
<label>
Phone Number
<input type="tel" name="phoneNumber" ng-model="phoneNumber" ng-pattern="/^([0-9]{7})?$/">
</label>
<div ng-messages="searchForm.phoneNumber.$error">
<div class="error" ng-message="pattern">The phone number must be seven digits</div>
</div>
</div>
<br>
<div>
<button type="reset">Reset</button>
<button type="submit" ng-disabled="searchForm.$invalid">Search</button>
</div>
</form>
As you can see, when the form is reset it calls the reset method on the $scope. Here's what the entire controller looks like:
angular.module('app').controller('mainController', function($scope) {
$scope.resetCount = 0;
$scope.reset = function(form) {
form.$setPristine();
form.$setUntouched();
$scope.resetCount++;
};
$scope.search = function() {
alert('Searching');
};
});
I'm calling form.$setPristine() and form.$setUntouched, following the advice from another question here on Stack Overflow. The only reason I added the counter was to prove that the code is being called (which it is).
The problem is that even after reseting the form, the validation messages don't go away. You can see the full code on Plunker. Here's a screenshot showing that the errors don't go away:
I started with the comment from #Brett and built upon it. I actually have multiple forms and each form has many fields (more than just the two shown). So I wanted a general solution.
I noticed that the Angular form object has a property for each control (input, select, textarea, etc) as well as some other Angular properties. Each of the Angular properties, though, begins with a dollar sign ($). So I ended up doing this (including the comment for the benefit of other programmers):
$scope.reset = function(form) {
// Each control (input, select, textarea, etc) gets added as a property of the form.
// The form has other built-in properties as well. However it's easy to filter those out,
// because the Angular team has chosen to prefix each one with a dollar sign.
// So, we just avoid those properties that begin with a dollar sign.
let controlNames = Object.keys(form).filter(key => key.indexOf('$') !== 0);
// Set each control back to undefined. This is the only way to clear validation messages.
// Calling `form.$setPristine()` won't do it (even though you wish it would).
for (let name of controlNames) {
let control = form[name];
control.$setViewValue(undefined);
}
form.$setPristine();
form.$setUntouched();
};
$scope.search = {areaCode: xxxx, phoneNumber: yyyy}
Structure all models in your form in one place like above, so you can clear it like this:
$scope.search = angular.copy({});
After that you can just call this for reset the validation:
$scope.search_form.$setPristine();
$scope.search_form.$setUntouched();
$scope.search_form.$rollbackViewValue();
There doesn't seem to be an easy way to reset the $errors in angular. The best way would probably be to reload the current page to start with a new form. Alternatively you have to remove all $error manually with this script:
form.$setPristine(true);
form.$setUntouched(true);
// iterate over all from properties
angular.forEach(form, function(ctrl, name) {
// ignore angular fields and functions
if (name.indexOf('$') != 0) {
// iterate over all $errors for each field
angular.forEach(ctrl.$error, function(value, name) {
// reset validity
ctrl.$setValidity(name, null);
});
}
});
$scope.resetCount++;
You can add a validation flag and show or hide errors according to its value with ng-if or ng-show in your HTML. The form has a $valid flag you can send to your controller.
ng-if will remove or recreate the element to the DOM, while ng-show will add it but won't show it (depending on the flag value).
EDIT: As pointed by Michael, if form is disabled, the way I pointed won't work because the form is never submitted. Updated the code accordingly.
HTML
<form name="searchForm" id="searchForm" ui-event="{reset: 'reset(searchForm)'}" ng-submit="search()">
<div>
<label>
Area Code
<input type="tel" name="areaCode" ng-model="areaCode" ng-pattern="/^([0-9]{3})?$/">
</label>
<div ng-messages="searchForm.areaCode.$error">
<div class="error" ng-message="pattern" ng-if="searchForm.areaCode.$dirty">The area code must be three digits</div>
</div>
</div>
<div>
<label>
Phone Number
<input type="tel" name="phoneNumber" ng-model="phoneNumber" ng-pattern="/^([0-9]{7})?$/">
</label>
<div ng-messages="searchForm.phoneNumber.$error">
<div class="error" ng-message="pattern" ng-if="searchForm.phoneNumber.$dirty">The phone number must be seven digits</div>
</div>
</div>
<br>
<div>
<button type="reset">Reset</button>
<button type="submit" ng-disabled="searchForm.$invalid">Search</button>
</div>
</form>
JS
$scope.search = function() {
alert('Searching');
};
$scope.reset = function(form) {
form.$setPristine();
form.$setUntouched();
$scope.resetCount++;
};
Codepen with working solution: http://codepen.io/anon/pen/zGPZoB
It looks like I got to do the right behavior at reset. Unfortunately, using the standard reset failed. I also do not include the library ui-event. So my code is a little different from yours, but it does what you need.
<form name="searchForm" id="searchForm" ng-submit="search()">
pristine = {{searchForm.$pristine}} valid ={{searchForm.$valid}}
<div>
<label>
Area Code
<input type="tel" required name="areaCode" ng-model="obj.areaCode" ng-pattern="/^([0-9]{3})?$/" ng-model-options="{ allowInvalid: true }">
</label>
<div ng-messages="searchForm.areaCode.$error">
<div class="error" ng-message="pattern">The area code must be three digits</div>
<div class="error" ng-message="required">The area code is required</div>
</div>
</div>
<div>
<label>
Phone Number
<input type="tel" required name="phoneNumber" ng-model="obj.phoneNumber" ng-pattern="/^([0-9]{7})?$/" ng-model-options="{ allowInvalid: true }">
</label>
<div ng-messages="searchForm.phoneNumber.$error">
<div class="error" ng-message="pattern">The phone number must be seven digits</div>
<div class="error" ng-message="required">The phone number is required</div>
</div>
</div>
<br>
<div>
<button ng-click="reset(searchForm)" type="reset">Reset</button>
<button type="submit" ng-disabled="searchForm.$invalid">Search</button>
</div>
</form>
And JS:
$scope.resetCount = 0;
$scope.obj = {};
$scope.reset = function(form_) {
$scope.resetCount++;
$scope.obj = {};
form_.$setPristine();
form_.$setUntouched();
console.log($scope.resetCount);
};
$scope.search = function() {
alert('Searching');
};
Live example on jsfiddle.
Note the directive ng-model-options="{allowinvalid: true}". Use it necessarily, or until the entry field will not be valid, the model value is not recorded. Therefore, the reset will not operate.
P.S. Put value (areaCode, phoneNumber) on the object simplifies purification.
Following worked for me
let form = this.$scope.myForm;
let controlNames = Object.keys(form).filter(key => key.indexOf('$') !== 0);
for (let name of controlNames) {
let control = form [name];
control.$error = {};
}
In Short: to get rid of ng-messages errors you need to clear out the $error object for each form item.
further to #battmanz 's answer, but without using any ES6 syntax to support older browsers.
$scope.resetForm = function (form) {
try {
var controlNames = Object.keys(form).filter(function (key) { return key.indexOf('$') !== 0 });
console.log(controlNames);
for (var x = 0; x < controlNames.length; x++) {
form[controlNames[x]].$setViewValue(undefined);
}
form.$setPristine();
form.$setUntouched();
} catch (e) {
console.log('Error in Reset');
console.log(e);
}
};
I had the same problem and tried to do battmanz solution (accepted answer).
I'm pretty sure his answer is really good, but however for me it wasn't working.
I am using ng-model to bind data, and angular material library for the inputs and ng-message directives for error message , so maybe what I will say will be useful only for people using the same configuration.
I took a lot of look at the formController object in javascript, in fact there is a lot of $ angular function as battmanz noted, and there is in addition, your fields names, which are object with some functions in its fields.
So what is clearing your form ?
Usually I see a form as a json object, and all the fields are binded to a key of this json object.
//lets call here this json vm.form
vm.form = {};
//you should have something as ng-model = "vm.form.name" in your view
So at first to clear the form I just did callback of submiting form :
vm.form = {};
And as explained in this question, ng-messages won't disappear with that, that's really bad.
When I used battmanz solution as he wrote it, the messages didn't appear anymore, but the fields were not empty anymore after submiting, even if I wrote
vm.form = {};
And I found out it was normal, because using his solution actually remove the model binding from the form, because it sets all the fields to undefined.
So the text was still in the view because somehow there wan't any binding anymore and it decided to stay in the HTML.
So what did I do ?
Actually I just clear the field (setting the binding to {}), and used just
form.$setPristine();
form.$setUntouched();
Actually it seems logical, since the binding is still here, the values in the form are now empty, and angular ng-messages directive is triggering only if the form is not untouched, so I think it's normal after all.
Final (very simple) code is that :
function reset(form) {
form.$setPristine();
form.$setUntouched();
};
A big problem I encountered with that :
Only once, the callback seems to have fucked up somewhere, and somehow the fields weren't empty (it was like I didn't click on the submit button).
When I clicked again, the date sent was empty. That even more weird because my submit button is supposed to be disabled when a required field is not filled with the good pattern, and empty is certainly not a good one.
I don't know if my way of doing is the best or even correct, if you have any critic/suggestion or any though about the problem I encountered, please let me know, I always love to step up in angularJS.
Hope this will help someone and sorry for the bad english.
You can pass your loginForm object into the function ng-click="userCtrl.login(loginForm)
and in the function call
this.login = function (loginForm){
loginForm.$setPristine();
loginForm.$setUntouched();
}
So none of the answers were completely working for me. Esp, clearing the view value, so I combined all the answers clearing view value, clearing errors and clearing the selection with j query(provided the fields are input and name same as model name)
var modelNames = Object.keys($scope.form).filter(key => key.indexOf('$') !== 0);
modelNames.forEach(function(name){
var model = $scope.form[name];
model.$setViewValue(undefined);
jq('input[name='+name+']').val('');
angular.forEach(model.$error, function(value, name) {
// reset validity
model.$setValidity(name, null);
});
});
$scope.form.$setPristine();
$scope.form.$setUntouched();

Form upper case input

I have a form where users enter a surname. In case if they type it in all small case letters i want it to show up properly E.g. the user types in the word 'smith' but the response page will show 'Smith' instead?
<p>Name: <input type="text" name="surname"></p>
All you need to do is capitalize your input, look snippet below:
P.S. - I edited your p class so you don't get confused when you apply the style to input. Because it could affect every input you may have in your site if was applied to input itself.
.surname input {
text-transform: capitalize
}
<p class="surname">Name:
<input type="text" name="surname">
</p>
EDIT: here is jQuery solution, that will solve your problem with response page.
jQuery.fn.capitalize = function() {
$(this[0]).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.replace(/^(.)|(\s|\-)(.)/g, function($1) {
return $1.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
}
$('.surname input').capitalize();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p class="surname">Name:
<input type="text" name="surname">
</p>
You could check the input value in the browser using Javascript and modify the value if the first character is not upper case. I'd recommend JQuery for that. Or use CSS to capitalize it.
Also note that browser-side Javascript or CSS transformations don't guarantee that a POST of your form will only send capitalized input; whatever happens in the browser can be bypassed. Hence, server-side you will want to do the same (capitalize if necessary).
Speaking of surnames, would you capitalize "van der Vaart"?
CSS:
text-transform: capitalize;
<p>Name: <input type="text" style="text-transform: capitalize;" name="surname"></p>

Dynamically change the font size of an input text box to fill the dimensions

I'd like to change the font size into an <input type="text" size="10> dynamically to fill the box. Here are some examples:
With less chars:
With more chars:
Is it possible?
I know JQuery and JavaScript weren't mentioned or tagged, but what you want will need JavaScript, and the JQuery.InputFit plugin will do exactly what you want:
<input type="text" name="younameit" id="input">
<script type="text/javascript">
$('input').inputfit();
</script>
I'm a little late to this question, but I want offer a solution in case you don't want to implement jquery just for this:
<p>A function is triggered when the user releases a key in the input field. The function transforms the characters size.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction()">
function myFunction(){
var x=document.getElementById("fname");
var initialSize=25-x.value.length;
initialSize=initialSize<=10?10:initialSize;
x.style.fontSize = initialSize + "px";
}
check out this jsfiddle

Can div with contenteditable=true be passed through form?

Can <div contenteditable="true">Some Text</div> be used instead of texarea and then passed trough form somehow?
Ideally without JS
Using HTML5, how do I use contenteditable fields in a form submission?
Content Editable does not work as a form element. Only javascript can allow it to work.
EDIT: In response to your comment... This should work.
<script>
function getContent(){
document.getElementById("my-textarea").value = document.getElementById("my-content").innerHTML;
}
</script>
<div id="my-content" contenteditable="true">Some Text</div>
<form action="some-page.php" onsubmit="return getContent()">
<textarea id="my-textarea" style="display:none"></textarea>
<input type="submit" />
</form>
I have tested and verified that this does work in FF and IE9.
You could better use:
<script>
function getContent(){
document.getElementById("my-textarea").value = document.getElementById("my-content").innerText;
}
</script>
NOTE: I changed innerHTML to innerText. This way you don't get HTML elements and text but only text.
Example: I submited "text", innerHTML gives the value: "\r\n text". It filters out "text" but it's longer then 4 characters.
innerText gives the value "text".
This is useful if you want to count the characters.
Try out this
document.getElementById('formtextarea').value=document.getElementById('editable_div').innerHTML;
a full example:-
<script>
function getContent() {
var div_val = document.getElementById("editablediv").innerHTML;
document.getElementById("formtextarea").value = div_val;
if (div_val == '') {
//alert("option alert or show error message")
return false;
//empty form will not be submitted. You can also alert this message like this.
}
}
</script>
`
<div id="editablediv" contenteditable="true">
Some Text</div>
<form id="form" action="action.php" onsubmit="return getContent()">
<textarea id="formtextarea" style="display:none"></textarea>
<input type="submit" />
</form>
`
Instead of this, you can use JQuery (if there is boundation to use JQuery for auto-resizing textarea or any WYSIWYG text editor)
Without JS it doesn't seem possible unfortunately.
If anyone is interested I patched up a solution with VueJS for a similar problem. In my case I have:
<h2 #focusout="updateMainMessage" v-html="mainMessage" contenteditable="true"></h2>
<textarea class="d-none" name="gift[main_message]" :value="mainMessage"></textarea>
In "data" you can set a default value for mainMessage, and in methods I have:
methods: {
updateMainMessage: function(e) {
this.mainMessage = e.target.innerText;
}
}
"d-none" is a Boostrap 4 class for display none.
Simple as that, and then you can get the value of the contenteditable field inside "gift[main_message]" during a normal form submit for example. I'm not interested in formatting, therefore "innerText" works better than "innerHTML" for me.