If I have code like this:
<form id="test_form">
<input type="text" value="Original value" />
</form>
Then using jQuery I run this code:
$('#test_form input').val('New value');
So input have new value, but I wanna get the old one, so I do:
$('#test_form')[0].reset();
now $('#test_form input').val() == 'Original value';
But reset method reset all form inputs and restore there default values, so how can I restore default value just in definite input?
on jQuery 1.6+
$('#test_form input').prop('defaultValue');
on older versions use .attr() instead of .prop()
You can use the defaultValue property:
this.value = this.defaultValue;
For example, the following code would reset the field to its default value when the blur event is fired:
$("#someInput").blur(function() {
this.value = this.defaultValue;
});
And here's a working example.
You could very easily build a plugin to do this, using the defaultValue property, which corresponds to the original state of the element.
$.fn.reset = function() {
this.each(function() {
this.value = this.defaultValue;
});
};
You can then call this plugin like this:
$('someSelector').reset();
Try whatever the jQuery equivalent to JavaScript's .getAttribute('value') is - the attribute does not change even if the value itself does.
I would suggest using placeholder attribute for inputs and textareas.
// Sample Usage
// $(document).ready(function(){ $.snapshot("#myForm"); }); Take shapshot
// event, function(){ $.reset("#myForm"); } Rest Form On Some Event
(function($) {
$.fn.getAttributes = function() {
var attributes = {};
if(!this.length)
return this;
$.each(this[0].attributes, function(index, attr) {
attributes[attr.name] = attr.value;
});
return attributes;
}
})(jQuery);
(function($)
{
jQuery.snapshot = function(form)
{
var form = $(form);
var elements = form.find("input, select, textarea");
if(elements && elements.length)
{
elements.each(function(){
var attributes = $(this).getAttributes();
var tagName = $(this).prop("tagName").toLowerCase();
var safe_attributes = {};
for(i in attributes)
{
var jq_attr = $(this).attr(i);
if(jq_attr != "undefined")
{
safe_attributes[i] = jq_attr;
}
}
if(tagName == "select")
{
var option = $(this).find("option:selected");
if(option && option.length)
{
var init_selected = option.attr("value");
safe_attributes['init_selected'] = init_selected;
}
}
if(tagName == "textarea")
{
var init_value = $(this).val();
safe_attributes['init_value'] = init_value;
}
$.data( $(this).get(0), "init_attr", safe_attributes );
});
}
}
jQuery.reset = function(form)
{
var form = $(form);
var elements = form.find("input, select, textarea");
var reset_btn = $('<input type="reset" name="reset" />');
form.append(reset_btn);
reset_btn.trigger("click");
reset_btn.remove();
if(elements && elements.length)
{
elements.each(function(){
var init_attributes = $(this).data("init_attr");
var attributes = $(this).getAttributes();
var tagName = $(this).prop("tagName").toLowerCase();
for(i in attributes)
{
if(i.toLowerCase() == "value" || i.toLowerCase() == "checked" || i.toLowerCase() == "selected")//if(i.toLowerCase() != "type")
{
var attr_found = false;
for(a in init_attributes)
{
if(i == a)
{
$(this).attr(a, init_attributes[a]);
attr_found = true;
}
}
if(!attr_found)
{
$(this).removeAttr(i);
}
}
}
if(tagName == "select" && 'init_selected' in init_attributes)
{
$(this).find("option:selected").removeAttr("selected");
var option = $(this).find("option[value="+init_attributes['init_selected']+"]");
if(option && option.length)
{
option.attr("selected", "selected");
}
}
if(tagName == "textarea")
{
if('init_value' in init_attributes)
{
$(this).val(init_attributes['init_value']);
}
}
$(this).trigger("change");
});
}
}
})(jQuery);
Related
I have a simple input that I'm using an keyup event listener on. If the input length is too short, the span element will remove the class on it that hides the element and display "Input too short".
If I have multiple inputs, how can I only enable the Submit button if all fields pass the validation.
Unfortunately, I'm thinking in a React-way and would accomplish this via state.
<style type="text/css">
.hide-first {
display: none;
}
.hide-last {
display: none;
}
</style>
<div>
<div>
<input id="first-name" />
<span id="validation-span" class="hide-first">Input too short</span>
</div>
<button>Submit</button>
</div>
<script type="text/javascript">
let firstName = document.getElementById( 'first-name' );
let span = document.getElementById( 'validation-span' );
firstName.addEventListener( 'keyup', () => {
console.log( event.target.value.length )
if ( event.target.value.length < 5 ) {
span.classList.remove( 'hide-first' )
} else {
span.classList.add( 'hide-first' )
}
} );
</script>
All your inputs could call the same validation function that checks everything except inputs that are empty. Only show the submit button if they all succeed and show the appropriate message on inputs that fail the validation.
Pseudo-code:
boolean succes = true
if username is invalid and not empty
username invalid message
success = false
if password is invalid and not empty
password invalid message
success = false
if success is true
show submit button
At first add style your button style="display:none". You can use jQuery as bellow
$( document ).ready( function () {
var _rules = {
"first-name": function ( $owner ) {
var val = $owner.val();
if ( !val ) return false;
if ( val.length < 5 ) return false;
return true;
}
};
//Validate here
function validate(total_mark) {
var mark = 0;//total mark
//Read all input value, than check rules
$( 'input' ).each( function () {
if ( 'function' !== typeof ( _rules[this.id] ) ) return;
var $owner = $( this );
var result = _rules[this.id]( $owner );
if ( !result ) {
mark -= 1;
$owner.next().removeClass( 'hide-first' );
return;
}
$owner.next().addClass( 'hide-first' );
mark += 1;
return;
} );
return mark;
};
var $btn = $( 'button' );
//Register keyup event for all input
var total_input = 1;
$( 'input' ).on( "keyup", function ( e ) {
e.preventDefault();
$btn.css( "display", "none" );
if ( validate() < total_input ) return;
$btn.css( "display", "" );
} );
} );
Something like this should work
<div>
<div>
<input id="first-name" onchange='validation()'/>
<span id ="validation-span" class="hide-first">Input too short</span>
</div>
<button id='submit-button'>
Submit
</button>
</div>
<script type="text/javascript">
function validateFirstName() {
let firstName = document.getElementById('first-name');
let span = document.getElementById('validation-span');
if (event.target.value.length < 5) {
span.classList.remove('hide-first')
return True
}
span.classList.add('hide-first')
return False
}
function validation() {
let submitButton = document.getElementById('submit-button');
submitButton.disabled = validateFirstName();
}
</script>
As you add additional fields, you should create the validation function for that field, and then running it inside validation() like:
function validation() {
let submitButton = document.getElementById('submit-button');
submitButton.disabled = validateFirstName() && validateSecondField() && validateThirdField() &&...;
}
Remember to add to the html input the onchange event listener.
Simple logic. Make a function that checks if all of the fields are validated, and call it from within the onkeyup event. A seemingly straight-forward way would be like this:
let firstName = document.getElementById('first-name'),
lastName = document.getElementById('last-name'),
company = document.getElementById('company-name');
let span = document.getElementById('validation-span'),
span1 = document.getElementById('validation-span1'),
span2 = document.getElementById('validation-span2'),
conditions = [],
length = 3;
firstName.addEventListener('keyup', () => {
console.log(event.target.value.length)
if (event.target.value.length < 5) {
span.classList.remove('hide-first')
conditions[0] = true;
} else {
span.classList.add('hide-first')
conditions[0] = false;
}
})
lastName.addEventListener('keyup', () => {
console.log(event.target.value.length)
if (event.target.value.length < 5) {
span1.classList.remove('hide-first')
conditions[1] = true;
} else {
span1.classList.add('hide-first')
conditions[1] = false;
}
})
company.addEventListener('keyup', () => {
console.log(event.target.value.length)
if (event.target.value.length < 5) {
span2.classList.remove('hide-first')
conditions[2] = true;
} else {
span2.classList.add('hide-first')
conditions[2] = false;
}
})
function checkAllTrueAndActivateSubmitBtn() {
var result = true;
for(var i = 0; i < length; i++) {
if(!conditions[i]) {
result = false;
}
}
if(result) {
submitBtn.classList.add("shown"); //or whatever
}
}
but of course, the more fields you have,the more messy this becomes. A more efficient way would be to use an array for the fields, and conditions:
let IDsAndConditions = {
'first-name':{
condition: (x) => x.length >= 5,
span: 'validation-span'
},
'last-name': {
condition: (x) => x.length >= 8,
span: 'validation-span-lastName'
},
'phoneNumber':{
condition: (x) => x.match(/^-{0,1}\d+$/),//or whatever
span:"phone-span"
}
};
var conditions = [];
var num = 0;
for(var k in IDsAndConditions) {
var cur = IDsAndConditions[k];
var el = document.getElementById(k);
var span = document.getElementById(cur["span"]);
if(el && span) {
el.addEventListener('keyup', () => {
console.log(event.target.value.length)
if (!cur["condition"](event.target.value)) {
span.classList.remove('hide-first')
conditions[num] = true;
} else {
span.classList.add('hide-first')
conditions[num] = false;
}
checkAllTrueAndActivateSubmitBtn();
});
} else {
conditions[num] = true; //this is to make the validation work even if the element doesn't exist
}
num++;
}
function checkAllTrueAndActivateSubmitBtn() {
var result = true;
for(var i = 0; i < IDsAndConditions.length; i++) {
if(!conditions[i]) {
result = false;
}
}
if(result) {
submitBtn.classList.add("active"); //or whatever
} else {
submitBtn.classList.remove("active"); //even if it was active at one point, if someone changes a field to an incorrect value, it deactivates again
}
}
I'm running a page which throws an error at the following line:
var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
For the sake of completeness, here is the full jQuery function (country-select.js):
(function($) {
$.fn.countrySelect = function (callback) {
$(this).each(function(){
var $select = $(this);
var lastID = $select.data('select-id'); // Tear down structure if Select needs to be rebuilt
if (lastID) {
$select.parent().find('span.caret').remove();
$select.parent().find('input').remove();
$select.unwrap();
$('ul#select-options-'+lastID).remove();
}
// If destroying the select, remove the selelct-id and reset it to it's uninitialized state.
if(callback === 'destroy') {
$select.data('select-id', null).removeClass('initialized');
return;
}
var uniqueID = Materialize.guid();
$select.data('select-id', uniqueID);
var wrapper = $('<div class="select-wrapper"></div>');
wrapper.addClass($select.attr('class'));
var options = $('<ul id="select-options-' + uniqueID +'" class="dropdown-content select-dropdown country-select"></ul>'),
selectChildren = $select.children('option, optgroup'),
valuesSelected = [],
optionsHover = false;
var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
// Function that renders and appends the option taking into
// account type and possible image icon.
var appendOptionWithIcon = function(select, option, type) {
// Add disabled attr if disabled
var disabledClass = (option.is(':disabled')) ? 'disabled ' : '';
var optgroupClass = (type === 'optgroup-option') ? 'optgroup-option ' : '';
var classes = option.attr('class');
var data = option.data('phone-code');
var opt = '<li class="' + disabledClass + optgroupClass + '"><span>';
if (option.val() !== '') {
opt += '<b class="flag flag-' + option.val().toLowerCase() + '"></b>';
}
opt += '<span class="option-label">' + option.html() + '</span>';
if (data && data !== '') {
opt += '<small>' + data + '</small>';
}
opt += '</span></li>';
options.append($(opt));
};
/* Create dropdown structure. */
if (selectChildren.length) {
selectChildren.each(function() {
if ($(this).is('option')) {
appendOptionWithIcon($select, $(this));
} else if ($(this).is('optgroup')) {
// Optgroup.
var selectOptions = $(this).children('option');
options.append($('<li class="optgroup"><span>' + $(this).attr('label') + '</span></li>'));
selectOptions.each(function() {
appendOptionWithIcon($select, $(this), 'optgroup-option');
});
}
});
}
options.find('li:not(.optgroup)').each(function (i) {
$(this).click(function (e) {
// Check if option element is disabled
if (!$(this).hasClass('disabled') && !$(this).hasClass('optgroup')) {
var selected = true;
options.find('li').removeClass('active');
$(this).toggleClass('active');
$newSelect.val($(this).find('.option-label').text());
activateOption(options, $(this));
$select.find('option').eq(i).prop('selected', selected);
// Trigger onchange() event
$select.trigger('change');
if (typeof callback !== 'undefined') callback();
}
e.stopPropagation();
});
});
// Wrap Elements
$select.wrap(wrapper);
// Add Select Display Element
var dropdownIcon = $('<span class="caret">▼</span>');
if ($select.is(':disabled'))
dropdownIcon.addClass('disabled');
// escape double quotes
var sanitizedLabelHtml = label.replace(/"/g, '"');
var $newSelect = $('<input type="text" class="select-dropdown" readonly="true" ' + (($select.is(':disabled')) ? 'disabled' : '') + ' data-activates="select-options-' + uniqueID +'" value="'+ sanitizedLabelHtml +'"/>');
$select.before($newSelect);
$newSelect.before(dropdownIcon);
$newSelect.after(options);
// Check if section element is disabled
if (!$select.is(':disabled')) {
$newSelect.data('constrainwidth', false)
$newSelect.dropdown({'hover': false, 'closeOnClick': false});
}
// Copy tabindex
if ($select.attr('tabindex')) {
$($newSelect[0]).attr('tabindex', $select.attr('tabindex'));
}
$select.addClass('initialized');
$newSelect.on({
'focus': function (){
if ($('ul.select-dropdown').not(options[0]).is(':visible')) {
$('input.select-dropdown').trigger('close');
}
if (!options.is(':visible')) {
$(this).trigger('open', ['focus']);
var label = $(this).val();
var selectedOption = options.find('li').filter(function() {
return $(this).find('.option-label').text().toLowerCase() === label.toLowerCase();
})[0];
activateOption(options, selectedOption);
}
},
'click': function (e){
e.stopPropagation();
}
});
$newSelect.on('blur', function() {
$(this).trigger('close');
options.find('li.selected').removeClass('selected');
});
options.hover(function() {
optionsHover = true;
}, function () {
optionsHover = false;
});
// Make option as selected and scroll to selected position
var activateOption = function(collection, newOption) {
if (newOption) {
collection.find('li.selected').removeClass('selected');
var option = $(newOption);
option.addClass('selected');
options.scrollTo(option);
}
};
// Allow user to search by typing
// this array is cleared after 1 second
var filterQuery = [],
onKeyDown = function(e){
// TAB - switch to another input
if(e.which == 9){
$newSelect.trigger('close');
return;
}
// ARROW DOWN WHEN SELECT IS CLOSED - open select options
if(e.which == 40 && !options.is(':visible')){
$newSelect.trigger('open');
return;
}
// ENTER WHEN SELECT IS CLOSED - submit form
if(e.which == 13 && !options.is(':visible')){
return;
}
e.preventDefault();
// CASE WHEN USER TYPE LETTERS
var letter = String.fromCharCode(e.which).toLowerCase(),
nonLetters = [9,13,27,38,40];
if (letter && (nonLetters.indexOf(e.which) === -1)) {
filterQuery.push(letter);
var string = filterQuery.join(''),
newOption = options.find('li').filter(function() {
return $(this).text().toLowerCase().indexOf(string) === 0;
})[0];
if (newOption) {
activateOption(options, newOption);
}
}
// ENTER - select option and close when select options are opened
if (e.which == 13) {
var activeOption = options.find('li.selected:not(.disabled)')[0];
if(activeOption){
$(activeOption).trigger('click');
$newSelect.trigger('close');
}
}
// ARROW DOWN - move to next not disabled option
if (e.which == 40) {
if (options.find('li.selected').length) {
newOption = options.find('li.selected').next('li:not(.disabled)')[0];
} else {
newOption = options.find('li:not(.disabled)')[0];
}
activateOption(options, newOption);
}
// ESC - close options
if (e.which == 27) {
$newSelect.trigger('close');
}
// ARROW UP - move to previous not disabled option
if (e.which == 38) {
newOption = options.find('li.selected').prev('li:not(.disabled)')[0];
if(newOption)
activateOption(options, newOption);
}
// Automaticaly clean filter query so user can search again by starting letters
setTimeout(function(){ filterQuery = []; }, 1000);
};
$newSelect.on('keydown', onKeyDown);
});
function toggleEntryFromArray(entriesArray, entryIndex, select) {
var index = entriesArray.indexOf(entryIndex),
notAdded = index === -1;
if (notAdded) {
entriesArray.push(entryIndex);
} else {
entriesArray.splice(index, 1);
}
select.siblings('ul.dropdown-content').find('li').eq(entryIndex).toggleClass('active');
// use notAdded instead of true (to detect if the option is selected or not)
select.find('option').eq(entryIndex).prop('selected', notAdded);
setValueToInput(entriesArray, select);
return notAdded;
}
function setValueToInput(entriesArray, select) {
var value = '';
for (var i = 0, count = entriesArray.length; i < count; i++) {
var text = select.find('option').eq(entriesArray[i]).text();
i === 0 ? value += text : value += ', ' + text;
}
if (value === '') {
value = select.find('option:disabled').eq(0).text();
}
select.siblings('input.select-dropdown').val(value);
}
};
$(function() {
$('.js-country-select').countrySelect();
});
$(document).on('change', '[data-country-select]', function() {
var target = 'select' + $(this).data('country-select');
var val = $(this).val();
var label = 'State';
var options = [
'<option value="" selected="" disabled="">Select State</option>'
];
if (val !== '') {
var country = window.__COUNTRIES[val];
var subdivisions = country.subdivisions;
var keys = Object.keys(subdivisions);
label = country.subdivisionName;
options = [
'<option value="" selected="" disabled="">Select ' + label + '</option>'
];
keys = keys.sort(function(a, b) {
var valA = subdivisions[a].toLowerCase();
var valB = subdivisions[b].toLowerCase();
if (valA < valB) return -1;
if (valA > valB) return 1;
return 0;
});
keys.forEach(function(key) {
options.push('<option value="' + key + '">' + subdivisions[key] + '</option>');
});
$(target).removeAttr('disabled');
} else {
$(target).attr('disabled', 'disabled');
}
$(target).parents('.input-field').find('label').html(label);
$(target).val('').html(options);
$(target).select2();
});
})(jQuery);
Here is the exception that I see in debug mode:
From what I understand from Failed to execute 'querySelectorAll' on 'Element' in ExtJS 5, :selected is not part of the CSS specification.
How should I fix this? Should I use:
var label = $select.find('option').filter(':selected').html() || $select.find('option').filter(':first').html() || "";
?
Converting Phil's comment to an answer, my debugger was set to pause on all exceptions (including caught ones). I had to de-activate the 'stop sign' button shown below to make the debugger work normally again.
HTML
<select ng-model="selectedName" ng-change="retrieveSelectedClass()" ng-options="(item.name||item) group by item.groupName for item in names"
class="code-helper" id="code-helperId">
<option value="">Select Option</option>
</select>
JavaScript
var globalEditor1 = null;
var globalMergeEditor = null;
var widgets = [];
var timeout;
var app = angular.module('myApp', []);
var previousValue;
app.controller('OrderFormController', function($scope, $http) {
$scope.retrieveSelectedClass = function() {
$scope.isPaneShown = true;
if ($scope.selectedName === undefined) {
$scope.isPaneShown = false;
return;
}
if ($scope.selectedName.groupName === 'Create New') {
if (globalEditor1) {
if (!globalEditor1.isClean()) {
var r = confirm("You have unsaved changes, are you sure you want to proceed ?");
if (r != true) {
$('.code-helper').val(previousValue);
$scope.isPaneShown = false;
return;
}
}
}
$scope.isPaneShown = false;
} else {
if (globalEditor1) {
if (!globalEditor1.isClean()) {
var r = confirm("You have unsaved changes, are you sure you want to proceed ?");
if (r != true) {
$('.code-helper').val(previousValue);
$scope.isPaneShown = false;
return;
}
}
}
}
}
});
$(document).ready(function() {
$('.code-helper').select2({
placeholder: 'Select a command to begin'
});
$('.code-helper').on('select2:selecting', function(evt) {
console.log($('.code-helper').val());
previousValue = $('.code-helper').val();
});
});
I have ng-model, attached, but still sometimes the ng-change function is not getting called, this happens only in this scenario.
When a change is detected: !globalEditor1.isClean() = true then I am trying to replace the selected value with the previous value.
This happens fine. But now when I try to change the value from select tag, it does not fire the ng-change event.
jsfiddle
Click here
Steps to reproduce:
Try the following: run the link again.
then step
1) From the drop down select "AccountProcessorTest"
2) select ok from alert
3) Select "AddPrimaryContact" and from alert select cancel
4) now the previous value is retained.
5) now select "AddPrimaryContact" again.
The event wont fire.
This works:
ng-change="retrieveSelectedClass(selectedName, '{{selectedName}}')"
JS
$scope.retrieveSelectedClass = function(newValue, oldValue) {
var oldValueSelected = {};
if (angular.isUndefined(oldValueSelected.id) && oldValue.indexOf('"id"') !== -1) {
oldValueSelected = JSON.parse(oldValue);
}
var possibleOldValues = $filter('filter')($scope.names, {
id: oldValueSelected.id
}, true);
oldValue = possibleOldValues[0];
}
I have used this jquery plugin SumoSelect for drop-down select with check-box
<select multiple="multiple" class="SlectBox" name="cat_ids[]">
<option value="op1">Options1</option>
<option value="op2">Options2</option>
<option value="op3">Options3</option>
<option value="op4">Options4</option>
<option value="op5">Options5</option>
</select>
This drop-down working fine with check-bow selections.
But I want to put some limitation for different users with this selection.
I have tried below jquery code but it not working proper
jQuery(document).ready(function($){
var last_valid_selection = null;
$('.SlectBox').change(function(event) {
if ($(this).val().length > 2) {
alert('You can only choose 2!');
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
}
}); });
You can use sumo methods unSelectAll and selectItem and the triggerChangeCombined option on the plugin init.
Ref: http://hemantnegi.github.io/jquery.sumoselect/
In the change event if the limit is raised you can deselect all and set the last valid selection by the index of each element.
Code:
$('#island').SumoSelect({ triggerChangeCombined: true, placeholder: "TestPlaceholder" });
var last_valid_selection = null;
$('#island').change(function (event) {
if ($(this).val().length > 2) {
alert('You can only choose 2!');
var $this = $(this);
$this[0].sumo.unSelectAll();
$.each(last_valid_selection, function (i, e) {
$this[0].sumo.selectItem($this.find('option[value="' + e + '"]').index());
});
} else {
last_valid_selection = $(this).val();
}
});
Demo: http://jsfiddle.net/IrvinDominin/80xLm01g/
There is better sample.
Dont forgot triggerChangeCombined: true
var last_selection = null;
var load_selection = false;
$('#SeasonIdList').change(function (event) {
if (load_selection == true) {
return false;
}
if ($(this).val() != null && $(this).val().length > 3) {
load_selection = true;
var $this = $(this);
$this[0].sumo.unSelectAll();
$.each(last_selection, function (i, e) {
$this[0].sumo.selectItem($this.find('option[value="' + e + '"]').index());
});
load_selection = false;
} else {
last_selection = $(this).val();
}
});
The below is the html code:
<textarea name="test" rows="5" cols="20" placeholder="Brief description of your requirement,project, concept or idea"></textarea>
<script>
$(function() {
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
if (!supports_input_placeholder()) {
var fields = document.getElementsByTagName('textarea');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('placeholder')) {
fields[i].defaultValue = fields[i].getAttribute('placeholder');
fields[i].onfocus = function() {
if (this.value == this.defaultValue)
this.value = '';
}
fields[i].onblur = function() {
if (this.value == '')
this.value = this.defaultValue;
}
}
}
}
});
</script>
Please help me point out the mistake. placeholder fallback functionality is not working.I have been debugging it from long time.
Below is the link for fiddle:
check the functionality in ie9 and below as they doesn't support placeholder attribute:
http://jsfiddle.net/DxcYW/
Thanks
Here it is in pure JavaScript:
(function (D, undefined) {
'use strict';
var i, length, placeholder, textareas;
function hidePlaceHolder (placeholder) {
return function (e) {
var target;
target = e.target || e.srcElement;
if (target.value === placeholder) {
target.value = '';
}
};
}
function showPlaceHolder (placeholder) {
return function (e) {
var target;
target = e.currentTarget || e.srcElement;
if (target.value === '') {
target.value = placeholder;
}
};
}
if (! ('placeholder' in D.createElement('textarea'))) {
textareas = D.getElementsByTagName('textarea');
length = textareas.length;
for (i = 0; i < length; i += 1) {
placeholder = textareas[i].getAttribute('placeholder');
textareas[i].value = placeholder;
if (textareas[i].addEventListener) {
textareas[i].addEventListener('focus', hidePlaceHolder(placeholder));
textareas[i].addEventListener('blur', showPlaceHolder(placeholder));
} else {
textareas[i].attachEvent('onfocus', hidePlaceHolder(placeholder));
textareas[i].attachEvent('onblur', showPlaceHolder(placeholder));
}
}
}
}(document));
try putting your JS in
<script> ... </script>
tags. :)
My findings and solution:
Input fields have value attribute but TEXTAREA doesn't have it.
So when we use inputObj.defaultValue="sometext" for input tag it sets the default value as well as current value to sometext, if we dont define the attribute value="something" in the input tag.This works fine from ie9 and above. For below versions if we don't define value="sometext" inputObj.defaultValue="sometext" won't set current value as the default value by itself. For this we can do two things:
we have to manually give value="something which is equal to placeholder text"
we can get the value of placeholder through javascript and set the value from there.
This is not the case with textarea. Textarea doesn't have a attribute value. So when we use textareaObj.defaultValue="sometextarea text" then the default value is set to the given text but not the value itself as we don't have value attribute.value in textarea is nothing but the content between the textarea tags.
Difference between defaultvalue and value:
default value remains the same once it is set.
value is the current value which is being modified by javascript or ourself my typing into the textfield.
For my above issue I found a workaround just by adding one more line to my code:
<textarea name="test" rows="5" cols="20" placeholder="Brief description of your requirement,project, concept or idea"></textarea>
<script>
$(function() {
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
if (!supports_input_placeholder()) {
var fields = document.getElementsByTagName('textarea');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('placeholder')) {
fields[i].defaultValue = fields[i].getAttribute('placeholder');
fields[i].value = fields[i].getAttribute('placeholder');//setting the value
fields[i].onfocus = function() {
if (this.value == this.defaultValue)
this.value = '';
}
fields[i].onblur = function() {
if (this.value == '')
this.value = this.defaultValue;
}
}
}
}
});
</script>
Thank you guys for your quick replies and I pity the guy who voted down the question. I feel it is a good question. isn't it ?