Email input form not showing/working properly in different browsers - html

I have a simple form which only has two input controls: a text box for taking emails, and a submit button.
HTML:
<form class="form-wrapper cf">
<input type="text" placeholder="Enter your email here..." required>
<button type="submit">
Submit
</button>
</form>
JSFiddle: http://jsfiddle.net/ahmadka/aDhUL/
Form has issues in different browsers:
Chrome: Works & displays fine.
iPhone: Works & displays fine.
Firefox 22: placeholder text not shown, and cannot type anything in
the textbox too !
Internet Explorer 10: Works fine, but placeholder text is cropped !
How can I make it cross-browser compatible guys ?
I've tried removing the placeholder and required parameters to make it very simple, but still it doesn't work on Firefox ..

I think you try to run "placeholder" in all browser.
then just attach one .js file that as follow it work Fine in all browser.
;(function(window, document, $) {
var isInputSupported = 'placeholder' in document.createElement('input'),
isTextareaSupported = 'placeholder' in document.createElement('textarea'),
prototype = $.fn,
valHooks = $.valHooks,
hooks,
placeholder;
if (isInputSupported && isTextareaSupported) {
placeholder = prototype.placeholder = function() {
return this;
};
placeholder.input = placeholder.textarea = true;
} else {
placeholder = prototype.placeholder = function() {
var $this = this;
$this
.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
.not('.placeholder')
.bind({
'focus.placeholder': clearPlaceholder,
'blur.placeholder': setPlaceholder
})
.data('placeholder-enabled', true)
.trigger('blur.placeholder');
return $this;
};
placeholder.input = isInputSupported;
placeholder.textarea = isTextareaSupported;
hooks = {
'get': function(element) {
var $element = $(element);
return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
},
'set': function(element, value) {
var $element = $(element);
if (!$element.data('placeholder-enabled')) {
return element.value = value;
}
if (value == '') {
element.value = value;
// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
if (element != document.activeElement) {
// We can't use `triggerHandler` here because of dummy text/password inputs :(
setPlaceholder.call(element);
}
} else if ($element.hasClass('placeholder')) {
clearPlaceholder.call(element, true, value) || (element.value = value);
} else {
element.value = value;
}
// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
return $element;
}
};
isInputSupported || (valHooks.input = hooks);
isTextareaSupported || (valHooks.textarea = hooks);
$(function() {
// Look for forms
$(document).delegate('form', 'submit.placeholder', function() {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder', this).each(clearPlaceholder);
setTimeout(function() {
$inputs.each(setPlaceholder);
}, 10);
});
});
// Clear placeholder values upon page reload
$(window).bind('beforeunload.placeholder', function() {
$('.placeholder').each(function() {
this.value = '';
});
});
}
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
function clearPlaceholder(event, value) {
var input = this,
$input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
input.value = '';
$input.removeClass('placeholder');
input == document.activeElement && input.select();
}
}
}
function setPlaceholder() {
var $replacement,
input = this,
$input = $(input),
$origInput = $input,
id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch(e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': true,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
}
}(this, document, jQuery));
and then just put one script on page.
<script>
$(function() {
$('input, textarea').placeholder();
});
</script>
It Work Fine in All Browser (placeholder)

Actually the problem is with your CSS styling.
You have set the height of the input as 0px. So the input box accepts the input but is not displayed in FF due to the height set to zero.
Your Previous Code is here:
.form-wrapper input {
width: 150px;
height: 0px;
padding: 10px 5px;
New JSFiddle with height set to 10px is here: http://jsfiddle.net/B435n/
And you can use any jQuery plugin for placeholder thing.

Related

kendoGrid and multiselectbox column initialization using query string parameters

I am implementing a custom solution that will initialize kendoGrid (and its multiselect columns) by applying filters to the grid using query string parameters. I am using Kendo UI v2014.2.903 and multiselectbox user extension.
To achieve this, I have a custom JavaScript function that parses query string parameters into filter object and applies it to kendoGrid's dataSource property using its filter method. Code snippet below:
var preFilterQueryString = getPreFilterQuery(queryString);
if (preFilterQueryString != '') {
kendoGrid.dataSource.filter(parseFilterString(preFilterQueryString));
}
I am initializing multiselectbox as follows:
args.element.kendoMultiSelectBox({
dataSource: getAutoCompleteDataSource(column.field),
valuePrimitive: true,
selectionChanged: function (e) {
//ignored for brevity
}
});
My problem is if I set filters to multiselectbox using above approach, they are not applied correctly to the data set.
For example, if I pass single filter as "Vancouver", correct result set is displayed. Choices in the multiselectbox are "All" and "Vancouver". However, Vancouver choice is not checked in the multiselectbox. Is that by design? Please see image below.
single filter image
If I pass in two filters Vancouver and Warsaw, only the last filter Warsaw is applied to the grid and data set containing only Warsaw is displayed. Again, none of the choices are checked in the multiselectbox.
two filters image
Below is the filter object that is applied to dataSource.filter() method.
kendoGrid's filter object image
Troubleshooting
Below is condensed version (for brevity) of selectionchanged event handler of a multiselectbox column.
if (e.newValue && e.newValue.length) {
var newValue = e.newValue;
console.log('e.newValue: ' + e.newValue);
filter.filters = [];
for (var i = 0, l = newValue.length; i < l; i++) {
filter.filters.push({field: field,operator: 'contains',value: newValue[i]});
}
kendoGrid.dataSource.filter(allFilters);
}
I noticed that when two filters are passed, e.newValue is "Warsaw" instead of an array - "[Vancouver, Warsaw]"
I spent lot of time troubleshooting why only Warsaw is applied to the data set.
Here's what I found out:
_raiseSelectionChanged function is what raises selection changed event. In that function, I noticed that it sets newValue and oldValue event arguments. To set newValue it uses "Value" function. Value function uses the below code to retrieve all the selected list items and return them.
else {
var selecteditems = this._getSelectedListItems();
return $.map(selecteditems, function (item) {
var obj = $(item).children("span").first();
return obj.attr("data-value");
}).join();
}
_getSelectedListItems function uses jQuery filter to fetch all list items that have css class ".selected"
_getSelectedListItems: function () {
return this._getAllValueListItems().filter("." + SELECTED);
},
There's a _select event which seems to be adding ".selected" class to list items. When I put a breakpoint on line 286, it is hitting it only once and that is for Warsaw. I am unable to understand why it is not getting called for Vancouver. I am out of clues and was wondering if anyone has pointers.
debug capture of _select function
Below is kendoMultiSelectBox user extension for your reference:
//MultiSelect - A user extension of KendoUI DropDownList widget.
(function ($) {
// shorten references to variables
var kendo = window.kendo,
ui = kendo.ui,
DropDownList = ui.DropDownList,
keys = kendo.keys,
SELECT = "select",
SELECTIONCHANGED = "selectionChanged",
SELECTED = "k-state-selected",
HIGHLIGHTED = "k-state-active",
CHECKBOX = "custom-multiselect-check-item",
SELECTALLITEM = "custom-multiselect-selectAll-item",
MULTISELECTPOPUP = "custom-multiselect-popup",
EMPTYSELECTION = "custom-multiselect-summary-empty";
var lineTemplate = '<input type="checkbox" name="#= {1} #" value="#= {0} #" class="' + CHECKBOX + '" />' +
'<span data-value="#= {0} #">#= {1} #</span>';
var MultiSelectBox = DropDownList.extend({
init: function (element, options) {
options.template = kendo.template(kendo.format(lineTemplate, options.dataValueField || 'data', options.dataTextField || 'data'));
// base call to widget initialization
DropDownList.fn.init.call(this, element, options);
var button = $('<input type="button" value="OK" style="float: right; padding: 3px; margin: 5px; cursor: pointer;" />');
button.on('click', $.proxy(this.close, this));
var popup = $(this.popup.element);
popup.append(button);
},
options: {
name: "MultiSelectBox",
index: -1,
showSelectAll: true,
preSummaryCount: 1, // number of items to show before summarising
emptySelectionLabel: '', // what to show when no items are selected
selectionChanged: null // provide callback to invoke when selection has changed
},
events: [
SELECTIONCHANGED
],
refresh: function () {
// base call
DropDownList.fn.refresh.call(this);
this._updateSummary();
$(this.popup.element).addClass(MULTISELECTPOPUP);
},
current: function (candidate) {
return this._current;
},
open: function () {
var self = this;
this._removeSelectAllItem();
this._addSelectAllItem();
if ($(this.ul).find('li').length > 6) {
$(this.popup.element).css({ 'padding-bottom': '30px' });
}
else {
$(this.popup.element).css({ 'padding-bottom': '0' });
}
DropDownList.fn.open.call(this);
//hook on to popup event because dropdown close does not
//fire consistently when user clicks on some other elements
//like a dataviz chart graphic
this.popup.one('close', $.proxy(this._onPopupClosed, this));
},
_onPopupClosed: function () {
this._removeSelectAllItem();
this._current = null;
this._raiseSelectionChanged();
},
_raiseSelectionChanged: function () {
var currentValue = this.value();
var currentValues = $.map((currentValue.length > 0 ? currentValue.split(",") : []).sort(), function (item) { return item.toString(); });
var oldValues = $.map((this._oldValue || []).sort(), function (item) { return item ? item.toString() : ''; });
// store for next pass
this._oldValue = $.map(currentValues, function (item) { return item.toString(); });
var changedArgs = { newValue: currentValues, oldValue: oldValues };
if (oldValues) {
var hasChanged = ($(oldValues).not(currentValues).length == 0 && $(currentValues).not(oldValues).length == 0) !== true;
if (hasChanged) {
//if (this.options.selectionChanged)
// this.options.selectionChanged(changedArgs);
this.trigger(SELECTIONCHANGED, changedArgs);
}
}
else if (currentValue.length > 0) {
//if (this.options.selectionChanged)
// this.options.selectionChanged(changedArgs);
this.trigger(SELECTIONCHANGED, changedArgs);
}
},
_addSelectAllItem: function () {
if (!this.options.showSelectAll) return;
var firstListItem = this.ul.children('li:first');
if (firstListItem.length > 0) {
this.selectAllListItem = $('<li tabindex="-1" role="option" unselectable="on" class="k-item ' + SELECTALLITEM + '"></li>').insertBefore(firstListItem);
// fake a data object to use for the template binding below
var selectAllData = {};
selectAllData[this.options.dataValueField || 'data'] = '*';
selectAllData[this.options.dataTextField || 'data'] = 'All';
this.selectAllListItem.html(this.options.template(selectAllData));
this._updateSelectAllItem();
this._makeUnselectable(); // required for IE8
}
},
_removeSelectAllItem: function () {
if (this.selectAllListItem) {
this.selectAllListItem.remove();
}
this.selectAllListItem = null;
},
_focus: function (li) {
if (this.popup.visible() && li && this.trigger(SELECT, { item: li })) {
this.close();
return;
}
this.select(li);
},
_keydown: function (e) {
// currently ignore Home and End keys
// can be added later
if (e.keyCode == kendo.keys.HOME ||
e.keyCode == kendo.keys.END) {
e.preventDefault();
return;
}
DropDownList.fn._keydown.call(this, e);
},
_keypress: function (e) {
// disable existing function
},
_move: function (e) {
var that = this,
key = e.keyCode,
ul = that.ul[0],
down = key === keys.DOWN,
pressed;
if (key === keys.UP || down) {
if (down) {
if (!that.popup.visible()) {
that.toggle(down);
}
if (!that._current) {
that._current = ul.firstChild;
} else {
that._current = ($(that._current)[0].nextSibling || that._current);
}
} else {
//up
// only if anything is highlighted
if (that._current) {
that._current = ($(that._current)[0].previousSibling || ul.firstChild);
}
}
if (that._current) {
that._scroll(that._current);
}
that._highlightCurrent();
e.preventDefault();
pressed = true;
} else {
pressed = DropDownList.fn._move.call(this, e);
}
return pressed;
},
selectAll: function () {
var unselectedItems = this._getUnselectedListItems();
this._selectItems(unselectedItems);
// todo: raise custom event
},
unselectAll: function () {
var selectedItems = this._getSelectedListItems();
this._selectItems(selectedItems); // will invert the selection
// todo: raise custom event
},
_selectItems: function (listItems) {
var that = this;
$.each(listItems, function (i, item) {
var idx = ui.List.inArray(item, that.ul[0]);
that.select(idx); // select OR unselect
});
},
_selectItem: function () {
// method override to prevent default selection of first item, done by normal dropdown
var that = this,
options = that.options,
useOptionIndex,
value;
useOptionIndex = that._isSelect && !that._initial && !options.value && options.index && !that._bound;
if (!useOptionIndex) {
value = that._selectedValue || options.value || that._accessor();
}
if (value) {
that.value(value);
} else if (that._bound === undefined) {
that.select(options.index);
}
},
_select: function (li) {
var that = this,
value,
text,
idx;
li = that._get(li);
if (li && li[0]) {
idx = ui.List.inArray(li[0], that.ul[0]);
if (idx > -1) {
if (li.hasClass(SELECTED)) {
li.removeClass(SELECTED);
that._uncheckItem(li);
if (this.selectAllListItem && li[0] === this.selectAllListItem[0]) {
this.unselectAll();
}
} else {
li.addClass(SELECTED);
that._checkItem(li);
if (this.selectAllListItem && li[0] === this.selectAllListItem[0]) {
this.selectAll();
}
}
if (this._open) {
that._current(li);
that._highlightCurrent();
}
var selecteditems = this._getSelectedListItems();
value = [];
text = [];
$.each(selecteditems, function (indx, item) {
var obj = $(item).children("span").first();
value.push(obj.attr("data-value"));
text.push(obj.text());
});
that._updateSummary(text);
that._updateSelectAllItem();
that._accessor(value, idx);
// todo: raise change event (add support for selectedIndex) if required
that._raiseSelectionChanged();
}
}
},
_getAllValueListItems: function () {
if (this.selectAllListItem) {
return this.ul.children("li").not(this.selectAllListItem[0]);
} else {
return this.ul.children("li");
}
},
_getSelectedListItems: function () {
return this._getAllValueListItems().filter("." + SELECTED);
},
_getUnselectedListItems: function () {
return this._getAllValueListItems().filter(":not(." + SELECTED + ")");
},
_getSelectedItemsText: function () {
var text = [];
var selecteditems = this._getSelectedListItems();
$.each(selecteditems, function (indx, item) {
var obj = $(item).children("span").first();
text.push(obj.text());
});
return text;
},
_updateSelectAllItem: function () {
if (!this.selectAllListItem) return;
// are all items selected?
if (this._getAllValueListItems().length == this._getSelectedListItems().length) {
this._checkItem(this.selectAllListItem);
this.selectAllListItem.addClass(SELECTED);
}
else {
this._uncheckItem(this.selectAllListItem);
this.selectAllListItem.removeClass(SELECTED);
}
},
_updateSummary: function (itemsText) {
if (!itemsText) {
itemsText = this._getSelectedItemsText();
}
if (itemsText.length == 0) {
this._inputWrapper.addClass(EMPTYSELECTION);
this.text(this.options.emptySelectionLabel);
return;
} else {
this._inputWrapper.removeClass(EMPTYSELECTION);
}
if (itemsText.length <= this.options.preSummaryCount) {
this._textAccessor(itemsText.join(", "));
}
else {
this._textAccessor(itemsText.length + ' selected');
}
},
_checkItem: function (itemContainer) {
if (!itemContainer) return;
itemContainer.children("input").prop("checked", true);
},
_uncheckItem: function (itemContainer) {
if (!itemContainer) return;
itemContainer.children("input").removeAttr("checked");
},
_isItemChecked: function (itemContainer) {
return itemContainer.children("input:checked").length > 0;
},
value: function (value) {
if(value != undefined)
console.log("value", value);
var that = this,
idx,
valuesList = [];
if (value !== undefined) {
if (!$.isArray(value)) {
valuesList.push(value);
this._oldValue = valuesList; // to allow for selectionChanged event
}
else {
valuesList = value;
this._oldValue = value; // to allow for selectionChanged event
}
// clear all selections first
$(that.ul[0]).children("li").removeClass(SELECTED);
$("input", that.ul[0]).removeAttr("checked");
$.each(valuesList, function (indx, item) {
var hasValue;
if (item !== null) {
item = item.toString();
}
that._selectedValue = item;
hasValue = value || (that.options.optionLabel && !that.element[0].disabled && value === "");
if (hasValue && that._fetchItems(value)) {
return;
}
idx = that._index(item);
if (idx > -1) {
that.select(
that.options.showSelectAll ? idx + 1 : idx
);
}
});
that._updateSummary();
}
else {
var selecteditems = this._getSelectedListItems();
return $.map(selecteditems, function (item) {
var obj = $(item).children("span").first();
return obj.attr("data-value");
}).join();
}
},
});
ui.plugin(MultiSelectBox);
})(jQuery);
UPDATE
I came across documentation for multiselectbox's select event that clearly states that the select event is not fired when an item is selected programmatically. Is it relevant to what I am trying to do? But why is it firing for one of the filters even though I am setting them programmatically?
enter link description here

Adjust the width of an element based on the width of another element

Please check the solution here:
https://stackoverflow.com/a/41686102/4180447
The above solution can be used to implement editable dropdown (select) element in Angular. However, the width of the element is assumed to be fixed. Now, we are implementing responsive design, and I need a way to adjust the width of an element based on the width of another element.
Basically, the implementation uses two elements and places them on top of each other. One element is the select element whose ID ends with _sel , and the other is the text element whose ID ends with _disp. The text element must be narrower than the drop-down element so that the drop-down arrow will be visible.
The width of the text element must be about 18px less than the width of the select element.
Is there a way to adjust the height of the text input the be 18px less than the size of the select element?
See snapshot below and related code to clarify the situation:
HTML:
<div class="select-editable stop-wrap" style="width: 265px; border:none">
<select type="text" id="exterior_finish_sel" editable-dropdown="exterior_finish" name="exterior_finish_sel"
ng-model="exterior_finish_sel" ng-options="o as o for o in ddlOptions.exterior_finish track by o" maxlength="80"
class="ng-valid ng-valid-maxlength ng-not-empty ng-dirty ng-valid-parse ng-touched" style="">
</select>
<input type="text" id="exterior_finish_disp" name="exterior_finish_disp" ng-model="exterior_finish_disp" style="width: 247px;"/>
<input type="text" id="exterior_finish" name="exterior_finish" ng-model="exterior_finish" ng-hide="true"/>
</div>
CSS:
.stop-wrap {
display: inline-block;
}
.select-editable {
position:relative;
background-color:white;
border:solid grey 1px;
width:120px;
height:25px;
vertical-align: middle;
margin-bottom: 5px;
}
.select-editable select {
position:absolute;
top:0px;
left:0px;
border:none;
width:118px;
margin:0;
}
.select-editable input {
position:absolute;
top:0px;
left:0px;
width:100px;
padding:1px;
border:none;
}
.select-editable select:focus, .select-editable input:focus {
outline:none;
}
I found the answer based on solution here:
https://stackoverflow.com/a/18743145/4180447
The jQuery plugin that will monitor changes on width/position:
jQuery.fn.onPositionChanged = function (trigger, millis) {
if (millis == null) millis = 100;
var o = $(this[0]); // our jquery object
if (o.length < 1) return o;
var lastPos = null;
var lastOff = null;
var lastWidth = null;
var lastOffWidth = null;
setInterval(function () {
if (o == null || o.length < 1) return o; // abort if element is non existend eny more
if (lastPos == null) lastPos = o.position();
if (lastOff == null) lastOff = o.offset();
if (lastWidth == null) lastWidth = o.width();
if (lastOffWidth == null) lastOffWidth = o[0].offsetWidth;
var newPos = o.position();
var newOff = o.offset();
var newWidth = o.width();
var newOffWidth = o[0].offsetWidth;
if (lastPos.top != newPos.top || lastPos.left != newPos.left) {
$(this).trigger('onPositionChanged', { lastPos: lastPos, newPos: newPos });
if (typeof (trigger) == "function") trigger(lastPos, newPos);
lastPos = o.position();
}
if (lastOff.top != newOff.top || lastOff.left != newOff.left) {
$(this).trigger('onPositionChanged', { lastOff: lastOff, newOff: newOff});
if (typeof (trigger) == "function") trigger(lastOff, newOff);
lastOff= o.offset();
}
if (lastWidth != newWidth) {
$(this).trigger('onPositionChanged', { lastWidth: lastWidth, newWidth: newWidth});
if (typeof (trigger) == "function") trigger(lastWidth, newWidth);
lastWidth= o.width();
}
if (lastOffWidth != newOffWidth) {
$(this).trigger('onPositionChanged', { lastOffWidth: lastOffWidth, newOffWidth: newOffWidth});
if (typeof (trigger) == "function") trigger(lastOffWidth, newOffWidth);
lastWidth= o.width();
}
}, millis);
return o;
};
The editable-dropdown directive below:
app.directive('editableDropdown', function ($timeout){
return {
link: function (scope, elemSel, attrs) {
//This is the hidden input, and will be used for data binding
var inpElemID = attrs.editableDropdown;
var inpElem;
//This is the display element and will be used for showing the selected value
var inpElemDispID = inpElemID + "_disp";
var inpElemDisp;
//The parameter 'elemSel' is the SELECT field
function initInpElem() {
//Get a reference to the hidden and displayed text field
if ($(elemSel).is("select")) {
inpElem = $('#' + inpElemID); //Hidden field
inpElemDisp = $('#' + inpElemDispID); //Displayed field
} else {
//This is in case the Dropdown is based on DATALIST which is not yet implemented
//In this case, the input element is actually the same as the dropdown field using DATALIST
inpElem = elemSel;
}
}
initInpElem();
function updateEditable(elm) {
initInpElem();
//Copy value from SELECT element to the INPUT Element
//Use NgModelController to copy value in order to trigger validation for 'inpElem'
var selectedValue = $(elm).children("option").filter(":selected").text();
//Update the hidden text field which is used to save the value to DB
angular.element(inpElem).controller('ngModel').$setViewValue(elm.val());
angular.element(inpElem).controller('ngModel').$render();
//Update the display text field based on the selection (text value)
angular.element(inpElemDisp).controller('ngModel').$setViewValue($(elm).find('option:selected').text());
angular.element(inpElemDisp).controller('ngModel').$render();
makeEditable(elm);
}
function makeEditable(selElm) {
//Allow edit text field if "other" is selected
initInpElem();
if ($(selElm).is("select")) {
//JIRA: NE-2995 - of option seletec starte with "other" then activate editable option
if (selElm.val().toLowerCase().startsWith("other")) {
//Make the display field editable
$(inpElemDisp).prop("readonly", false);
} else {
//Make the display field read-only
$(inpElemDisp).prop("readonly", true);
}
} else {
if (elm.value != "Other" && !$(elm).attr("keypressOff")) {
$(elm).keypress(function(event) {
console.log("keypress preventd")
event.preventDefault();
})
} else {
$(elm).off("keypress");
$(elm).attr("keypressOff", true);
console.log("keypress event removed")
}
}
}
function resizeElem() {
angular.element(document).ready(function() {
initInpElem();
$(inpElemDisp).width($(elemSel).outerWidth()-20);
})
}
angular.element(document).ready(function(){
initInpElem();
//When the display value changes, then update the hidden text field
inpElemDisp.change(function(){
angular.element(inpElem).controller('ngModel').$setViewValue(inpElemDisp.val());
angular.element(inpElem).controller('ngModel').$render();
});
makeEditable(elemSel);
});
//When field values are initialized, ensure the drop-down list and other fields are synchronized
scope.$on('event:force-model-update', function() {
initInpElem();
//Use the value of the hidden field which is saved in DB to update the values of the other fields
var selectedValue = $(elemSel).find('option[value="' + inpElem.val() + '"]').val();
var selectedText;
if (angular.isUndefined(selectedValue)) {
selectedText = inpElem.val();
} else {
//Update the selected value
if (angular.element(elemSel).controller('ngModel')) {
angular.element(elemSel).controller('ngModel').$setViewValue(selectedValue);
angular.element(elemSel).controller('ngModel').$render();
}
$(elemSel).find('option[value="' + inpElem.val() + '"]').attr('selected', 'selected');
selectedText = $(elemSel).find('option:selected').text()
}
//Update the display value
angular.element(inpElemDisp).controller('ngModel').$setViewValue(selectedText);
angular.element(inpElemDisp).controller('ngModel').$render();
});
$(elemSel).change(function () {
//Everytime the selected value is update, then change the display and hidden value
updateEditable(elemSel);
});
$(elemSel).onPositionChanged(function() {
resizeElem();
})
}
}
});
The above code needs improvement to monitor changes only to the width. I will do that in the next sprint.
Tarek

Automatic text detection on contenteditable div using angular js

what is the best way to do following using angular js
when writing text on a contenteditable div need to detect special word like ' {{FULL_NAME}} ' and covert to tag with pre-deifined constant words
example - if some one write
' His name is {{FULL_NAME}} '
should be instantly convert to ' His name is john smith '
Here is a demo plunker: http://plnkr.co/edit/GKYxXiDKv7fBeaE7rrZA?p=preview
Service:
app.factory('interpolator', function(){
var dict = { .... };
return function(str){
return (str || "").replace(/\{\{([^\}]+)\}\}/g, function(all, match){
return dict[match.trim().toLowerCase()] || all;
});
};
});
Directive:
app.directive('edit',[ 'interpolator', function(interpolator){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
element.on('blur', function(e) {
scope.$apply(function() {
var content = interpolator(element.text());
element.text(content);
ngModel.$setViewValue(content);
});
});
ngModel.$formatters.push(interpolator);
ngModel.$render = function() {
element.text(ngModel.$viewValue);
ngModel.$setViewValue(ngModel.$viewValue);
};
}
};
}]);
Here's an example using simple DOM methods, based on other answers I've provided on Stack Overflow. It also uses Rangy to save and restore the selection while doing the substitutions so that the caret does not move.
Demo:
http://jsbin.com/zuvevocu/2
Code:
var editorEl = document.getElementById("editor");
var keyTimer = null, keyDelay = 100;
function createKeyword(matchedTextNode) {
var el = document.createElement("b");
el.style.backgroundColor = "yellow";
el.style.padding = "2px";
el.contentEditable = false;
var matchedKeyword = matchedTextNode.data.slice(1, -1); // Remove the curly brackets
matchedTextNode.data = (matchedKeyword.toLowerCase() == "name") ? "John Smith" : "REPLACEMENT FOR " + matchedKeyword;
el.appendChild(matchedTextNode);
return el;
}
function surroundInElement(el, regex, surrounderCreateFunc) {
// script and style elements are left alone
if (!/^(script|style)$/.test(el.tagName)) {
var child = el.lastChild;
while (child) {
if (child.nodeType == 1) {
surroundInElement(child, regex, surrounderCreateFunc);
} else if (child.nodeType == 3) {
surroundMatchingText(child, regex, surrounderCreateFunc);
}
child = child.previousSibling;
}
}
}
function surroundMatchingText(textNode, regex, surrounderCreateFunc) {
var parent = textNode.parentNode;
var result, surroundingNode, matchedTextNode, matchLength, matchedText;
while ( textNode && (result = regex.exec(textNode.data)) ) {
matchedTextNode = textNode.splitText(result.index);
matchedText = result[0];
matchLength = matchedText.length;
textNode = (matchedTextNode.length > matchLength) ?
matchedTextNode.splitText(matchLength) : null;
surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true));
parent.insertBefore(surroundingNode, matchedTextNode);
parent.removeChild(matchedTextNode);
}
}
function updateKeywords() {
var savedSelection = rangy.saveSelection();
surroundInElement(editorEl, /\{\w+\}/, createKeyword);
rangy.restoreSelection(savedSelection);
}
function keyUpHandler() {
if (keyTimer) {
window.clearTimeout(keyTimer);
}
keyTimer = window.setTimeout(function() {
updateKeywords();
keyTimer = null;
}, keyDelay);
}
editorEl.onkeyup = keyUpHandler;
Related:
https://stackoverflow.com/a/5905413/96100
https://stackoverflow.com/a/4026684/96100
https://stackoverflow.com/a/4045531/96100

Polyfill HTML5 form attribute (for input fields)

This is the markup I use:
<input type="text" form="myform" name="inp1" />
<form id="myform" name="myform">
...
</form>
Now I realized that it does not work for old IE and therefore I am searching for a HTML 5 polyfill.
Anyone aware of a certain polyfill which covers this HTML5 feature?
I wrote this polyfill to emulate such feature by duplicating fields upon form submission, tested in IE6 and it worked fine.
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var sampleElement = $('[form]').get(0);
var isIE11 = !(window.ActiveXObject) && "ActiveXObject" in window;
if (sampleElement && window.HTMLFormElement && (sampleElement.form instanceof HTMLFormElement || sampleElement instanceof window.HTMLFormElement) && !isIE11) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e) {
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// append data to form
$(this).appendField(data);
}).each(function() {
var form = this,
$fields = $('[form=' + this.id + ']');
$fields.filter('button, input').filter('[type=reset],[type=submit]').click(function() {
var type = this.type.toLowerCase();
if (type === 'reset') {
// reset form
form.reset();
// for elements outside form
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
} else if (type.match(/^submit|image$/i)) {
$(form).appendField({name: this.name, value: this.value}).submit();
}
});
});
})(jQuery);
The polyfill above doesn't take into account the Edge browser. I have amended it to use feature detection, which I have tested in IE7+, Edge, Firefox (mobile/desktop), Chrome (mobile/desktop), Safari (mobile/desktop), and Android browser 4.0.
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var SAMPLE_FORM_NAME = "html-5-polyfill-test";
var sampleForm = $("<form id='" + SAMPLE_FORM_NAME + "'/>");
var sampleFormAndHiddenInput = sampleForm.add($("<input type='hidden' form='" + SAMPLE_FORM_NAME + "'/>"));
sampleFormAndHiddenInput.prependTo('body');
var sampleElementFound = sampleForm[0].elements[0];
sampleFormAndHiddenInput.remove();
if (sampleElementFound) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e) {
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// append data to form
$(this).appendField(data);
}).each(function() {
var form = this,
$fields = $('[form=' + this.id + ']');
$fields.filter('button, input').filter('[type=reset],[type=submit]').click(function() {
var type = this.type.toLowerCase();
if (type === 'reset') {
// reset form
form.reset();
// for elements outside form
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
} else if (type.match(/^submit|image$/i)) {
$(form).appendField({name: this.name, value: this.value}).submit();
}
});
});
})(jQuery);
I improved patstuart's polyfill, such that:
a form can now be submitted several times, e.g. when using the target attribute (external fields were duplicated previously)
reset buttons now work properly
Here it is:
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var SAMPLE_FORM_NAME = "html-5-polyfill-test";
var sampleForm = $("<form id='" + SAMPLE_FORM_NAME + "'/>");
var sampleFormAndHiddenInput = sampleForm.add($("<input type='hidden' form='" + SAMPLE_FORM_NAME + "'/>"));
sampleFormAndHiddenInput.prependTo('body');
var sampleElementFound = sampleForm[0].elements[0];
sampleFormAndHiddenInput.remove();
if (sampleElementFound) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
var CLASS_NAME_POLYFILL_MARKER = "html-5-polyfill-form-attr-marker";
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.attr('class', CLASS_NAME_POLYFILL_MARKER)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e, origSubmit) {
// clean up form from last submit
$('.'+CLASS_NAME_POLYFILL_MARKER, this).remove();
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// add data from external submit, if needed:
if (origSubmit && origSubmit.name)
data.push({name: origSubmit.name, value: origSubmit.value})
// append data to form
$(this).appendField(data);
})
//submit and reset behaviour
$('button[type=reset], input[type=reset]').click(function() {
//extend reset buttons to fields with matching form attribute
// reset form
var formId = $(this).attr("form");
var formJq = $('#'+formId);
if (formJq.length)
formJq[0].reset();
// for elements outside form
if (!formId)
formId = $(this).closest("form").attr("id");
$fields = $('[form=' + formId + ']');
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
});
$('button[type=submit], input[type=submit], input[type=image]').click(function() {
var formId = $(this).attr("form") || $(this).closest("form").attr("id");
$('#'+formId).trigger('submit', this); //send clicked submit as extra parameter
});
})(jQuery);
after reading thru the docs of webshim it seems it has a polyfill for that.
http://afarkas.github.io/webshim/demos/demos/webforms.html
I made a vanilla JavaScript polyfill based on the above polyfills and uploaded it on GitHub: https://github.com/Ununnilium/form-attribute-polyfill.
I also added a custom event to handle the case when submit is processed by JavaScript and not directly by the browser. I tested the code only shortly with IE 11, so please check it yourself before use. The polling should maybe be replaced by a more efficient detection function.
function browserNeedsPolyfill() {
var TEST_FORM_NAME = "form-attribute-polyfill-test";
var testForm = document.createElement("form");
testForm.setAttribute("id", TEST_FORM_NAME);
testForm.setAttribute("type", "hidden");
var testInput = document.createElement("input");
testInput.setAttribute("type", "hidden");
testInput.setAttribute("form", TEST_FORM_NAME);
testForm.appendChild(testInput);
document.body.appendChild(testInput);
document.body.appendChild(testForm);
var sampleElementFound = testForm.elements.length === 1;
document.body.removeChild(testInput);
document.body.removeChild(testForm);
return !sampleElementFound;
}
// Ideas from jQuery form attribute polyfill https://stackoverflow.com/a/26696165/2372674
function executeFormPolyfill() {
function appendDataToForm(data, form) {
Object.keys(data).forEach(function(name) {
var inputElem = document.createElement("input");
inputElem.setAttribute("type", "hidden");
inputElem.setAttribute("name", name);
inputElem.value = data[name];
form.appendChild(inputElem);
});
}
var forms = document.body.querySelectorAll("form[id]");
Array.prototype.forEach.call(forms, function (form) {
var fields = document.querySelectorAll('[form="' + form.id + '"]');
var dataFields = [];
Array.prototype.forEach.call(fields, function (field) {
if (field.disabled === false && field.hasAttribute("name")) {
dataFields.push(field);
}
});
Array.prototype.forEach.call(fields, function (field) {
if (field.type === "reset") {
field.addEventListener("click", function () {
form.reset();
Array.prototype.forEach.call(dataFields, function (dataField) {
if (dataField.nodeName === "SELECT") {
Array.prototype.forEach.call(dataField.querySelectorAll('option'), function (option) {
option.selected = option.defaultSelected;
});
} else {
dataField.value = dataField.defaultValue;
dataField.checked = dataField.defaultChecked;
}
});
});
} else if (field.type === "submit" || field.type === "image") {
field.addEventListener("click", function () {
var obj = {};
obj[field.name] = field.value;
appendDataToForm(obj, form);
form.dispatchEvent(eventToDispatch);
});
}
});
form.addEventListener("submit", function () {
var data = {};
Array.prototype.forEach.call(dataFields, function (dataField) {
data[dataField.name] = dataField.value;
});
appendDataToForm(data, form);
});
});
}
// Poll for new forms and execute polyfill for them
function detectedNewForms() {
var ALREADY_DETECTED_CLASS = 'form-already-detected';
var newForms = document.querySelectorAll('form:not([class="' + ALREADY_DETECTED_CLASS + '"])');
if (newForms.length !== 0) {
Array.prototype.forEach.call(newForms, function (form) {
form.className += ALREADY_DETECTED_CLASS;
});
executeFormPolyfill();
}
setTimeout(detectedNewForms, 100);
}
// Source: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
function polyfillCustomEvent() {
if (typeof window.CustomEvent === "function") {
return false;
}
function CustomEvent(event, params) {
params = params || {bubbles: false, cancelable: false, detail: undefined};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
}
if (browserNeedsPolyfill()) {
polyfillCustomEvent(); // IE is missing CustomEvent
// This workaround is needed if submit is handled by JavaScript instead the browser itself
// Source: https://stackoverflow.com/a/35155789/2372674
var eventToDispatch = new CustomEvent("submit", {"bubbles": true, "cancelable": true});
detectedNewForms(); // Poll for new forms and execute form attribute polyfill for new forms
}
I take some time to send an update for this polyfill because it doesn't work with MS Edge.
I add 2 line to fix it :
var isEdge = navigator.userAgent.indexOf("Edge");
if (sampleElement && window.HTMLFormElement && sampleElement.form instanceof HTMLFormElement && !isIE11 && isEdge == -1) {
// browser supports it, no need to fix
return;
}
UPDATE: Edge now support it:
https://caniuse.com/#feat=form-attribute

How to support placeholder attribute in IE8 and 9

I have a small issue, the placeholder attribute for input boxes is not supported in IE 8-9.
What is the best way to make this support in my project (ASP Net). I am using jQuery.
Need I use some other external tools for it?
Is http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html a good solution?
You could use this jQuery plugin:
https://github.com/mathiasbynens/jquery-placeholder
But your link seems to be also a good solution.
You can use any one of these polyfills:
https://github.com/jamesallardice/Placeholders.js (doesn't support password fields)
https://github.com/chemerisuk/better-placeholder-polyfill
These scripts will add support for the placeholder attribute in browsers that do not support it, and they do not require jQuery!
the $.Browser.msie is not on the latest JQuery anymore...
you have to use the $.support
like below:
<script>
(function ($) {
$.support.placeholder = ('placeholder' in document.createElement('input'));
})(jQuery);
//fix for IE7 and IE8
$(function () {
if (!$.support.placeholder) {
$("[placeholder]").focus(function () {
if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
}).blur(function () {
if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function () {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
});
});
}
});
</script>
if you use jquery you can do like this. from this site Placeholder with Jquery
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
these are the alternate links
Placeholder jquery library
HTML5 polyfills -- go for placeholder section
I had compatibility issues with several plugins I tried, this seems to me to be the simplest way of supporting placeholders on text inputs:
function placeholders(){
//On Focus
$(":text").focus(function(){
//Check to see if the user has modified the input, if not then remove the placeholder text
if($(this).val() == $(this).attr("placeholder")){
$(this).val("");
}
});
//On Blur
$(":text").blur(function(){
//Check to see if the use has modified the input, if not then populate the placeholder back into the input
if( $(this).val() == ""){
$(this).val($(this).attr("placeholder"));
}
});
}
$(function(){
if($.browser.msie && $.browser.version <= 9){
$("[placeholder]").focus(function(){
if($(this).val()==$(this).attr("placeholder")) $(this).val("");
}).blur(function(){
if($(this).val()=="") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function() {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
})
});
}
});
try this
I use thisone, it's only Javascript.
I simply have an input element with a value, and when the user clicks on the input element, it changes it to an input element without a value.
You can easily change the color of the text using CSS. The color of the placeholder is the color in the id #IEinput, and the color your typed text will be is the color in the id #email. Don't use getElementsByClassName, because the versions of IE that don't support a placeholder, don't support getElementsByClassName either!
You can use a placeholder in a password input by setting the type of the original password input to text.
Tinker: http://tinker.io/4f7c5/1
- JSfiddle servers are down!
*sorry for my bad english
JAVASCRIPT
function removeValue() {
document.getElementById('mailcontainer')
.innerHTML = "<input id=\"email\" type=\"text\" name=\"mail\">";
document.getElementById('email').focus(); }
HTML
<span id="mailcontainer">
<input id="IEinput" onfocus="removeValue()" type="text" name="mail" value="mail">
</span>
For others landing here. This is what worked for me:
//jquery polyfill for showing place holders in IE9
$('[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.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
Just add this in you script.js file.
Courtesy of http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
Since most solutions uses jQuery or are not this satisfying as I wished it to be I wrote a snippet for myself for mootools.
function fix_placeholder(container){
if(container == null) container = document.body;
if(!('placeholder' in document.createElement('input'))){
var inputs = container.getElements('input');
Array.each(inputs, function(input){
var type = input.get('type');
if(type == 'text' || type == 'password'){
var placeholder = input.get('placeholder');
input.set('value', placeholder);
input.addClass('__placeholder');
if(!input.hasEvent('focus', placeholder_focus)){
input.addEvent('focus', placeholder_focus);
}
if(!input.hasEvent('blur', placeholder_blur)){
input.addEvent('blur', placeholder_blur);
}
}
});
}
}
function placeholder_focus(){
var input = $(this);
if(input.get('class').contains('__placeholder') || input.get('value') == ''){
input.removeClass('__placeholder');
input.set('value', '');
}
}
function placeholder_blur(){
var input = $(this);
if(input.get('value') == ''){
input.addClass('__placeholder');
input.set('value', input.get('placeholder'));
}
}
I confess that it looks a bit more MORE than others but it works fine.
__placeholder is a ccs-class to make the color of the placeholder text fancy.
I used the fix_placeholder in window.addEvent('domready', ... and for any additinally added code like popups.
Hope you like it.
Kind regards.
I used the code of this link
http://dipaksblogonline.blogspot.com/2012/02/html5-placeholder-in-ie7-and-ie8-fixed.html
But in browser detection I used:
if (navigator.userAgent.indexOf('MSIE') > -1) {
//Your placeholder support code here...
}
<input type="text" name="Name" value="Name" onfocus="this.value = ''" onblur=" if(this.value = '') { value = 'Name'}" />
Add the below code and it will be done.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="https://code.google.com/p/jquery-placeholder-js/source/browse/trunk/jquery.placeholder.1.3.min.js?r=6"></script>
<script type="text/javascript">
// Mock client code for testing purpose
$(function(){
// Client should be able to add another change event to the textfield
$("input[name='input1']").blur(function(){ alert("Custom event triggered."); });
// Client should be able to set the field's styles, without affecting place holder
$("textarea[name='input4']").css("color", "red");
// Initialize placeholder
$.Placeholder.init();
// or try initialize with parameter
//$.Placeholder.init({ color : 'rgb(255, 255, 0)' });
// call this before form submit if you are submitting by JS
//$.Placeholder.cleanBeforeSubmit();
});
</script>
Download the full code and demo from https://code.google.com/p/jquery-placeholder-js/downloads/detail?name=jquery.placeholder.1.3.zip
Here is a javascript function that will create placeholders for IE 8 and below and it works for passwords as well:
/* Function to add placeholders to form elements on IE 8 and below */
function add_placeholders(fm) {
for (var e = 0; e < document.fm.elements.length; e++) {
if (fm.elements[e].placeholder != undefined &&
document.createElement("input").placeholder == undefined) { // IE 8 and below
fm.elements[e].style.background = "transparent";
var el = document.createElement("span");
el.innerHTML = fm.elements[e].placeholder;
el.style.position = "absolute";
el.style.padding = "2px;";
el.style.zIndex = "-1";
el.style.color = "#999999";
fm.elements[e].parentNode.insertBefore(el, fm.elements[e]);
fm.elements[e].onfocus = function() {
this.style.background = "yellow";
}
fm.elements[e].onblur = function() {
if (this.value == "") this.style.background = "transparent";
else this.style.background = "white";
}
}
}
}
add_placeholders(document.getElementById('fm'))
<form id="fm">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<textarea name="description" placeholder="Description"></textarea>
</form>
<script>
if ($.browser.msie) {
$('input[placeholder]').each(function() {
var input = $(this);
$(input).val(input.attr('placeholder'));
$(input).focus(function() {
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
$(input).blur(function() {
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.val(input.attr('placeholder'));
}
});
});
}
;
</script>