Using watermark effect in forms - javascript

I want to implement watermark effect in my html form.
I have my code like this http://jsfiddle.net/aMjT4/1/
I want to set particular value to all my textboxes. Like in my textbox field
<input type="text" id="firstName" name="firstName" value="Enter First Name" class="inputTextboxId"/>
I want to set watermark text from value.(value="Enter First Name").
My javascript look like this but it will set watermark text into all my form fields.
$(document).ready(function () {
var watermark = 'Enter something...';
$('.inputTextboxId').blur(function () {
if ($(this).val().length == 0)
$(this).val(watermark).addClass('watermark');
}).focus(function () {
if ($(this).val() == watermark)
$(this).val('').removeClass('watermark');
}).val(watermark).addClass('watermark');
});
How can i set value text to all my textboxes?
I have this code but in this code i have to write this for all textboxes.
is there any way to generlize this?
<input type="text" id="city" name="city" value="Enter Your City" class="inputTextboxId" onblur="if (this.value == '') { this.value = 'Enter Country City';this.style.color = 'Gray'; }" maxlength="255" onfocus="if(this.value == this.defaultValue){this.value='';this.style.color='Black'}"/>

This is the hard way. You want to just either write a plugin or grab one that is readily available.
http://plugins.jquery.com/project/TinyWatermark
http://plugins.jquery.com/plugin-tags/watermark
Here's one I wrote
this is the js file code;
(function ($) {
$.fn.extend({
watermark: function () {
return this.each(function () {
var $obj = $(this);
$obj.val($obj.attr("watermarkText"));
$obj.focus(function (e) {
if ($obj.val() == $obj.attr("watermarkText"))
$obj.val("");
});
$obj.blur(function (e) {
if ($obj.val() == "")
$obj.val($obj.attr("watermarkText"));
});
});
}
});
})(jQuery);
and then in your html;
<script>
$(function () {
$(".watermark").watermark();
</script>
<input id="author" value="" type="text" name="author" watermarkText="Your name..." class="watermark required">

Related

Displaying range validator error message on html input

I have an input type =text in html and i have this js code in js file to show error message
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
var toReturn = 0;
$("input", $form).each(function () {
if ($(this).val() == "") {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = 1;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
I am trying to convert this code to make range validator on input type=text field .dispalying only 5 digits in the textbox, but i couldn't achieve . Is there any easy way to do this ?
Thanks
Consider using the jQuery validation plugin instead, especially the rangelength method for your case. However, if you want to stick to the original code without using any library then I suggest you try the code below for example:
HTML:
<form id="myid" name="myid" method="post" action="/">name :
<input type="text" name="name" id="name" />age :
<input type="text" name="age" id="age" />
<input type="submit" id="submit" name="submit" value="Save" />
</form>
jQuery:
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
$("#submit").on("click", function () {
var toReturn = true;
$("input", $form).each(function () {
var value = $(this).val();
if((!$.trim(this.value).length) || (value.length > 5)) {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});
Working JSFiddle Demo

Use same function on multiple elements

I need this function to work on multiple elements in the form, right now it only works on TfDiagnosis.
How do I use it on TfDiagnosis and TfDiagnosis2 with results in TfSnowmed and TfSnowmed2?
JQUERY
$(function snowmedlist() {
$('#TfDiagnosis').on('click keyup change blur', function() {
if ($('#TfDiagnosis').val() == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
if ($('#TfDiagnosis').val() == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});
});
HTML
<input name="TfDiagnosis" type="text" id="TfDiagnosis" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed">
<input name="TfDiagnosis2" type="text" id="TfDiagnosis2" size="100" >
<input type="text" name="TfSnowmed2" id="TfSnowmed2"></td>
It's easy to work on groups of elements using class names.
<input name="TfDiagnosis" type="text" id="TfDiagnosis" class="diagnosis" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed">
js:
$('.diagnosis').on('click keyup change blur', function() {
if($(this).val() == "...") {
$(this).next().val(1.00);
}
})
This way .next() is always the next element, so you don't need to keep passing IDs around. You can then store the data outside of the function to get rid of a cluster of IF statements:
var myData = []
myData['[D]Anterograde amnesia (780.93)'] = '206789002';
myData['[D]Chills with fever (780.60)'] = '206760004';
...then substitute the look-up from the array....
$('.diagnosis').on('click keyup change blur', function() {
$(this).next().val(myData[$(this).attr(id)]);
})
You can use
$('#TfDiagnosis, #TfDiagnosis2').on('click keyup change blur', function() {
if($(this).attr('id') == 'TfDiagnosis' ){
if ($(this).val() == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
if ($(this).val() == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
}else{
//Stuff to do in case it is the #TfDiagnosis2
}
});
The most efficient way to make your function work on multiple inputs is to use event delegation:
$(document).on('click keyup change blur', 'input', function() {
var value = $(this).val(); //Get the value only once
if (value == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
else if (value == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});
Which will call the function for any input on the page. You probably want to assign a class to the specific inputs you want to use like so:
HTML
<input name="TfDiagnosis" type="text" id="TfDiagnosis" class="TfInput" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed" class="TfInput">
<input name="TfDiagnosis2" type="text" id="TfDiagnosis2" class="TfInput" size="100" >
<input type="text" name="TfSnowmed2" id="TfSnowmed2" class="TfInput">
JavaScript
$(document).on('click keyup change blur', '.TfInput', function() {
var value = $(this).val(); //Get the value only once
if (value == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
else if (value == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});

Javascript Simplification - Onclick, Onblur, Onfocus - Forms

Is there a way to simplify my javascript code below?
It works but I am quite sure that there must be a way to reduce what evidently shows my elementary javascript skills, and of course, I am trying to improve my understanding.
My HTML Code is just a simple form:
<div>
<form action="">
<input type="text" name="firstname" id="un1" value="First Name"/>
<input type="text" name="surname" id="un2" value="Surname" />
<input type="text" name="username" id="un3" value="Email Address"/>
<input type="button" value="Register!" />
</form>
</div>
My Javascript Code (unobtrusive):
window.onload = function(){
//Field Manoeuvre1
document.getElementById("un1").onclick = fieldClear1;
document.getElementById("un1").onfocus = fieldClear1;
document.getElementById("un1").onblur = fieldReplace1;
//Field Manoeuvre2
document.getElementById("un2").onclick = fieldClear2;
document.getElementById("un2").onfocus = fieldClear2;
document.getElementById("un2").onblur = fieldReplace2;
//Field Manoeuvre3
document.getElementById("un3").onclick = fieldClear3;
document.getElementById("un3").onfocus = fieldClear3;
document.getElementById("un3").onblur = fieldReplace3;
}
//Field Manoeuvre1
function fieldClear1(){
if(document.getElementById("un1").value == "First Name"){
document.getElementById("un1").value = "";
}
}
function fieldReplace1(){
if(document.getElementById("un1").value == ""){
document.getElementById("un1").value = "First Name";
}
}
//Field Manoeuvre2
function fieldClear2(){
if(document.getElementById("un2").value == "Surname"){
document.getElementById("un2").value = "";
}
}
function fieldReplace2(){
if(document.getElementById("un2").value == ""){
document.getElementById("un2").value = "Surname";
}
}
//Field Manoeuvre3
function fieldClear3(){
if(document.getElementById("un3").value == "Email Address"){
document.getElementById("un3").value = "";
}
function fieldReplace3(){
if(document.getElementById("un3").value == ""){
document.getElementById("un3").value = "Email Address";
}
}
SOLUTION 1:
HTML:
<div>
<form action="">
<input type="text" name="firstname" id="un1" class="myInput" value="First Name"/>
<input type="text" name="surname" id="un2" class="myInput" value="Surname" />
<input type="text" name="username" id="un3" class="myInput" value="Email Address"/>
<input type="button" value="Register!" />
</form>
</div>
JS:
var defaultValues = {
un1 : 'First Name',
un2 : 'Surname',
un3 : 'Email Address'
}
var elements = document.querySelectorAll('.myInput');
for (var i=0; i<elements.length; i++) {
elements[i].addEventListener(['click', 'focus'], function(){
if (this.value === defaultValues[this.id]) this.value = '';
});
elements[i].addEventListener('blur', function(){
if (this.value === '') this.value = defaultValues[this.id];
});
}
PS: The code is not compatible with all browsers. If you aim for browser compatibility, you should probably use a library that abstracts away the differences (ex: jQuery).
SOLUTION 2:
No change in HTML
JS:
window.onload = function(){
var field;
//Field Manoeuvre1
field = document.getElementById('un1');
field.onclick = fieldClear.bind(field, 'First Name');
field.onfocus = fieldClear.bind(field, 'First Name');
field.onblur = fieldReplace.bind(field, 'First Name');
//Field Manoeuvre2
field = document.getElementById('un2');
field.onclick = fieldClear.bind(field, 'Surname');
field.onfocus = fieldClear.bind(field, 'Surname');
field.onblur = fieldReplace.bind(field, 'Surname');
//Field Manoeuvre3
field = document.getElementById('un3');
field.onclick = fieldClear.bind(field, 'Last Name');
field.onfocus = fieldClear.bind(field, 'Last Name');
field.onblur = fieldReplace.bind(field, 'Last Name');
}
function fieldClear(value){
if(this.value === value) this.value = '';
}
function fieldReplace(value){
if(this.value === '') this.value = value;
}
DEMO: http://jsbin.com/ekoJuQE/1/edit
Use either jquery or html5
Html5 solution:
Add parameter placeholder to input like this
<input name="firstname" type="text" placeholder="First name" />
Jquery (plus attribute data-placeholder="text shown in field" on html input fields:
$(window).on("load", function(){
$("#un1, #un2, #un3").on("click, focus", fieldClear(this));
$("#un1, #un2, #un3").on("blur", fieldReplace(this));
});
function fieldClear(obj) {
$(obj).val('');
}
function fieldReplace(obj) {
$(obj).val($(obj).data('placeholder'));
}
Delegated event handling can shorten things up a bit. If you pick up jQuery, then add classes or select by element type. Also add a data attr.
<input type="text" name="surname" id="un2" value="Surname" data-placeholder="Surname"/>
$('form').on('click, focus', 'input', function(e){
$(this).val("");
});
$('form').on('blur', 'input', function(){
$(this).val($(this).attr('data-placeholder'));
});

Dynamically show/hide a label based on user input

http://jsfiddle.net/ZKsjr/20/
I would like to know how to add a label field to the bottom of that text field that prints invalid or valid depending on the user input, how could I implement this idea?
HTML:
<input type="text" class="fname" maxlength="255" size="8" value="First Name" required/>
JS:
function isfname(text) {
var reg = /^[a-z ,.'-]+$/i;
return reg.test(text); }
$(".fname").keyup(function (e) {
var $test = $(this);
if (isfname($test.val())) {
$test.css("background-color", "rgb(140, 202, 165)");
$test.css("color", "white");
} else {
$test.css("background-color", "rgb(198, 95, 88)");
$test.css("color", "white");
}
}).blur(function (e) {
$(this).css("background-color", "");
$(this).css("color", "#4A4F4B");
if (!isfname($(this).val()))
$(this).val('First Name');
}).focus(function (e) {
$(this).css("background-color", "");
$(this).css("text-transform", "capitalize");
if (!isfname($(this).val()))
$(this).val('');
});
Try this:
Put input in, lets say div
<div>
<input type="text" class="fname" maxlength="255" size="8" " value="First Name" required/>
</div>
Update your javascript
$(".fname").keyup(function (e) {
var $test = $(this);
$test.parent().find('div').remove();//remove error element before validation
if (isfname($test.val())) {
$test.css("background-color", "rgb(140, 202, 165)");
$test.css("color", "white");
} else {
$test.css("background-color", "rgb(198, 95, 88)");
$test.css("color", "white");
$test.parent().append('<div>Invalid name !</div>');//create error element
}
}).blur(function (e) {
$(this).css("background-color", "");
$(this).css("color", "#4A4F4B");
if (!isfname($(this).val()))
$(this).val('First Name');
}).focus(function (e) {
$(this).css("background-color", "");
$(this).css("text-transform", "capitalize");
if (!isfname($(this).val()))
$(this).val('');
});
fiddle
First, we can use some semantic HTML to describe our elements better.
<input type="text" id="fname" maxlength="255" size="8"
placeholder="First Name" required />
<label for="fname">First name is required</label>
Then we can define a Validator function, which aids us in validating.
function Validate(expression){
return (function(){
var $el = $(this),
$label = $("label[for='"+$el.attr('id')+"']"),
val = $el.val();
if (expression.test(val)) {
$label.fadeOut();
}
else {
$label.fadeIn();
}
});
};
Creating validators in this way is flexible. Here's a simple "one word" check for our first name.
validate = {
first: Validate(/[a-z]+/i)
};
Our binding to the HTML is then much simpler.
$('#fname').blur(validate.first).keyup(validate.first);

JQuery focusOut issue in IE

I have a small problem with focusout function in IE.
I have two fields with the same class and I wrote an empty validation code in jQuery for that class with focusout.
While I focus out of a field which is empty it shows alert and focus to the same field.
While doing that focus, It shows me alert again and again b'coz of the same class.
What to do?
JS:
$(".emptyValidate").focusout(function() {
var currFocusOut = $(this).attr("inText");
if($(this).val() == ""){
alert(currFocusOut+" should not be Empty");
document.getElementById(currFocusOut).focus();
}
});
Markup :
<input type="text" inText="Name" id="Name" class="emptyValidate "/>
<input type="text" inText="Phone" id="Phone" class="emptyValidate "/>
Working Demo
$(".emptyValidate").focusout(function () {
var currFocusOut = $(this).attr("id");
if ($(this).val() == "") {
alert(currFocusOut + " should not be Empty");
$('#'+currFocusOut).focus();
}
});
Try to use blur function like,
$(".emptyValidate").blur(function() {
var currFocusOut = $(this).attr("inText");
if($(this).val() == ""){
alert(currFocusOut+" should not be Empty");
document.getElementById(currFocusOut).focus();
}
});
Read blur()
Or, custom attribute inText may not work, so you can use data in jquery like
<input type="text" data-inText="Name" id="Name" class="emptyValidate "/>
<input type="text" data-inText="Phone" id="Phone" class="emptyValidate "/>
$(".emptyValidate").focusout(function() { // use blur if not works
var currFocusOut = $(this).data("inText");
if($(this).val() == ""){
alert(currFocusOut+" should not be Empty");
document.getElementById(currFocusOut).focus();
}
});
Read data()
Try inline function like this:
<input type="text" inText="Name" id="Name" class="emptyValidate" onfocusout="myFunction(this)"/>
<input type="text" inText="Phone" id="Phone" class="emptyValidate" onfocusout="myFunction(this)"/>
function myFunction(el){
var currFocusOut = $(el).attr("inText");
if($(el).val() == ""){
alert(currFocusOut+" should not be Empty");
document.getElementById(currFocusOut).focus();
}
}

Categories

Resources