I'm trying to improve myself by working on codes. I can understand its normal state without any problems. In the sample code below, jquery, value reading, value assignment and if-else queries are nested. I could not get the code in a meaningful readable way. Can anyone write the code below in a simple expanded readable format?
$('.input-required input, .input-required select, .input-required textarea').on('focusin keyup', function () {
var inputSpan = $(this).parent().find('span').text();
$(this).val() != inputSpan && '' != $(this).val() && $(this).parent().find('span').addClass('input-style-1-active').removeClass('input-style-1-inactive'),
'' === $(this).val() && $(this).parent().find('span').removeClass('input-style-1-inactive input-style-1-active')
});
$('.input-required input, .input-required select, .input-required textarea').on('focusout', function () {
$(this).parent().find('span').text();
'' === $(this).val() && $(this).parent().find('span').removeClass('input-style-1-inactive input-style-1-active'),
$(this).parent().find('span').addClass('input-style-1-inactive')
});
The extended version of the first code block is correct as below?
$('.input-required input, .input-required select, .input-required textarea').on('focusin keyup', function () {
var inputSpan = $(this).parent().find('span').text();
if(($(this).val() != inputSpan) && ('' != $(this).val())){
$(this).parent().find('span').addClass('input-style-1-active').removeClass('input-style-1-inactive');
}else{
$(this).parent().find('span').removeClass('input-style-1-inactive input-style-1-active');
}
});
Whoever wrote that did not write it with maintenance in mind. Is it generated code by some tool?
I would think it could be condensed to
$(':input.input-required').on('input focusout', function (e) {
let $inputSpan = $(this).parent().find('span'),
text = $inputSpan.text(),
val = $(this).val();
if (val && val != text) {
$inputSpan
.addClass('input-style-1-active')
.removeClass('input-style-1-inactive')
}
else {
$inputSpan
.removeClass('input-style-1-active')
.addClass('input-style-1-inactive')
}
});
Which may be even more readable with toggleClass
Related
I am trying to use one of the IE9 IE8 placeholder solutions, but i have an error showing in IE9 test setup with the code. The solution i am using is clearly working for many people according to the comments and updates in github, but I have a fundamental problem getting the code recognised.
I have this line in my page header, which should allow me to use jquery. Indeed i am running other jquery functions and they seem to be working:
<!-- Javascript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Also in the head i have this (again all the other functions in my myjs.js are showing in developer tools and are available as required):
<!-- my java code link -->
<script src="/js/myjs.js"></script>
The function that i am using for the placeholder solution is this one:
placeholderSupport = ("placeholder" in document.createElement("input"));
if (!placeholderSupport) {
//This browser does not support the placeholder attribute
//use javascript instead
$('[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().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() === input.attr('placeholder')) {
input.val('');
}
})
});
}
The error that i am getting from IE9 developer tools is this:
Invalid App Id: Must be a number or numeric string representing the application id.
The error is showing on the line of code that looks like this, specifically the dollar sign:
$('[placeholder]').focus(function() {
From my reading I thought that the $ start was a function of the jquery library, which i beleive to be present and working, but i am obviously missing a trick. Can anybody help please. Thanks for any guidance.
Try this code, It works IE8+
UPDATED: to match all inputs and textarea
// This adds 'placeholder' to the items listed in the jQuery .support object.
jQuery(function () {
jQuery.support.placeholder = false;
test = document.createElement('input');
if ('placeholder' in test) jQuery.support.placeholder = true;
});
// This adds placeholder support to browsers that wouldn't otherwise support it.
$(function () {
if (!$.support.placeholder) {
var active = document.activeElement;
$('input,textarea').focus(function () {
if ($(this).attr('placeholder') !== '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('has-placeholder');
}
}).blur(function () {
if ($(this).attr('placeholder') !== '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('has-placeholder');
}
});
$('input,textarea').blur();
$(active).focus();
$('form:eq(0)').submit(function () {
$('input.has-placeholder,textarea.has-placeholder').val('');
});
}
});
Plus CSS
.has-placeholder {
color:#777 /*whatever you like*/
}
Here is the final code using Dippas' answer with the extras to cover textareas and inputs that have type='tel' rather than type='text'. This seems to cover everything on my form, but there might be other input types that need adding at other times. I'm sure that somebody who knows what they are doing can trim this down by sorting out some of the duplicate code.
// This adds 'placeholder' to the items listed in the jQuery .support object.
jQuery(function() {
jQuery.support.placeholder = false;
test = document.createElement('input');
if ('placeholder' in test) jQuery.support.placeholder = true;});
// This adds placeholder support to browsers that wouldn't otherwise support it.
$(function() {
if (!$.support.placeholder) {
var active = document.activeElement;
$('textarea').focus(function() {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('has-placeholder');
}
}).blur(function() {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('has-placeholder');
}
});
$('textarea').blur();
$(active).focus();
$('form:eq(0)').submit(function() {
$('textarea.has-placeholder').val('');
});
$('input').focus(function() {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('has-placeholder');
}
}).blur(function() {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('has-placeholder');
}
});
$('input').blur();
$(active).focus();
$('form:eq(0)').submit(function() {
$('input.has-placeholder').val('');
});
}
});
I have a dropdown box and an input that is used to autofilter the dropdown.I need to make a dropdown filtering faster. I've added a textbox before the dropdown menu and an event to filter the dropdown:The code snippet is:
td.prepend(' <span class="ms-metadata"><br/>(type some chars to filter )</span><br/>');
.....
td.prepend($('<input/>', {id: 'DPFilter',
onkeyup: 'filterDP(this)'
}));
and on the function filterDP(element) :
....
var value = $(element).val();
$( dropdown).find("option").each(function() {
var optionValue = $(this).val();
$(dropdown).find('option[value="' + optionValue + '"]').map(function () {return $(this).parent('span').length === 0 ? this : null;})
.wrap('<span>')
$(this).map(function () { return $(this).parent('span').length === 0 ? this : null;}).wrap('<span>').hide();
...
if ((value == "") || ($(this).text().search(value) > -1) ){
$(dropdown).find('option[value="'+optionValue+'"]').show();
}
The only place I can think of, is the $(dropdown).find('option[value="'+optionValue+'"]').show(); , instead of finding it, to use an index, but I don't know how.
Also, I use the find() twice (in a code not shown), will a variable making faster?
Thank you
You can both simplify and speed this up by using filter:
var value = $(element).val();
$(dropdown).filter(function() {
if ($(this).text().indexOf(value) != -1) {
$(this).show();
}
});
$('input').keypress(function(e){
if(($(this).val().split('a').length - 1) > 0){
console.log($('input').val());
$('input').val($('input').val().replace('a', ''));
}
})
jsfiddle: http://jsfiddle.net/Ht8rU/
I want have only one "a" in input. I check if length a > 1 and next remove "a" from input, but this not working good. I would like remove only second a from this input. One "a" is allow.
Edit: Oh I see now... If you want to keep only the first a you can try this:
$('input').keypress(function(e) {
var key = String.fromCharCode(e.which);
if (/a/i.test(key) && /a+/i.test(this.value)) {
e.preventDefault();
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/6/
You have to check if the current letter being typed is a:
if (String.fromCharCode(e.which) == 'a')
But here's a simplified version. You don't need to use val() if you can use value, specially because it makes your code cleaner. Also you might want to check for A or a so a regex might be a better option. Here's the code:
$('input').keypress(function(e) {
var A = /a/gi,
letter = String.fromCharCode(e.which);
if (A.test(letter)) {
$(this).val(this.value.replace(A,''));
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/3/
I suggest using preventDefault to stop the key from being pressed:
$('input').keypress(function(e) {
if (e.keyCode === 97 && $(this).val().split('a').length > 1) {
e.preventDefault();
}
});
JSFiddle
This code may seem long and without any usefulness, but it works.
$('input').keyup(function(e) {
var e = $(this),
val = e.val(),
aPos = val.indexOf('a'),
spl1 = val.substring(0, aPos + 1),
spl2 = val.substring(aPos, val.length).replace(/a/gi, ''),
v = spl1 + spl2;
e.val(v);
});
Here is a working JSFiddle of this.
I would try something like this. Not sure how well supported is the input event currently, though.
(function() {
var elem = $('input');
var value = elem.val();
elem.bind("input propertychange", function(e) {
if (elem.val().split('a').length - 1 > 1)
elem.val(value);
else
value = elem.val();
});
})();
http://jsfiddle.net/Ht8rU/8/
When the user presses 'a' or 'A', you can check if there is one 'a' or 'A' already present, if there is one already then you don't add it to the input.
$('input').keypress(function(e){
if ((e.keyCode === 65 || e.keyCode === 97) & $(this).val().match(/a/gi) !== null) e.preventDefault();
})
Updated jsFiddle
Here's a modified version of your fiddle that works: http://jsfiddle.net/orlenko/zmebS/2/
$('input').keypress(function(e){
var that = $(this);
var parts = that.val().split('a');
if (parts.length > 2) {
parts.splice(1, 0, 'a');
that.val(parts.join(''));
} else {
// no need to replace
}
})
Note that we only replace the contents of the input if we have to - otherwise, constant rewriting of the contents will make it impossible to type in the midle or at the beginning of the text.
If you want to further improve it and make it possible to type at the beginning even when we are replacing the contents, check out this question about detecting and restoring selection: How to get selected text/caret position of an input that doesn't have focus?
For a normal input field i can write something like the below code, which will remove the default value of an input field when i click, and if i dont write anything in the input field, than the default value will return when i leave the input field.
jQuery('input[type="text"]').focus(function()
{
if (this.value == this.defaultValue)
{
this.value = '';
}
if(this.value != this.defaultValue)
{
this.select();
}
});
jQuery('input[type="text"]').blur(function()
{
if (this.value == '')
{
this.value = this.defaultValue;
}
});
But i have no clue how to do this with CKEditor.. Can I get some help.
I found this code which will alert when I click in the CKEditor. But I dont know how modify it to work the way I need.
CKEDITOR.instances['post_content'].on('focus', function()
{
alert(1);
});
Have you tried this?
CKEDITOR.instances['post_content'].on('focus', function()
{
if (this.value == defaultValue)
{
this.value = '';
}
});
Combining the idea above with [this other SO article][1]:
// delete default text on focus
CKEDITOR.instances['editor1'].on('focus', function () {
var defaultText = '<p class=\"ckNormal\">Type your comment here</p>';
var currentText = CKEDITOR.instances.editor1.getData();
// debug - removed
// alert(defaultText + '\n' + currentText);
if (defaultText.trim()==currentText.trim()) {
CKEDITOR.instances.editor1.setData('');
}
});
You probably won't need to trim the text before testing. This uses getData to find what the text is, and setData to change it.
So I need to have an input box in where people only is allowed to enter either the words "Yes" or "No". No other input is allowed. Does anybody out there knows a plugin or any other easy way to that with Jquery? I found a plugin named constraint (http://plugins.jquery.com/project/constrain), that can prevent the user from typing certain characters, but that is not enough, as the plugin can only prevent the user from typing numbers in an alphabetic field, for example. Drop down boxes or other components are not an option.
Thank you for your help.
Why not something like this (link to jsFiddle)? This will only let you type those characters that are contained in an array of allowed values? I suspect there's a better way to check for the existence of values or partial values in the array instead of looping. But this will be triggered by a user's key press, not when the control loses focus...so the UX may be better.
Hope this helps!!
HTML
Enter text: <input type="text" id="data" />
JavaScript Code
var allowedValues = ['yes','no'];
$(document).ready(function() {
$("#data").keyup(function(e) {
var typedValue = $(this).val(),
valLength = typedValue.length;
for(i=0;i<allowedValues.length;i++) {
if(typedValue.toLowerCase()===allowedValues[i].substr(0,valLength)) {
return;
}
}
$("#data").empty().val(typedValue.substr(0, valLength-1));
});
});
Based on clarification in comment, try this:
Try it out: http://jsfiddle.net/fsPgJ/2/
EDIT: Added a keypress event to deal with the user holding down a key.
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
})
.keypress(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no")
this.value = '';
})
.keyup(function() {
var val = this.value.toLowerCase();
if("yes".indexOf(val) != 0 &&
"no".indexOf(val) != 0) {
this.value = this.value.substr(0,this.value.length - 1);
}
});
Original:
If there's some reason you're not using a <select> or :radio or something, then you could have jQuery check the value on a .blur() event.
Try it out: http://jsfiddle.net/fsPgJ/
$('input').blur(function() {
var val = this.value.toLowerCase();
if(val != "yes" && val != "no") {
this.value = '';
alert( "'Yes' or 'No' is required. \n Please try again.");
}
});
This just clears the input if the (case insensitive) value is not "yes" or "no". I also added an alert() to give the user a little feedback as to why the field was cleared. You may want a different feedback approach.