Stylesheet for .html document not imported - google-apps-script

I have this form I created in HTML (called form.html) written in google apps script and I also have a stylesheet (CSS) to go with that. All is working well when I have the CSS in the same HTML-file as the form. However if I want to put my stylesheet in a separate HTML-file (called Stylesheet.html) and then include it in the form.html by using a scriplet
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
or even creating an 'include' function:
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.getContent();
}
and then in form.html
<?!= include(Stylesheet) ?>
..it doesn't seem to work. What's even worse the scriplet shows up on the form.
Maybe there is something basic I am overlooking, but I can't wrap my head around this. Any ideas ?
Here is the code so far...
function doGet() {
return HtmlService.createHtmlOutputFromFile('Formulier')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.getContent();
}
function materiaalLijst(afdnum) {
return SpreadsheetApp.openById('1l6MKG61GHMFSZrOg04W4KChpb7oZBU9VKp42FPXmldc')
.getSheetByName('RESERVATIE')
.getDataRange()
.getValues()
.map(function (v) {
return v[Number(afdnum) - 1]
})
.splice(1);
}
//work in progress
function processForm(form) {
Logger (form); //array containing form elements
}
<style>
form {
/* Just to center the form on the page */
margin: 0 auto;
width: 400px;
/* To see the outline of the form */
padding: 1em;
border: 1px solid #CCC;
border-radius: 1em;
}
form div + div {
margin-top: 1em;
}
label {
/* To make sure that all labels have the same size and are properly aligned */
display: inline-block;
width: 90px;
text-align: right;
}
input, textarea {
/* To make sure that all text fields have the same font settings
By default, textareas have a monospace font */
font: 1em sans-serif;
/* To give the same size to all text field */
width: 300px;
-moz-box-sizing: border-box;
box-sizing: border-box;
/* To harmonize the look & feel of text field border */
border: 1px solid #999;
}
input:focus, textarea:focus {
/* To give a little highlight on active elements */
border-color: #000;
}
textarea {
/* To properly align multiline text fields with their labels */
vertical-align: top;
/* To give enough room to type some text */
height: 5em;
/* To allow users to resize any textarea vertically
It does not work on every browsers */
resize: vertical;
}
</style>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
<form id="myForm">
<!-- Text input field -->
<div>
<label for="name">Naam:</label>
<input type="text" id="name" placeholder="Voornaam + naam" required>
</div>
<div>
<label for="mail">E-mail:</label>
<input type="email" id="mail" required>
</div>
<div>
<label for="Afdeling">Afdeling:</label>
<input type="radio" id="1" name="Afd" value="Oostende">Oostende
<input type="radio" id="2" name="Afd" value="Brugge">Brugge
<input type="radio" id="3" name="Afd" value="Westhoek">Westhoek
</div>
<div>
<label for="datepicker">Datum:</label>
<input type="date" id="resdatum" required>
</div>
<div>
<label for="timepicker">Uur:</label>
<input type="time" id="restijd" required>
</div>
<div>
<label for="Frequentie">Frequentie:</label>
<input type="radio" name="freq" value="éénmalig" required>éénmalig
<input type="radio" name="freq" value="meermaals">voor meerdere weken
</div>
<div>
<label for="Materiaal">Materiaal:</label>
<select id="materiaal" name="materiaalselectie" required>
<option value="notSel">Kies..</option>
</select>
</div>
<div>
<!-- The submit button. It calls the server side function uploadfiles() on click -->
<input type="submit" id="verzenden" name="verzenden" class="verzenden" value="Reservatie verzenden" >
</div>
<div id="output"></div>
</form>
<div id="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("input:radio[name=Afd]").click(function() {
go(this.id);
});
function go(idAfd) {
google.script.run.withSuccessHandler(showList).materiaalLijst(idAfd);
}
function showList(things) {
var list = $('#materiaal');
list.empty();
for (var i = 0; i < things.length; i++) {
list.append('<option value="' + things[i] + '">' + things[i] + '</option>');
}
}
//below is work in progress...
$('#myForm').submit(function(e) {
e.preventDefault();
var arr =[];
//var fields = $( ":input" ).serializeArray();
$.each( $( ":input" ).serializeArray(), function( i, field ) {
arr.push( field.value);
});
var json = JSON.stringify($('#myForm').serializeArray());
google.script.run.processForm(arr);
alert(arr);
})
</script>
The result with CSS IN the form.html
and here is the CSS in a separate .html file and included
in form.html with
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>

You're doing this right:
Your css file must be an HTML file, as those are the only type supported by HtmlService. If you look at the starter scripts, you'll find that they have Stylesheet.html, with content:
<!-- This CSS package applies Google styling; it should always be included. -->
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<style>
...
</style>
You know the google css is working if your sidebar or dialog looks pretty much like google stuff - same font, same text size. To have an action button be blue, you need to add the appropriate class to it, class="action".
Why isn't yours working?
Get ready for a face-palm moment...
You're using scriptlets, part of the Html Service templated HTML. They require interpretation, which is not done by HtmlService.createHtmlOutputFromFile(). (That's why you see the scriptlet line literally.)
Instead, you need to read the file containing scriptlets as a template, and then .evaluate() it.
function doGet() {
return HtmlService.createTemplateFromFile('form')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
To display the google-themed action button, include the Apps Script CSS and add "action" class:
<input type="submit" id="verzenden" name="verzenden" class="action verzenden" value="Reservatie verzenden" >

How about to name it Stylesheet.css?
And try to include it via normal HTML in the header.
<link rel="stylesheet" href="Stylesheet.css" type="text/css">
HTH

Related

html page not showing (only in debuging tho)

I need to display a specific html output following a condition on a variable ("tvs" a boolean).
I created the 2 html files in another spreadsheet and tested them OK.
Then I copy&pasted the samples in my much bigger spreadsheet and it doesn't work. Well, it works when i debug each 'show' functions but not in the execution of the spreadsheet.
My script goal is to detect change in a column (process info near the change occurred), then launch modal dialogs from html files (2 possible files).
GS code:
function onEdit(e) {
var celluleRef = e.range.getA1Notation()
GLOBALVAR.setProperty('CELLREF', celluleRef);
var cas = DetectCas(celluleRef) // do stuff, return cas = 0 or 1 or 2.
if (cas == 0) {
return
}
var tvs = SiTvs(celluleRef) // do stuff, return tvs as boolean.
tvs ? showPageTvs() : showPageVide();
}
function showPageTvs() {
//SpreadsheetApp.getUi().alert("cas : page tvs") //THIS SHOWS when called
var ui = SpreadsheetApp.getUi();
var htmlTvs = HtmlService.createTemplateFromFile('PageTvs')
.evaluate()
.setHeight(600);
ui.showModalDialog(htmlTvs, 'Confirmation');
}
function showPageVide() {
// SpreadsheetApp.getUi().alert("cas : page vide") //THIS SHOWS when called
var htmlVide = HtmlService.createHtmlOutputFromFile('PageVide')
.setWidth(400);
SpreadsheetApp.getUi()
.showModalDialog(htmlVide, 'Confirmation');
}
Then the html files :
PageVide.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
body{
font-size:25px;
}
input.largerCheckbox {
width: 20px;
height: 20px;
}
</style>
</head>
<body>
Gamme vide, quelle est votre action ?<br><br>
<form id="myForm" onsubmit="google.script.run.processForm(this)">
<div>
<input class="largerCheckbox" type="checkbox" id="ConfP" name="ConfP">
<label for="ConfP">Confirmation totale Prod</label>
</div>
<div>
<input class="largerCheckbox" type="checkbox" id="ConfQ" name="ConfQ">
<label for="ConfQ">Confirmation totale Qls</label>
</div>
<div>
<br>
<input class="largerCheckbox" type="checkbox" id="Tvs" name="Tvs">
<label for="Tvs">TVS :</label>
</div>
<input style="font-size:25px" type="text" name="TvsText"><br><br>
<input style="font-size:25px; float: left" type="submit" value="Submit">
</form>
<input style="font-size:25px; float: right" type="button" value="Annuler" onclick="google.script.host.close()" />
</body>
</html>
PageTvs.html :
I add that function "decoupe" just add some checkboxes.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
body{
font-size:25px;
}
input.largerCheckbox {
width: 20px;
height: 20px;
}
p {
text-indent: 10%;
}
fieldset {
input[type=checkbox] {
text-indent: 20%;
}
}
</style>
</head>
<body>
Gamme en TVS, quelle est votre action ?<br><br>
<form id="myForm" onsubmit="google.script.run.processForm(this)">
<div>
<input type="checkbox" class="largerCheckbox" id="ConfP" name="ConfP">
<label for="ConfP">Confirmation totale Prod</label>
</div>
<div>
<input type="checkbox" class="largerCheckbox" id="ConfQ" name="ConfQ">
<label for="ConfQ">Confirmation totale QLS</label>
</div>
<p>Confirmation partielle :
<fieldset>
<?!= decoupe() ?>
</p>
</fieldset>
<br>
<input style="font-size:25px; float: left" type="submit" value="Valider">
</form>
<input style="font-size:25px; float: right" type="button" value="Annuler" onclick="google.script.host.close()" />
</body>
</html>
I need to understand why html doesn't show (except in debug) and if anything hurt your eyes, tell me !
I think the problem is that you do not have permission to call Ui.showModalDialog() because onedit is a simple trigger.
The following works on an installable trigger but not on a simple trigger:
function showMyTestDialog1() {
SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutputFromFile('ah1'), 'Test1');
}
function showMyTestDialog2() {
SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutputFromFile('ah1'), 'Test2');
}
function onMyEdit(e) {
e.source.toast('entry');
const a1 = e.range.getA1Notation();
const sh = e.range.getSheet();
if (sh.getName() == 'Sheet2' && e.range.columnStart == 1 && e.range.rowStart > 1) {
e.source.toast('cond')
let v = e.range.rowStart % 3 == 0;
v ? showMyTestDialog1() : showMyTestDialog2();
}
}
If you had checked your execution log you would have seen an error like this:
Exception: You do not have permission to call Ui.showModalDialog. Required permissions: https://www.googleapis.com/auth/script.container.ui
at showMyTestDialog2(ag1:5:26)
at onEdit(ag1:16:31)
I found something wrong with your style in PageTvs.html
<style>
body{
font-size:25px;
}
input.largerCheckbox {
width: 20px;
height: 20px;
}
p {
text-indent: 10%;
}
fieldset {
input[type=checkbox] {
text-indent: 20%;
}
}
</style>
You should put fieldset input[type=checkbox] next to each other.
Like this:
fieldset input[type=checkbox] {
text-indent: 20%;
}
w3schools: css selectors

How to display the html div so that after form submit the error messgae is displayed automatically

I have a form that validates whether the username and password is correct or not but it does not show the error messages unless i click on the form again.The form is inside a html div tag, I want to know how to style the div with css so that the error messages can be displayed automatically after form submit. Here is my code
<h3 class="registration-header">
Log in. </h3>
<div class="registration-box-info"><span>
Please enter username and password </span></div>
<form action="/" charset="UTF-8" method="post">
<div class="error-message alert-danger">
<span>Sorry, unrecognized username or password.Have you forgotten your password?</span>
</div>
The error message is not displayed automatically after inserting wrong input and so I would be grateful if you can tell me how to style the div using css to make it visible after submitting wrong input
If you want to do it without js, you could use
:valid
:invalid
CSS pseudo class and style the border of the input accordingly.
You could also attach a pattern to the validation.
Check: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
For checking wheather username and other filed are empty or not, you have to just add required inside the tag like <input type="text" name="full-name" id="full-name" placeholder="Name" required /> An for validation visit https://www.w3schools.com/js/js_validation.asp
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: #eee;
font-family: 'helvetica neue', helvetica, arial, sans-serif;
color: #222;
}
#form {
max-width: 700px;
padding: 2rem;
box-sizing: border-box;
}
.form-field {
display: flex;
flex-wrap: wrap;
margin: 0 0 1rem 0;
}
label, input {
width: 70%;
padding: 0.5rem;
box-sizing: border-box;
justify-content: space-between;
font-size: 1.1rem;
}
label {
text-align: right;
width: 30%;
}
input {
border: 2px solid #aaa;
border-radius: 2px;
}
.error-message {
flex: 0 0 100%;
margin-left: 30%;
color: red;
}
<form method="post" action="/" id="form" class="validate">
<div class="form-field">
<label for="full-name">Full Name</label>
<input type="text" name="full-name" id="full-name" placeholder="Name" required />
</div>
<div class="form-field">
<label for="email-input">Email</label>
<input type="email" name="email-input" id="email-input" placeholder="test#gmail.com" required />
</div>
<div class="form-field">
<label for="password-input">Password</label>
<input type="password" name="password-input" id="password-input" required />
</div>
<div class="form-field">
<label for=""></label>
<input type="submit" value="Sign Up" />
</div>
</form>
If you can use jquery, and if you want customise your kind of error,
like, if you enter, 'map', derive' or 'glossary, you have different message.
If you enter '???' or anything else you'll have your message 'Sorry, unrecognized...'
You can use :
<!DOCTYPE html>
<html>
<head>
<style>
#div1 {background-color: red;}
#div2 {background-color: blue;}
#div3 {background-color: black;
color: white;}
#error {background-color: red;}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<h3 class="registration-header">
Log in. </h3>
<div class="registration-box-info"><span>
Please enter username and password </span></div>
<!-- form action="/" charset="UTF-8" method="post" -->
<input type="text" placeholder="ENTER COMMAND" />
<div id="div1">div1 : you entered the log 'map'</div>
<div id="div2">div2 : you entered the log 'derive'</div>
<div id="div3">div1= : you entered the log 'glossary'</div>
<div id="error"><span>Sorry, unrecognized username or password.Have you forgotten your password?</span></div>
<script>
$(document).ready(function() {
// Hide both <div> by default
$('#div1').hide();
$('#div2').hide();
$('#div3').hide();
$('#error').hide();
// Check on keydown
$('input').keyup(function (e) {
if (e.keyCode == 13) {
var value = $(this).val();
$('#div1').hide();
$('#div2').hide();
$('#div3').hide();
$('#error').hide();
if (value == 'map') { // If input value is div1
$('#div1').slideDown();
} else if (value == 'derive') { // If input value is div2
$('#div2').slideDown();
} else if (value == 'glossary') { // If input value is div3
$('#div3').slideDown();
} else if (value != '') { // If input value is wrong
//$('#error').html(value + " is an incorrect input value");
$('#error').slideDown();
}
}
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
#div1 {background-color: red;}
#div2 {background-color: blue;}
#div3 {background-color: black;
color: white;}
#error {background-color: red;}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<h3 class="registration-header">
Log in. </h3>
<div class="registration-box-info"><span>
Please enter username and password </span></div>
<form action="submit_form.php" method="post" id="form_1" charset="UTF-8" >
<input id="submit_form" type="text" placeholder="ENTER COMMAND" />
</form>
<div id="div1">div1 : you entered the log 'map'</div>
<div id="div2">div2 : you entered the log 'derive'</div>
<div id="div3">div1= : you entered the log 'glossary'</div>
<div id="error"><span>Sorry, unrecognized username or password.Have you forgotten your password?</span></div>
<script>
$(document).ready(function() {
// Hide both <div> by default
$('#div1').hide();
$('#div2').hide();
$('#div3').hide();
$('#error').hide();
// Check on keydown
$('input').keyup(function (e) {
if (e.keyCode == 13) {
var value = $(this).val();
$('#div1').hide();
$('#div2').hide();
$('#div3').hide();
$('#error').hide();
if (value == 'map') { // If input value is div1
$('#div1').slideDown();
} else if (value == 'derive') { // If input value is div2
$('#div2').slideDown();
} else if (value == 'glossary') { // If input value is div3
$('#div3').slideDown();
} else if (value != '') { // If input value is wrong
//$('#error').html(value + " is an incorrect input value");
$('#error').slideDown();
}
}
});
});
$('#submit_form').addEventListener('click', function (event) {
// Prevents form from submitting
event.preventDefault();
$.ajax({
type: "POST",
url: "submit_form.php",
dataType: "json",
data: $('#form_1').serialize(),
success: function (json) {
$('.message_center').html('');
if(json['success']) {
$('.message_center')
.html('<div class="row">'+
' <div class="col-md-12">'+
' <div class="alert alert-success alert-dismissible">'+
' <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+
' <h4><i class="icon fa fa-check"></i> Success!</h4>'+
' '+json['success']+''+
' </div>'+
' </div>'+
' </div> ');
}
if(json['error']) {
var html='';
$.each( json['error'], function( key, value ) {
html += value+'<br>';
});
$('.message_center')
.html('<div class="row">'+
' <div class="col-md-12">'+
' <div class="alert alert-warning alert-dismissible">'+
' <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+
' <h4><i class="icon fa fa-warning"></i> Error! There was a problem.</h4>'+
' '+html+''+
' </div>'+
' </div>'+
' </div> ');
}
}
});
});
</script>
</body>
</html>

how to save input field data to text file without flushing out the textboxes

I am making a thing for setting goals,and to show your progress, I use the progress element. I would like to save my goal with php/js/other to a .txt file on my server called user.txt. I have already tried this Write server text files with Ajax and PHP write file from input to txt shows what I want, but instead of form tags, I want just 2 input fields
Is there any way I can merge these 2 files to save my data from my 2 fields to a text file(user.txt)
Here is my code:
function myFunction() {
var x = document.getElementById("myTextarea").value;
document.getElementById("myProgress").value = x;
}
function myFunction2() {
var x = document.getElementById("myTextarea2").value;
document.getElementById("myProgress").max = x;
}
progress {
color: #0063a6;
font-size: .6em;
line-height: 1.5em;
text-indent: .5em;
width: 30em;
height: 3em;
border: 1px solid #0063a6;
background: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>Goal Progress:</h3>
<progress id="myProgress" value="0" max="100">
</progress>
<hr>
<input type="text" id="myTextarea"></input>
<button onclick="myFunction()">Add</button>
<hr>
<input type="text" id="myTextarea2" />
<button onclick="myFunction2()">Set Goal</button>
<hr>
here I finally solved my perplexing paradyme:
<html>
<body onload="timer=setTimeout('myFunction2(); myFunction();',3000)">
<style>
progress {
color: #0063a6;
font-size: .6em;
line-height: 1.5em;
text-indent: .5em;
width: 30em;
height: 3em;
border: 1px solid #0063a6;
background: #fff;
}
</style>
<h3>Goal Progress:</h3>
<progress id="myProgress" value="0" max="100">
</progress>
<hr>
<form action="form.php" method="POST">
add money:
<input type ="text" name="field1" id="myTextarea"></input>
<hr>
Goal:
<input type ="text" name="field2" id="myTextarea2"/>
<input type="submit" name="submit" value="Save Data">
</form>
<hr>
<button onclick="myFunction2(); myFunction();">show new progress</button>
<script>
function myFunction() {
var x = document.getElementById("myTextarea").value;
document.getElementById("myProgress").value = x;
}
function myFunction2() {
var x = document.getElementById("myTextarea2").value;
document.getElementById("myProgress").max = x;
}
</script>
</body>
</html>

Change color of input field after the submit has failed

I would like to know if there is a way to change the color of an input field after you clicked on a submit button, like change it's color to red if the input is invalid. My current solution marks every input red at the beginning, because of my current css code.
input:invalid {
background: #FF3300;
}
I want the input fields to remain white until you hit submit button, then the correct inputs should turn green while the incorrect ones should turn red.
Thanks in advance.
Small example.
HTML:
<html><!DOCTYPE html>
<head>
<title>Example</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<form action="">
<input type="text" id="name" class="input" maxlength="50" pattern="[A-Za-z\\s]*" placeholder="Name" required>
<input type="submit" value="Submit" id="Submit">
</form>
</body>
</html>
CSS:
input:invalid {
background: #FF3300;
}
input:valid {
background: lightgreen;
}
#Submit{
background: lightgrey;
}
Try this:
<!DOCTYPE html>
<html>
<head>
<title>Say I'm a duck</title>
</head>
<body>
<script>
function verify(){
var value = document.forms[0].item.value; // or replace document.forms[0].item by document.getElementById('name')
var objective = "I'm a duck";
if(objective != value){
document.forms[0].item.style.color="#FF3300";
return false;
} else {
document.forms[0].item.style.color="lightgreen";
}
return true;
}
</script>
<form action="" method="" onSubmit="verify();">
<input type="text" name="item" id="name" class="input" maxlength="50" pattern="[A-Za-z\\s]*" placeholder="Name" required>
<input type="submit" value="Submit" id="Submit">
</form>
</body>
</html>
The onSubmit property will call the js verif() function.
In javascript, the call to DOM Object.style.property = value; will change the object style.
W3School js change css
Admin XVII
You may have incorrectly set parameters in the tag input. That is: type, required, pattern. Read more on the Internet about HTML5 form validation. CSS selector you are correct. Please note that this method works only in modern browsers supporting HTML5, in older browsers, you will have to use JS libraries to validate the form or write a small script in PHP.
What you are asking for is one of angularJS features.
But to answer your question... First of all I asume you are using ajax, or the reload won't show the input any more. If that is so, when you get an error from the call you can add an .invalid class, so instead you'd need this:
input.invalid {
background: #FF3300;
}
And on ajax error:
document.querySelector(".targetInput").classList.add("invalid");
Have you considered using JQuery validation plugin?
$("form").validate({
errorClass: "my-error-class",
validClass: "my-valid-class",
rules: {
test: {
required: true,
minlength: 12
}
}
});
http://jsfiddle.net/8vQFd/

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

How do I make a textbox that has a grayed out content, and when I click on it to enter text, the grayed out portion, it disappears and allows me to enter the desired text?
Example:
A "First Name" text box. The words "First Name" are inside the text box grayed out, when I click, those words disappear and I write my name in it.
Chrome, Firefox, IE10 and Safari support the html5 placeholder attribute
<input type="text" placeholder="First Name:" />
In order to get a more cross browser solution you'll need to use some javascript, there are plenty of pre-made solutions out there, though I don't know any off the top of my head.
http://www.w3schools.com/tags/att_input_placeholder.asp
This answer illustrates a pre-HTML5 approach. Please take a look at Psytronic's answer for a modern solution using the placeholder attribute.
HTML:
<input type="text" name="firstname" title="First Name" style="color:#888;"
value="First Name" onfocus="inputFocus(this)" onblur="inputBlur(this)" />
JavaScript:
function inputFocus(i) {
if (i.value == i.defaultValue) { i.value = ""; i.style.color = "#000"; }
}
function inputBlur(i) {
if (i.value == "") { i.value = i.defaultValue; i.style.color = "#888"; }
}
With HTML5, you can do this natively with: <input name="first_name" placeholder="First Name">
This is not supported with all browsers though (IE)
This may work:
<input type="first_name" value="First Name" onfocus="this.value==this.defaultValue?this.value='':null">
Otherwise, if you are using jQuery, you can use .focus and .css to change the color.
If you're targeting HTML5 only you can use:
<input type="text" id="firstname" placeholder="First Name:" />
For non HTML5 browsers, I would build upon Floern's answer by using jQuery and make the javascript non-obtrusive. I would also use a class to define the blurred properties.
$(document).ready(function () {
//Set the initial blur (unless its highlighted by default)
inputBlur($('#Comments'));
$('#Comments').blur(function () {
inputBlur(this);
});
$('#Comments').focus(function () {
inputFocus(this);
});
})
Functions:
function inputFocus(i) {
if (i.value == i.defaultValue) {
i.value = "";
$(i).removeClass("blurredDefaultText");
}
}
function inputBlur(i) {
if (i.value == "" || i.value == i.defaultValue) {
i.value = i.defaultValue;
$(i).addClass("blurredDefaultText");
}
}
CSS:
.blurredDefaultText {
color:#888 !important;
}
The shortest way is to directly add the below code as additional attributes in the input type that you want to change.
onfocus="if(this.value=='Search')this.value=''"
onblur="if(this.value=='')this.value='Search'"
Please note: Change the text "Search" to "go" or any other text to suit your requirements.
This works:
<input type="text" id="firstname" placeholder="First Name" />
Note: You can change the placeholder, id and type value to "email" or whatever suits your need.
More details by W3Schools at:http://www.w3schools.com/tags/att_input_placeholder.asp
But by far the best solutions are by Floern and Vivek Mhatre ( edited by j0k )
I have a code snippet below, that is a typical web page.
.Submit {
background-color: #008CBA;
border: 3px;
color: white;
padding: 8px 26px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
div {
background-color: yellow;
}
<div>
<center>
<p>Some functions may not work, such as the css ect.
<p>First Name:<input type="text" id="firstname" placeholder="John" />
<p>Surname:<input type="text" id="surname" placeholder="Doe" />
<p>Email:<input type="email" id="email" placeholder="john.doe#example.com" />
<p>Password:<input type="email" id="email" placeholder="john.doe#example.com" />
<br /><button class="submit">Submit</button> </center>
</div>
This is an elaborate version, to help you understand
function setVolatileBehavior(elem, onColor, offColor, promptText){ //changed spelling of function name to be the same as name used at invocation below
elem.addEventListener("change", function(){
if (document.activeElement == elem && elem.value==promptText){
elem.value='';
elem.style.color = onColor;
}
else if (elem.value==''){
elem.value=promptText;
elem.style.color = offColor;
}
});
elem.addEventListener("blur", function(){
if (document.activeElement == elem && elem.value==promptText){
elem.value='';
elem.style.color = onColor;
}
else if (elem.value==''){
elem.value=promptText;
elem.style.color = offColor;
}
});
elem.addEventListener("focus", function(){
if (document.activeElement == elem && elem.value==promptText){
elem.value='';
elem.style.color = onColor;
}
else if (elem.value==''){
elem.value=promptText;
elem.style.color = offColor;
}
});
elem.value=promptText;
elem.style.color=offColor;
}
Use like this:
setVolatileBehavior(document.getElementById('yourElementID'),'black','gray','Name');
You can use Floern's solution. You may also want to disable the input while you set the color to gray. http://www.w3schools.com/tags/att_input_disabled.asp
Here's a one-liner slim way for layering text on top of an input in jQuery using ES6 syntax.
$('.input-group > input').focus(e => $(e.currentTarget).parent().find('.placeholder').hide()).blur(e => { if (!$(e.currentTarget).val()) $(e.currentTarget).parent().find('.placeholder').show(); });
* {
font-family: sans-serif;
}
.input-group {
position: relative;
}
.input-group > input {
width: 150px;
padding: 10px 0px 10px 25px;
}
.input-group > .placeholder {
position: absolute;
top: 50%;
left: 25px;
transform: translateY(-50%);
color: #929292;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group">
<span class="placeholder">Username</span>
<input>
</div>