Input Text format, Jquery, Javascript or Css - javascript

While Typing in a input First letter should change to Capital, But rest letters should be in lowercase, Even user Input capital letters it should changed it lowercase.
Example input word: mOuSe , ComPuTER
Important Point: While Typing it should change to: Mouse, Computer
I have tried many Stackflow soloution, But for above logic i found none.
Using Css: Click Here
Using Javacript: Click Here (This one worked but for last letter it doesnt works)
Any solution is accepted using Jquery, Javascript or Css
$(document).ready(function() {
//alert('ready');
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val();
val = val.substr(0, 1).toUpperCase() + val.substr(1).toLowerCase();
$this.val(val);
});
});

Use the input event instead of the keypress event.
$('input').on('input', function(event) {

function initCap(t){
t.value=t.value.toLowerCase();
t.style='text-transform:capitalize;'
}
call the method onkeypress and onblur

Try This
$('input').on('keyup', function(event) {
var firstchar = $(this).val().substring(0,1);
var remainchar = $(this).val().substring(1,$(this).val().length).toLowerCase();
$(this).val(firstchar + remainchar);
});
$('input').on('keydown', function(event) {
var firstchar = $(this).val().substring(0,1);
var remainchar = $(this).val().substring(1,$(this).val().length).toLowerCase();
$(this).val(firstchar + remainchar);
});
DEMO

It might be interesting to point out that CSS text-transform: capitalize; only alters the display of the input, while Javascript modifies the actual HTML value. This matters if the input is, for example, a CAPTCHA response or form input field that needs to be validated.
With pure Javascript, you could split the input into separate words & transform each one of them, like so:
HTML
<div id="transform">mOuSE, cOmPUTEr</div>
<button type="button">Capitalize</button>
JS
var rgx = /,/; /* word splitter, can be anything */
var target = document.getElementById('transform');
document.getElementsByTagName('button')[0].onclick = function() {
var strArr = target.innerHTML.split(rgx); /* split the input */
for (var word = 0; word < strArr.length; word++) { /* iterate over each word */
strArr[word] = strArr[word].toLowerCase().trim();
var firstLetter = strArr[word].substr(0,1).toUpperCase();
var otherLetters = strArr[word].substr(1, strArr[word].length)
strArr[word] = firstLetter+otherLetters;
}
target.innerHTML = strArr.join();
}
Demo: http://jsbin.com/farib/2/edit
NB: If your input is in a <textarea> or <input>, replace .innerHTML with .value.

Try this css solution.
DEMO
input {
text-transform:capitalize;
color: blue;
}
$(document).ready(function(){
$("input").on("keypress",function(){
$(this).val($(this).val().toLowerCase());
});
})

Related

Split div content at cursor position

I need to split an element after user clicks on it and the attr 'contenteditable' becomes 'true'. This fiddle works for the first paragraph but not second because the latter is in a p tag. Similary in this fiddle you will see that when the element has html tags in it, the counter loses accuracy and hence the text before and after the cursor is not what you'd expect.
The assumption here is that the users will split the data in a way that the help tags will stay intact. As pointed out by dandavis here, e.g. the div has <i>Hello</i> <b>Wo*rld</b>, the user will only need to split the div into two divs, first will have <i>Hello</i> and the second div will have <b>Wo*rld</b> in it.
Html:
<div><mark>{DATE}</mark><i>via email: </i><mark><i>{EMAIL- BROKER OR TENANT}</i></mark></div>
JS:
var $splitbut = $('<p class="split-but">Split</p>');
$(this).attr('contenteditable', 'true').addClass('editing').append($splitbut);
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
}
var start = userSelection.anchorOffset;
var end = userSelection.focusOffset;
var before = $(this).html().substr(0, start);
var after = $(this).html().substr(start, $(this).html().length);
The "Split" button is not working as generating the html is not an issue once I get proper "after" and "before" text. Any ideas as to what I am doing wrong here?
Something like this could work for the specific case you describe
$('div, textarea').on('click', function(e) {
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
}
var start = userSelection.anchorOffset,
end = userSelection.focusOffset,
node = userSelection.anchorNode,
allText = $(this).text(),
nodeText = $(node).text();
// before and after inside node
var nodeBefore = nodeText.substr(0, start);
var nodeAfter = nodeText.substr(start, nodeText.length);
// before and after for whole of text
var allExceptNode = allText.split(nodeText),
before = allExceptNode[0] + nodeBefore,
after = nodeAfter + allExceptNode[1];
console.log('Before: ', before);
console.log('------');
console.log('After: ', after);
});
Updated demo at https://jsfiddle.net/gaby/vaLz55fv/10/
It might exhibit issues if there are tags whose content is repeated in the whole text. (problem due to splitting)

Disable button if a string is matched from a line in jquery

I'm trying to build a website using jquery-1.10.2 where I want to block css related strings like <style>, <link> etc. I want to disable the submit button if any of those strings match. So far I've managed to block them using .keyup() function but if I write more than those tags like <link rel="stylesheet" href="css/bootstrap.min.css"> then it won't work. Here are my codes,
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var input = $(this).val();
if (input == "<style>" || input == "</style>" || input == "<link>") {
$('#deactivedivEditor-2').attr("disabled", "disabled");
}else{
$('#deactivedivEditor-2').removeAttr("disabled");
}
});
});
JSFiddle Demo
How can I disable the button if any of those strings match from any lines? Need this help badly. Thanks.
You can use regex to check if the text contains certain pattern.
$(document).ready(function () {
var regex = /<\/?style.*?>|<link.*?>/;
$('#inputdivEditor-2').keyup(function () {
var val = $(this).val();
$('#deactivedivEditor-2').prop('disabled', regex.test(val));
});
});
Demo: http://fiddle.jshell.net/tusharj/52xd3s11/
Regex
/ : Delimiters of regex
\/?: Matches 0 or 1 /
.*?: Matches any character any no. of times
|: OR in regex
You can use the following regex to match those strings.
var regex = /<(style|link)>/;
To disable update when the elements are present. That however wouldn't solve all cases. If someone wants he can bypass the regex by writing < style > or with using different encoding and so on.
In my opinion a better option is to look at the content from a browser's perspective. In other words take the input and make an element out of it:
var dummyElement = $('<div></div>');
dummyElement.html(input); //contents of the input field
if(dummyElement.find('style').length > 0) {
//you get the point
}
..because there's that one question on SO, which explains why not parse HTML with regexes..
RegEx match open tags except XHTML self-contained tags
Just use regex to check anything between < > like below:
DEMO
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var input = $(this).val();
var regex=/<*>/;
if (regex.test(input)) {
$('#deactivedivEditor-2').attr("disabled", "disabled");
} else {
$('#deactivedivEditor-2').removeAttr("disabled");
}
});
});
You can use .prop('disabled',true) for disable button and .prop('disabled',false) for enable button. Both are used after $('#deactivedivEditor-2').
First of all, you can use regular expressions to check the string with a pattern at any position. The regexp I show below matches on anything between two angular braces - even non html tags too.
Secondly - it is a bit off topic - the best and recommended solution for setting and disabling the "disabled" attribute with jquery is by using the .prop() method
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var inputValue = $(this).val();
var regexp = /]*?>/;
var isDisabled = regex.test(inputValue);
$('#deactivedivEditor-2').prop("disabled", isDisabled);
});
});

Determining a character of a sentence when clicked on

On a random break I found myself wondering if it would be possible to use jQuery to determine a single character within a sentence when it is clicked on.
For example:
This
When the user clicks on first h, jQuery would return this to me.
The only way I could think of doing this would be to wrap each character within the sentence in a span with a class of its letter such as the following example:
<span class="clickable T">T</span>
<span class="clickable h">h</span>
<span class="clickable i">i</span>
<span class="clickable s">s</span>
Followed by a $('.clickable').click(function()) that would return its second class.
My question is: is this the most efficient way to do this?
Obviously wrapping every single letter of the document in span tags is not efficient.
I was able to spin something up that works in Chrome at least. Basically, when you click on a letter, it then triggers a double clicks which selects the word. We get the selection which actually gives us the text of the entire target element. From that, we get the letter that was clicked. We remove the selection and do what we want with the letter.
Fiddle here
$(function(){
$(document).click(function(e){
var target = e.target;
$(target).dblclick();
}).dblclick(function(){
var selection,
node,
text,
start,
end,
letter;
if (window.getSelection) {
selection = document.getSelection();
node = selection.anchorNode;
if (node.nodeType === 3) {
text = node.data;
start = selection.baseOffset;
end = selection.extentOffet;
if (!isNaN(start)) {
letter = text.substr(start, 1);
}
}
window.getSelection().removeAllRanges()
} else if(document.selection) {
//continue work here
}
if (letter) {
alert(letter);
}
});
});
You could return the innerHTML as well with:
$('.clickable').on('click', function(){
alert($(this).html());
});
As for a more efficient way to do it...maybe try this:
in Javascript/jQuery, how to check a specific part of a string and determine if it is a whitespace or letter?
You can do it with this script
$('.clickable').on('click', function(){
var html = $(this).text(); // if you want the text inside the span
var index = $(this).index(); // if you want the position among siblings
var classes = $(this).attr('class').split(" ");
var secondClass = getSecondClass(classes);
});
function getSecondClass(classArray){
if(classArray.length<2){
return null;
}else{
return classArray[1];
}
}
I've also included the html and index variables if you want to do something else with the clicked element.
Basically you split the classes of the element by spaces and then check if the array has less than two elements, in that case it returns null, otherwise it returns the second element.
jsFiddle
Well wrapping all text dyanamically with span tag , it is possible what you were looking for
JS
$(function(){
var lengthText = $('#singlecharacter').text().length;
var textValue = $('#singlecharacter').text();
var textArray = textValue.split('');
var newText = new Array();
for (var i = lengthText - 1; i >= 0; i--) {
newText[i] = "<span class='sp'>"+textArray[i]+"</span>";
};
$('#singlecharacter').html(newText);
$('.sp').click(function()
{
alert($(this).text());
});
});
HTML
<div id='singlecharacter'>THIS</div>
DEMO JSFIDDLE

How to remove extra commas from a list

I have a list of checkboxes and if one is checked, I'm appending the checkbox value to a input field elsewhere on the page. If a checkbox is unchecked, I'm removing the value from the hidden input field. What is happening is if the values are being added and removed just fine but they are leaving a series of commas behind when a check box is checked, unchecked, checked, unchecked, etc.
A) should I worry about it
B) if yes, how should I alter my add/append routine (see below) or is there a better way to do what I'm doing? I'd prefer to end up with a clean list like 0_1,0_2,41_4 opposed to 0_1,,,,,,,,,,,,,,,,0_2,,,,41_4,,,,.
<input type="text" value="0_1,0_2,41_4" id="EOStatus_SelLayers" />
// example of dataset: '0_1,0_2,41_4';
if ( xyz.hasClass("icon-check-empty") ) {
var existing_str = $('#EOStatus_SelLayers').val();
if (existing_str==null || existing_str==""){
//add
$('#EOStatus_SelLayers').val(id);
}
else {
//append
$('#EOStatus_SelLayers').val( existing_str + ',' + id);
}
}
else {
$(xyz).removeClass("icon-check").addClass("icon-check-empty");
var old_str = $('#EOStatus_SelLayers').val();
var new_str = old_str.replace(','+id,'');
var new_str = old_str.replace(id,'');
$('#EOStatus_SelLayers').val(new_str);
}
In the else statement, I could do something like this:
var new_str = old_str.replace(id,'');
var new_str = old_str.replace(',,',',');
You can replace the id with an empty string and then replace any extraneous commas.
There are three places you can end up with an extraneous comma:
A double comma somewhere in the middle (needs to be replaced with a single comma)
A leading comma (needs to be removed)
A trailing comma (needs to be removed)
You can address all three cases with these two replace operations:
.replace(/,,/g, ",").replace(/^,|,$/g, "");
Which in place could look like this:
else {
$(xyz).removeClass("icon-check").addClass("icon-check-empty");
var old_str = $('#EOStatus_SelLayers').val();
var new_str = old_str.replace(id,'').replace(/,,/g, ",").replace(/^,|,$/g, "");
$('#EOStatus_SelLayers').val(new_str);
}
If you're using jQuery - a simpler approach would be simple re-set the input value each time a change was made to checkboxes? Simply concat the ID of each :checked input... If you're using a custom lib to change the appearance of the checkboxes I'm sure there's on-change event triggers that would allow the following to work.
Alternatively you should be able to edit to suit your specific needs.
$('input[type=checkbox]').on('change', function(e) {
var newVal = [];
$('input[type=checkbox]:checked').each(function() {
newVal.push($(this).attr('id'));
});
$('#EOStatus_SelLayers').val(newVal.join(','));
});
Or, in the case you're using images:
$('[class^="icon-check"]').on('click', function(e) {
var newVal = [];
$('.icon-check').each(function() {
newVal.push($(this).attr('id'));
});
$(this).toggleClass('icon-check-empty');
$(this).toggleClass('icon-check');
$('#EOStatus_SelLayers').val(newVal.join(','));
});
Disclaimer: not tested - but looks like it should work.

REGEX - Highlight part over 19 chars

Hi,
I have some text inside div[contenteditable="true"] and I should highlight (span.tooLong) part which goes over the 19 character limit. Content in div may have HTML tags or entities and those should be ignored when counting to 19.
Twitter has similar way to highlight too long tweet:
Examples:
This is text ⇨ This is text
This is just too long text ⇨ This is just too lo<span class="tooLong">ng text</span>
This <b>text</b> has been <i>formatted</i> with HTML ⇨ This <b>text</b> has been <span class="tooLong"><i>formatted</i> with HTML</span>
How can I implement this in JavaScript?
(I want to use regular expressions as much as possible)
Okay... here's some code that I think will work for you, or at least get your started.
Basically, the regex you need to find everything over 19 characters is this:
var extra = content.match(/.{19}(.*)/)[1];
So, I put together a sample document of how you might use this.
Take a look at the DEMO.
Here's the Javascript I'm using (I'm using jQuery for the locators here, but this can easily be modified to use straight Javascript... I just prefer jQuery for stuff like this)...
$(document).ready(function() {
$('#myDiv').keyup(function() {
var content = $('#myDiv').html();
var extra = content.match(/.{19}(.*)/)[1];
$('#extra').html(extra);
var newContent = content.replace(extra, "<span class='highlight'>" + extra + "</span>");
$('#sample').html(newContent);
});
});
Basically, I have three DIVs setup. One for you to enter your text. One to show what characters are over the 19 character limit. And one to show how you might highlight the extra characters.
My code sample does not check for html tags, as there are too many to try and handle... but should give you a great starting point as to how this might work.
NOTE: you can view the complete code I wrote using this link: http://jsbin.com/OnAxULu/1/edit
Here's an answer that uses my Rangy library. It uses the Class Applier and TextRange modules to apply styling on character ranges within the editable content while preserving the selection. It also uses a configurable debounce interval to prevent sluggishness in editor performance. Also, it should work on old IE.
Demo: http://jsfiddle.net/timdown/G4jn7/2/
Sample code:
var characterLimit = 40;
var debounceInterval = 200;
function highlightExcessCharacters() {
// Bookmark selection so we can restore it later
var sel = rangy.getSelection();
var savedSel = sel.saveCharacterRanges(editor);
// Remove previous highlight
var range = rangy.createRange();
range.selectNodeContents(editor);
classApplier.undoToRange(range);
// Store the total number of characters
var editorCharCount = range.text().length;
// Create a range selecting the excess characters
range.selectCharacters(editor, characterLimit, editorCharCount);
// Highlight the excess
classApplier.applyToRange(range);
// Restore the selection
sel.restoreCharacterRanges(editor, savedSel);
}
var handleEditorChangeEvent = (function() {
var timer;
function debouncer() {
if (timer) {
timer = null;
}
highlightExcessCharacters();
}
return function() {
if (timer) {
window.clearTimeout(timer);
}
timer = window.setTimeout(debouncer, debounceInterval);
};
})();
function listen(target, eventName, listener) {
if (target.addEventListener) {
target.addEventListener(eventName, listener, false);
} else if (target.attachEvent) {
target.attachEvent("on" + eventName, listener);
}
}
rangy.init();
var editor = document.getElementById("editor");
var classApplier = rangy.createClassApplier("overrun");
// Set up debounced event handlers
var editEvents = ["input", "keydown", "keypress", "keyup",
"cut", "copy", "paste"];
for (var i = 0, eventName; eventName = editEvents[i++]; ) {
listen(editor, eventName, handleEditorChangeEvent);
}

Categories

Resources