Dynamically show/hide a label based on user input - javascript

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

Related

Use JavaScript to disable fields in a HTML form

I have two fields in a HTML form:
<input type="text" name="name1"/>
<input type="text" name="name2"/>
Is there a way using JavaScript that if the user user has entered text into the first test box, the second textbox is disabled and vice-versa?
You could do it with jQuery by disabling the input that wasn't being typed in using the keyup() event in conjunction with the not() method. That would look like this:
$(function() {
var textLength;
$('input').keyup(function() {
textLength = $(this).val().length;
if (textLength > 0) {
$('input').not(this).attr('disabled','disabled');
} else {
$('input').removeAttr('disabled');
}
});
});
input[type="text"]:disabled {
background: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name1"/>
<input type="text" name="name2"/>
Here is an very simple example(jsfiddle link below):
<input type="text" name="name1" id="name1" placeholder="Name 1"/>
<input type="text" name="name2"id="name2" placeholder="Name 2"/>
var name1 = document.getElementById('name1'),
name2 =document.getElementById('name2');
name1.onkeyup = function(e) {
if (name1.value.length > 0) {
name2.setAttribute('disabled', 'disabled');
} else {
name2.removeAttribute('disabled');
}
}
name2.onkeyup = function(e) {
if (name2.value.length > 0) {
name1.setAttribute('disabled', 'disabled');
} else {
name1.removeAttribute('disabled');
}
}
https://jsfiddle.net/Neviton/81zzjabk/
jQuery way:
At first you have to create CSS class 'disabled'.
<style>
.disabled {
opacity: 0.5;
pointer-events: none;
}
</style>
Then you add event listener 'change' to your inputs.
$( "input[value='name1']" ).change(function() {
$("input[value='name2']" ).addClass('disabled');
});
and
$( "input[value='name2']" ).change(function() {
$("input[value='name1']" ).addClass('disabled');
});
That will do the trick. When user changes value of input it adds class 'disabled' to another input.
This is an answer in clear JavaScript. The advantage of using the disabled property is, that even with tabulating it is not possible to put an input into the other field.
In the snippet the disabling is also reset if both input fields are empty.
var in1 = document.getElementById("input1"),
in2 = document.getElementById("input2");
function doOnChange() {
if (in1.value != "") {
in1.disabled = false;
in2.disabled = true;
} else if (in2.value != "") {
in1.disabled = true;
in2.disabled = false;
} if (in1.value == "" && in2.value == "") {
in1.disabled = false;
in2.disabled = false;
}
}
in1.addEventListener("keyup", doOnChange);
in2.addEventListener("keyup", doOnChange);
<input id="input1" />
<input id="input2" />
function myFunction() {
var a = document.getElementById('input1');
var b = document.getElementById('input2');
if (a.value.length == 0 && b.value.length == 0) {
a.disabled = false;
b.disabled = false;
} else if (a.value.length == 0) {
a.disabled = true;
} else if (b.value.length == 0) {
b.disabled = true;
}
}
<input type="text" id="input1" onkeyup="myFunction()" />
<input type="text" id="input2" onkeyup="myFunction()" />

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

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

Using watermark effect in forms

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">

Categories

Resources