how to make textarea required - javascript

Pretty self-explanatory, I have a textarea and it's set to required, but it only prompts user if you actually click in the text area, if you submit without clicking inside the text area it will not prompt the alert.
Fiddle
<p class="textHeader">
<strong>
Which type of elements would you be in favor of for a future
pattern for interactive media to follow?
</strong>
<textarea
name="styled-textarea"
id="styled"
onfocus="this.value=''; setbg('#e5fff3');"
oninvalid="invalidComment(this);"
onblur="setbg('white')"
placeholder="Max characters 140"
maxlength="140"
required
>
</textarea>
</p>

Easy answer. You are already providing contents for textarea, some white space with how your existing HTML is laid out. Therefore a value has been provided. Make sure your textarea closing tag is right next to the opening tag, without any spaces, so there is no white space content in-between. Like this:
<p class="textHeader">
<strong>
Which type of elements would you be in favor of for a future
pattern for interactive media to follow?
</strong>
<textarea
name="styled-textarea"
id="styled"
onfocus="this.value=''; setbg('#e5fff3');"
oninvalid="invalidComment(this);"
onblur="setbg('white')"
placeholder="Max characters 140"
maxlength="140"
required
></textarea>

You can use a js library like abide
http://www.siegeengine.org/documentation/abide-html5-validation.html
Or if you prefere
<script type="text/javascript">
// without jQuery style
var bindEvents = function(event){
if( document.getElementById('styled').value.trim() === '' ){
event.preventDefault();
alert("Write something please");
}
};
window.onload = function(){
document.forms[0].addEventListener('submit', bindEvents, true);
};
// jQuery style
var bindEvents = function(){
$('form').on('submit', function(e){
if( $(this).val().trim() === '' ){
e.preventDefault();
alert("Write something please");
}
});
};
$(document).ready( bindEvents );
// i would not recommend this but it will work also
var initForm = function(){
document.getElementById('styled').focus();
document.getElementById('styled').blur();
}
window.onload = initForm;
</script>

Related

typed.js how to make text editable?

I want to make the text as on the home page https://laracasts.com/
use for this library
https://mattboldt.com/demos/typed-js/
Question
How do I make when I click on text the animation stops and I can write my text
here is my code
<h1>
<span class="header-title-accent" id="typed" contenteditable="true" spellcheck="false" > Front-end Developer</span>
</h1>
<script>
$('document').ready(function(){
var typed = new Typed('#typed', {
strings: ['First ^1000 sentence.', 'Second sentence.'],
backSpeed:50,
typeSpeed:60,
cursorChar: '|||',
});
});
</script>
You could create 2 listeners on the input field to start() & stop() the Typed instance on blur & focus respectively. See the docs for more info: https://mattboldt.github.io/typed.js/docs/#typed
Example:
$('#typed').on('focus', function(e) {
typed.stop();
});
// You may not need/want this one...
$('#typed').on('blur', function(e) {
typed.start();
});
Codepen

how do I modify an element with text received from input, and how do I stop the disable input if a character terminator is used?

I'm learning jQuery and having trouble figuring something out.
What I need to do is display an alert or note (I used h3) to a user to input their name followed by # (the character terminator). Anything the user types prior to the # symbol should change the text of a span element with id userName, in the heading. After the # is typed no other text should able to be typed. I wanted to have to ghost writer effect of the user typing out their naming in the header, but I couldn't figure that out so I put an input field in. I'm trying to use the if statement to append the keyspressed to the id, or otherwise stop the text from being input.
This is what I have:
$(document).ready(function() {
$('input').on(function() {
$('input').keypress(function(evt) {
var keyPressed=String.fromCharCode(evt.which);
if (keyPressed !== '#')
{
$("userNameInput").append('userName');
}
else {
return false;
}
});
});
});
html:
<header>
<h1>Lab 6</h1>
<h2>Welcome, <span id="userName">User!</span></h2>
<h3>Please enter your name followed by # i.e. John#</h3>
<input id="userNameInput" type="text">
</header>
You had a bunch of issues... I think this is what you were going for though:
JSFiddle
HTML:
<h1>Lab 6</h1>
<h2>Welcome, <span id="userName">User</span>!</h2>
<h3>Please enter your name followed by # i.e. John#</h3>
<input id="userNameInput" type="text">
JS:
$(document).ready(function() {
var appendName = function(evt) {
var keyPressed = String.fromCharCode(evt.which);
if (keyPressed !== '#') {
$("#userName").text(this.value + keyPressed);
} else {
$(this).off();
}
};
$('#userNameInput').on("keypress", appendName);
});
You could also just disable the input field instead of turning off the listener if you wanted... just change $(this).off(); to $(this).prop("disabled",true);
Some problems that I noted in your code were... it looks like you were trying to just do a keypress event, but you had that nested in an on, and the on had no event type. This didn't really make sense but I assume you just wanted the keypress event listener.
This chunk here $("userNameInput").append('userName'); was saying to look for an <userNameInput> and append the string userName to it.
You ignored # but did nothing to stop any new input afterwards.

Disabling a textbox when the other textbox have a value HTML

im sorry for this question but how can i disable a textbox if another textbox have a value??
I already try this code but its not working,, sorry for the noob question T_T
function disable(downpayment,full_payment)
{
if ( downpayment.value.length >= 1 )
document.getElementById(full_payment).disabled = true;
else
document.getElementById(full_payment).disabled = false;
}
</script>
<input name="downpayment" id="downpayment" type="text" onselect="function disable(downpayment,full_payment);" style="width:250px" />
</p>
<p>
<input name="full_payment" id="full_payment" type="text" style="width:250px" />
If you want to stay with plain JavaScript:
// finding the relevant elements *outside* the function
var downpayment = document.getElementById('downpayment'),
full_payment = document.getElementById('full_payment');
function enableToggle(current, other) {
/* 'current' is the element that currently has focus
'other' is the other input element, that does not have focus.
1. if the 'current' value of the focused/active element, once the whitespace
is removed, is greater than 0 (so it has something in it other than whitespace,
the disabled property of the 'other' element is true,
2. if the 'current' element has only whitespace, and/or a zero-length value,
the 'other' element's disabled property is false.
*/
other.disabled = current.value.replace(/\s+/,'').length > 0;
}
// using the onkeyup event to call a function on the elements.
downpayment.onkeyup = function () {
enableToggle(this, full_payment);
}
full_payment.onkeyup = function () {
enableToggle(this, downpayment);
}
This works with the following HTML:
<input name="downpayment" id="downpayment" type="text" style="width:250px" />
<input name="full_payment" id="full_payment" type="text" style="width:250px" />
JS Fiddle demo.
If you're using jQuery already, then you can either nest the above into jQuery's $(document).ready(function(){ /* the code in here */});, or switch to a jQuery-only solution, such as Alex's.
To stick with plain-JavaScript, and avoiding explaining how to set up an equivalent DOM-ready event, put the following at the end of your HTML content, just before the closing </body> tag:
<script>
var downpayment = document.getElementById('downpayment'),
full_payment = document.getElementById('full_payment');
function enableToggle(current, other) {
other.disabled = current.value.replace(/\s+/,'').length > 0;
}
downpayment.onkeyup = function () {
enableToggle(this, full_payment);
}
full_payment.onkeyup = function () {
enableToggle(this, downpayment);
}
</script>
(This is exactly the same JavaScript as above, with the comments stripped out, but wrapped in <script></script> tags)
Putting this at the bottom of the HTML means that the elements exist in the DOM prior to your trying to assign event-handlers to them.
Incidentally, with adjusted HTML, to give:
<form>
<!--
I associated the relevant elements with a class-name 'enableToggle',
you don't have to, it just reduces the work the jQuery has to do later
when using siblings('.enableToggle') to find the relevant elements.
-->
<div>
<label for="downpayment">Downpayment</label>
<input name="downpayment" class="enableToggle" id="downpayment" type="text" style="width:250px" />
<label for="full_payment">Full payment</label>
<input name="full_payment" class="enableToggle" id="full_payment" type="text" style="width:250px" />
</div>
</form>
The following jQuery could be used:
// binds both event-handler to both 'keyup' and 'paste' events.
$('.enableToggle').on('keyup paste', function(){
/* 'curVal' is a Boolean (true or false) depending on whether there's
a value other than whitespace */
var curVal = $(this).val().replace(/\s+/g,'').length > 0;
/* sets the 'disabled' property of the sibling elements of the current
element, as long as those siblings have the class 'enableToggle'
(this avoids having to explicitly identify all the elements you want
to act on). */
$(this).siblings('.enableToggle').prop('disabled', curVal);
});
JS Fiddle demo.
You have tagged the question jQuery, so it's as simple as...
$("#downpayment").on("change paste", function() {
$("#full_payment").prop("disabled", this.value.length);
});
As soon as your down payment has some content in it (even if it's a space, if that's not ideal, $.trim() the input before you check its length property) then it will enable the full payment.
$(document).ready(function()
{
$(".PaxHeads").on('keypress','input[name="DebitAmount"]',function()
{
var myLength = $('input[name="DebitAmount"]').val().length;
if (myLength!=0)
{
$('input[name="CreditAmount"]').attr("disabled", "disabled");
}
else
{
$('input[name="CreditAmount"]').removeAttr("disabled");
}
});
$(".PaxHeads").on('keypress', 'input[name="CreditAmount"]', function()
{
var myLength1 = $('input[name="CreditAmount"]').val().length;
if (meLength1!=0)
{
$('input[name="DebitAmount"]').attr("disabled", "disabled");
}
else
{
$('input[name="DebitAmount"]').removeAttr("disabled");
}
});
});

How can I position a label inside its textfield?

I have many textfields that show instruction text within the textbox (how the default value would look). On focus the color of the text becomes lighter, but doesn't go away until text is entered. When text is erased, the label returns. It's pretty slick. A default value doesn't cut it, because these go away onfocus.
I have it working, but the code is complicated because it relies on negative margins that correspond to the individual widths of the textfields. I want a dynamic solution where the label for its textfield is positioned correctly automatically, probably using a script.
Any help would be greatly appreciated. But I am not looking for default values as a solution.
Thanks.
Mike
Edited to be more precise.
Edited again to provide some simple code that illustrates the effect I am after:
<input style="position: relative; width: 150px; font-size: 10px; font-family: Verdana, sans-serif; " type="text" name="name" id="name"
onfocus="javascript: document.getElementById('nameLabel').style.color='#BEBEBE';"
onkeypress="javascript: if (event.keyCode!=9) {document.getElementById('nameLabel').innerHTML=' ';}"
onkeyup="javascript: if (this.value=='') document.getElementById('nameLabel').innerHTML='Your Name';"
onblur="javascript: if (this.value=='') {document.getElementById('nameLabel').style.color='#7e7e7e'; document.getElementById('nameLabel').innerHTML='Your Name';}"/>
<label id="nameLabel" for="name" style="position: relative; margin-left: -150px; font-size: 10px; font-family: Verdana, sans-serif;">Your Name</label>
I would have taken a different approach (It's not entirely my idea, but i can't find the source for credit):
1st - Use html5 "placeholder" property.
2nd - Use Modernizr.js to detect support of placeholders in the browser and a simple jQuery script to add support to browsers that doesn't support it.
So, the html will look something like that:
<input type="text" class="placeholder" placeholder="Help Text" />
<textarea class="placeholder" placeholder="Another help text"></textarea>
The css:
.placeholder{color:#ccc;}
And the javascript:
/* Set placeholder for browsers that don't support HTML5 <input placeholder='text'>
* Depends on Modernizr v1.5
*/
if (!Modernizr.input.placeholder){
$('input[placeholder], textarea[placeholder]')
.focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
})
.blur(function() {
var input = $(this);
if (input.val() == '') {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
})
//Run once on load
.blur();
// Clear all 'placeholders' on submit
$('input[placeholder], textarea[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
});
}
What you are asking here is probably what is called textbox watermark.
For this, you usually don't use a label (control) inside a textfield. Instead you replace the content of the textfield when the real content of the text field is empty with some text using certain CSS property and then remove it once you blur out (w/ additional check to see if the text inside the textbox itself is the same as the watermark text. If it is, blank the field again.)
Try this. It's pretty simple implementation of this using jquery and css.
Here's one that I borrowed from somewhere:
$(function() {
// Give the textbox a watermark
swapValues = [];
$('.your_input_class').each(function(i){
$(this).val("Please enter xyz");
swapValues[i] = $(this).val();
$(this).focus(function(){
if ($(this).val() == swapValues[i]) {
$(this).val("").css("color", "#333");
}
}).blur(function(){
if ($.trim($(this).val()) == "") {
$(this).val(swapValues[i]).css("color", "#ccc");
}
});
});
});
And then for your input box:
<input class="your_input_class" type="text" value="" />
It remembers the value that is stored in it when the page loads (well, I'm setting mine directly in the JS) and it also changes the color when it's focused/not focused.
Do you mean like this? But instead of 'required' it would have the label?
I used a jQuery solution where I set the value of the input to 'required'. The input has a class of gray so the default text is lighter.
Edit after comment
Instead of using focus, you can change the input values on keydown and keyup.
$('.required_input').keydown(function()
{
if (this.value == 'required')
{
$(this).val('').removeClass('gray');
}
} );
$('.required_input').keyup(function()
{
if (this.value == '')
{
$(this).val('required').addClass('gray');
}
} );
$('.required_input').blur(function()
{
if (this.value == '')
{
$(this).val('required').addClass('gray');
}
} );
<script type="text/javascript">
window.onload = function(){
inputs = document.getElementsByTagName("input");
for(i = 0; i < inputs.length;i++){
var feild = inputs[i];
if(feild.type == "text"){
var label = document.getElementById(feild.id + "Label");
label.style.left = "-" + feild.clientWidth;
}
}
}
</script>
This bit of script should do what you wanted

Default text on input

How to set blank default text on input field and clear it when element is active.
In modern browsers, you may set the placeholder attribute on a field to set its default text.
<input type="text" placeholder="Type some text" id="myField" />
However, in older browsers, you may use JavaScript to capture the focus and blur events:
var addEvent = function(elem, type, fn) { // Simple utility for cross-browser event handling
if (elem.addEventListener) elem.addEventListener(type, fn, false);
else if (elem.attachEvent) elem.attachEvent('on' + type, fn);
},
textField = document.getElementById('myField'),
placeholder = 'Type some text'; // The placeholder text
addEvent(textField, 'focus', function() {
if (this.value === placeholder) this.value = '';
});
addEvent(textField, 'blur', function() {
if (this.value === '') this.value = placeholder;
});
Demo: http://jsbin.com/utecu
Using the onFocus and onBlur events allows you to achieve this, I.e.:
onfocus="if(this.value=='EGTEXT')this.value=''"
and
onblur="if(this.value=='')this.value='EGTEXT'"
The full example is as follows:
<input name="example" type="text" id="example" size="50" value="EGTEXT" onfocus="if(this.value=='EGTEXT')this.value=''" onblur="if(this.value=='')this.value='EGTEXT'" />
Or simply
<input name="example" type="text" id="example" value="Something" onfocus="value=''" />
This will not post back the default text once the box is cleared but also will allow the user to clear the box and see all results in the case of an autocomplete script.
Declare styles for inactive and active states:
.active {
color: black;
}
.inactive {
color: #909090;
}
Add the Javascript to handle the changing of state:
function toggleText(el)
{
var v = el.value;
//Remove text to allow editing
if(v=="Default text") {
el.value = "";
el.className = "active";
}
else {
//Remove whitespace
if(v.indexOf(" ")!=-1) {
split = v.split(" ").join("");
v = split;
}
//Change to inactive state
if(v=="") {
el.value = "Default text";
el.className = "inactive";
}
}
}
Add your input box, with the default value set, the inactive class set and Javascript handlers pointing to the toggleText() function (you could use event listeners to do this if you wish)
<input type="text" value="Default text" class="inactive" onFocus="toggleText(this);" onBlur="toggleText(this);">
From a usability point of view the text in the input component should be preserved only for user's input purposes. The possible default value in the input should be valid if left untouched by the user.
If the placeholder text is meant to be a hint for how to fill the input, it is better to be blaced near the input where it can be seen also when the input has been filled. Moreover, using a placeholder text inside text components can cause troubles e.g. with braille devices.
If a placeholder text is used, regardless of usability guidelines, one should make sure that it is done in an unobtrusive way so that it works with user agents without javascript or when js is turned off.
I have found jQuery plugin (http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/) and use it :)
What I did is put a placeholder attribute for modern browsers:
<input id='search' placeholder='Search' />
Then, I made a fallback for older browsers using JQuery:
var placeholder = $('search').attr('placeholder');
//Set the value
$('search').val(placeholder);
//On focus (when user clicks into the input)
$('search').focus(function() {
if ($(this).val() == placeholder)
$(this).val('');
});
//If they focus out of the box (tab or click out)
$('search').blur(function() {
if ($(this).val() == '')
$(this).val(placeholder);
});
This works for me.
You can use this plugin (I'm an co-author)
https://github.com/tanin47/jquery.default_text
It clones an input field and put it there.
It works on IE, Firefox, Chrome and even iPhone Safari, which has the famous focus problem.
This way you do not have to be worried about clearing input field before submitting.
OR
If you want to HTML5 only, you can just use attribute "placeholder" on input field
You can use placeholder attribute.
np. <input type="text" name="fname" placeholder="First name">
check http://www.w3schools.com/tags/att_input_placeholder.asp

Categories

Resources