Jquery function strange behaviour - javascript

I found following function to enable placeholder like effect on browsers like IE6-9.
The problem is placeholder appears after first-time focusing. There is no initial value. Input boxes are just blank after page loading.
And another thing is, as on tutorial I created .placeholder class and set color to grey. It sets inputs color to light grey and doesn't change to black while user types.
var isInputSupported = 'placeholder' in document.createElement('input');
var isTextareaSupported = 'placeholder' in document.createElement('textarea');
if (!isInputSupported || !isTextareaSupported) {
$('[placeholder]').focus(function () {
var input = $(this);
if (input.val() == input.attr('placeholder') && input.data('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function () {
var input = $(this);
if (input.val() == '') {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
input.data('placeholder', true);
} else {
input.data('placeholder', false);
}
}).blur().parents('form').submit(function () {
$(this).find('[placeholder]').each(function () {
var input = $(this);
if (input.val() == input.attr('placeholder') && input.data('placeholder')) {
input.val('');
}
})
});
}
Any suggestions?

To address the problem of the placeholders not showing up initially, you need to initialize each of them when the page loads, something like this:
$('[placeholder]').each(function(){
var $this = $(this);
if($this.val() == ''){
$this.val($this.data('placeholder')).addClass('placeholder');
}
});
The problem with the text color is that the .placeholder class is being added/removed on focus or blur, not when the user types. You need an additional event handler for keyup that removes the .placeholder class (this also includes my snippet from above):
var isInputSupported = 'placeholder' in document.createElement('input');
var isTextareaSupported = 'placeholder' in document.createElement('textarea');
if (!isInputSupported || !isTextareaSupported) {
$('[placeholder]').each(function(){
var $this = $(this);
if($this.val() == ''){
$this.val($this.data('placeholder')).addClass('placeholder');
}
});
$('[placeholder]').focus(function () {
var input = $(this);
if (input.val() == input.attr('placeholder') && input.data('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).on('keyup', function(){
$(this).removeClass('placeholder')
}).blur(function () {
var input = $(this);
if (input.val() == '') {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
input.data('placeholder', true);
} else {
input.data('placeholder', false);
}
}).blur().parents('form').submit(function () {
$(this).find('[placeholder]').each(function () {
var input = $(this);
if (input.val() == input.attr('placeholder') && input.data('placeholder')) {
input.val('');
}
})
});
}

Related

CSS Float Form Pattern for WooCommerce Forms

I'm attempting to implement the float label pattern (https://webdesign.tutsplus.com/articles/implementing-the-float-label-form-pattern--webdesign-16407) for my WooCommerce forms.
The checkout from is here - https://dev.joshkern.co/checkout/.
You'll first need to add a product/service from here - https://dev.joshkern.co/wordpress-maintenance/. You'll see the form isn't working as it should. What am I missing?
This is my javascript:
(function($) {
$(document).ready(function(){
// Test for placeholder support
$.support.placeholder = (function(){
var i = document.createElement('input');
return 'placeholder' in i;
})();
// Hide labels on page load if placeholders are supported
if ($.support.placeholder) {
$('.woocommerce form .form-row').each(function(){
$(this).addClass('js-hide-label');
});
$('.woocommerce form .form-row').find('input, textarea').on('keyup blur focus', function(e){
// Cache our selectors
var $this = $(this),
$parent = $this.parent();
// Add or remove classes
if (e.type == 'keyup') {
if ($this.val() == '') {
$parent.addClass('js-hide-label');
}
else {
$parent.removeClass('js-hide-label');
}
}
else if (e.type == 'blur') {
if( $this.val() == '' ) {
$parent.addClass('js-hide-label');
}
else {
$parent.removeClass('js-hide-label').addClass('js-unhighlight-label');
}
}
else if (e.type == 'focus') {
if( $this.val() !== '' ) {
$parent.removeClass('js-unhighlight-label');
}
}
});
}
});
})(jQuery);

Placeholder is showing like dots insted of placeholder text(Default text)

Placeholder is not working in below IE10 browsers, meanwhile i wrote following code it is working fine.
But problem is in password field it shows dots instead of placeholder text. Please find the attached screen shot.
Here is my code, could you please help is there any solution for fixing the password field placeholder visible.
//Default text in login page.
(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("login").submit(function () {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
});
});
}
});![enter image description here][1]
Use this below, it will help you
$(function () {
var input = document.createElement("input");
if (('placeholder' in input) == false) {
$('[placeholder]').focus(function () {
var i = $(this);
if (i.val() == i.attr('placeholder')) {
i.val('').removeClass('placeholder');
if (i.hasClass('password')) {
i.removeClass('password');
this.type = 'password';
}
}
}).blur(function () {
var i = $(this);
if (i.val() == '' || i.val() == i.attr('placeholder')) {
if (this.type == 'password') {
i.addClass('password');
this.type = 'text';
}
i.addClass('placeholder').val(i.attr('placeholder'));
}
}).blur().parents('form').submit(function () {
$(this).find('[placeholder]').each(function () {
var i = $(this);
if (i.val() == i.attr('placeholder'))
i.val('');
})
});
}
});

Prevent submit until all required fields (input,select..) are populated

How can I prevent my form from submitting until all required fields are populated? Required fields could be input, select, etc.
Below is my current code which is not working. Basically after I click on the submit button I would like to iterate through each field in the form which has tag='required' and if all fields are populated/selected then allow form submit.
Thanks.
$("#submitButton").click(function (e) {
var submit = false;
var count = 0;
$('#Form input, #Form select').each(function () {
var id = $(this).attr('id');
var value = $('#' + id).val();
var tagValue = $('#' + id).attr('tag');
var isDisabled = $('#' + id).is(':disabled');
if (isDisabled == false) {
if ($('#' + id).is(':visible')) {
if (tagValue == 'required') {
if (id == 'email') {
validateEmail('#' + id);
}
if (id == 'phone') {
validatePhone('#' + id);
}
if ($('#' + id).hasClass("currency")) {
validateCurrency('#' + id);
}
if ($('#' + id).is('select')) {
if (value == '' || value == 'Unknown' || value == 'unassigned' || value == null) {
$('#' + id).css({
'border': '1px solid #F70D1A'
});
}
}
else if (value == "") {
$('#' + id).css({
'border': '1px solid #F70D1A'
});
}
if (value == '' || value == 'Unknown' || value == 'unassigned' || value == null) {
submit = false;
} else {
submit = true;
}
}
}
}
});
if (!submit) {
e.preventDefault();
}
});
Rather than attaching this event to the button click, you should attach it to the form on submit:
$('#Form').on('submit', function (e) {
//-- your current code should work fine, put it here
});
I went ahead and cleaned up your method:
$("#Form").on('submit', function (e) {
var submit = true;
//-- use find+filter to reduce the set of matched elements
$(this).find('input, select').filter('[tag="required"]:visible:enabled').each(function () {
var $this = $(this),
value = $this.val();
//-- switch for unique flags
switch ($this.attr('id')) {
case 'email': validateEmail($this); break;
case 'phone': validatePhone($this); break;
}
//-- continue parsing non-unique flags
if ($this.hasClass('currency')) validateCurrency($this);
if (!value || value === 'Unknown' || value === 'unassigned') {
$this.css('border', '1px solid #F70D1A');
submit = false;
}
});
if (!submit) {
e.preventDefault();
}
});
Things to note:
I removed all of the unnecessary ID-based lookups. This is a huge performance hit, and should be reduced to a single $(this) lookup which you should reuse.
I am currently passing $this to each validate method, so they will have to be updated accordingly.
Rather than iterating through all select/input fields, I reduced the matched elements first, cutting down on unnecessary code.
I simplified your logic to the best of my understanding based on the code provided.
I switched the method used on the submit flag. It now starts out as valid and will be set to false if any item fails the check.
$('#Form').on('submit', function (e) {
$.each(this.find("[tag='required']"),function(i,item)
{
validation logic goes here.
....
}
)});

KeyPress doesn't return false in IE8

Im trying to prevent user to enter a space " " with KeyPress() using jQuery. it's work fine on all browser except IE8.
Here is my code:
$("<input type='text'>")
.attr( 'placeholder', opts.addTagPrompt )
.keypress( function(e) {
var $this = $(this),
pressed = e.which;
for ( i in opts.delimiters ) {
if (pressed == opts.delimiters[i]) {
if($this.val().indexOf(";",0) > 0)
{
var list = $this.val().split(';');
}else{
var list = $this.val().split(',');
}
for(var i in list){
self.add( list[i] );
}
e.preventDefault();
return false;
}
}
})
Update 1:
it's a plugin for tagify if user click space or Enter or Comma it's should return false and chance Css for the selected input.
(function ($) {
$.widget("ui.tagify", {
options: {
delimiters: [13, 32, 44], // what user can type to complete a tag in char codes: [enter], [space], [comma]
outputDelimiter: ',', // delimiter for tags in original input field
cssClass: 'tagify-container', // CSS class to style the tagify div and tags, see stylesheet
addTagPrompt: 'enter an email address' // placeholder text
},
_create: function() {
var self = this,
el = self.element,
opts = self.options;
this.tags = [];
var ctrlDown = false;
// hide text field and replace with a div that contains it's own input field for entering tags
this.tagInput = $("<input type='text'>")
.attr( 'placeholder', opts.addTagPrompt )
.keypress( function(e) {
var $this = $(this),
pressed = e.which;
for ( i in opts.delimiters ) {
if (pressed == opts.delimiters[i]) {
if($this.val().indexOf(";",0) > 0)
{
var list = $this.val().split(';');
}else{
var list = $this.val().split(',');
}
for(var i in list){
self.add( list[i] );
}
e.preventDefault();
return false;
}
}
})
// Ctrl+V Detection
.keydown(function(e)
{
if (e.keyCode == 17) ctrlDown = true;
})
.keyup(function(e)
{
if (e.keyCode == 17) ctrlDown = false;
})
.keyup(function(e)
{
var $this = $(this);
console.log($this.val());
if (ctrlDown && (e.keyCode == 86) ) {
if($this.val().indexOf(";",0) > 0)
{
var list = $this.val().split(';');
}else{
var list = $this.val().split(',');
}
var name_fix = "";
for(var i in list){
console.log(list[i]);
if(!checkEmail(list[i])){
name_fix = list[i]+", ";
}else{
if (name_fix != "") {
self.add( name_fix+list[i] );
name_fix = "";
}else{
self.add( list[i] );
}
}
}
e.preventDefault();
return false;
}
})
.keydown( function(e) {
var $this = $(this),
pressed = e.which;
// if backspace is hit with no input, remove the last tag
if (pressed == 8) { // backspace
if ( $this.val() == "" )
{
self.remove();
return false;
}
return;
}
});
this.tagDiv = $("<div></div>")
.addClass( opts.cssClass )
.click( function() {
$(this).children('input').focus();
})
.append( this.tagInput )
.insertAfter( el.hide() );
// if the field isn't empty, parse the field for tags, and prepopulate existing tags
var initVal = $.trim( el.val() );
if ( initVal ) {
var initTags = initVal.split( opts.outputDelimiter );
$.each( initTags, function(i, tag) {
self.add( tag );
});
}
},
Any one know how to fix that ?? thanks in advance.

How to refactor this code block to be simple and dynamic?

$(document).ready(function() {
$('.watermark').focus(function() {
if (this.className == 'watermark')
{
this.className = '';
this.value = '';
}
});
$('.watermark').blur(function() {
if (this.value == '')
{
this.className = 'watermark';
this.value = 'Type here';
}
});
});
I have this block of code that works perfectly except that it is not dynamic. I was wondering if there was an elegant way to reset the value to the original dynamically. I was thinking that maybe if you defined the original text in its ID or some other sort of attribute you could reset it that way.. or maybe you could use variables or arrays or tuples. What does SO think is the best way of doing it?
How about storing the value into some other attribute of the input?
$(document).ready(function() {
$('.watermark').focus(function() {
if (this.className == 'watermark')
{
this.className = '';
this.title = this.value;
this.value = '';
}
});
$('.watermark').blur(function() {
if (this.value == '')
{
this.className = 'watermark';
this.value = this.title;
}
});
});
In this scenario i prefer to use html5(placeholder attrinute) with javascript fall back.
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
$(document).ready(function() {
if (!supports_input_placeholder())
{
$('input').each(function(){
$(this).val($(this).attr('placeholder'))
});
$('input').focus(function() {
if (this.className == 'watermark')
{
this.className = '';
this.value = '';
}
});
$('input').blur(function() {
if (this.value == '')
{
this.className = 'watermark';
this.value = $(this).attr('placeholder');
}
});
}
});
This script will detect if native placeholder is available if not it will take text from placeholder attribute and simulate it.
You can just store it in a variable if it's scoped to each element:
$(function() {
$('.watermark').each(function() {
var lead = $(this).val();
$(this).focus(function() {
if ($(this).val() == lead) $(this).val('');
}).blur(function() {
if ($(this).val() == '') $(this).val(lead);
});
});
});

Categories