Replacing text with jQuery only in active/focussed input-Element - html

I have a page where I have around 10 input-Elements. Some of them I gave the class .no-whitespace-allowed. Now I have a jQuery script running in the background with the purpose to avoid whitespaces in the very input-Elements:
$(function() {
var elements = $(".no_whitespace_allowed");
var func = function() {
if (elements.is(':focus')) elements.val(elements.val().replace(/\s/g, ''));
else elements.val(elements.val());
}
elements.keyup(func).blur(func);
});
However, it replaces the text in every input field with the result that I have the same text in all inputs. Any ideas?

$(".no_whitespace_allowed").keyup(function(){
$(this).val( $(this).val().replace(/\s/g, '') );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="no_whitespace_allowed" type="text">
Something like this ?

Related

Check if text is being entered in input using Javascript/jQuery

I am trying to hide a placeholder while the input is being used and while there's text inside the input. Here's a simplified version of the HTML for the input and placeholder:
<div id="search-placeholder"><span class="fa fa-search"></span> Search</div>
<input id="search-input" type="text" name="search" />
I tried using jQuery but it does not return the desired result:
$(document).ready(function(){
$('#search-input').focus(function(){
$('#search-placeholder').fadeOut(100);
}).focusout(function(){
$('#search-placeholder').fadeIn(100);
});
});
The placeholder will hide when the input is selected, as it should. But it will show again when the user clicks elsewhere, even while the input is not empty! The placeholder is visible on top of the input value, so I tried a different approach:
$('#search-input').change(function(){
if($('#search-input').val() = '') {
$('#search-placeholder').fadeIn(100);
}else{
$('#search-placeholder').fadeOut(100);
}
})
Unfortunately, this only works when the user clicks elsewhere. The placeholder still shows while typing and while the input is selected, again showing itself on top of the input value. How do I hide <div id="search-placeholder"> while <div id="search-input"> is not empty, or when the input is selected by clicking or tapping it (on focus)?
Maybe try to check the value of the input in the focusout event and only show the placeholder if it's empty:
$(document).ready(function(){
$('#search-input').focus(function(){
$('#search-placeholder').fadeOut(100);
}).focusout(function(){
if($('#search-input').val() === '')
{
$('#search-placeholder').fadeIn(100);
}
});
});
I think you could extract the $('#search-input') and $('#search-placeholder') elements to variables, so the code becomes a bit more readable.
You do this using javascript and jquery
jquery :-
$(document).ready(function(){
$('#search-input').focus(function() {
$('#search-placeholder').fadeOut(100);
});
$('#search-input').focusout(function() {
if($('#search-input').val() === '') {
$('#search-placeholder').fadeIn(100);
}
});
});
javascript
var searchInput = document.getElementById("search-input");
var searchPlaceholder = document.getElementById("search-placeholder");
searchInput.onfocus = function() {
searchPlaceholder.style.display = "none";
}
searchInput.onfocusout = function() {
if(this.value == "") {
searchPlaceholder.style.display = "block";
}
}
if you want to add fade-in fade-out transitions in javascript method use css transition property- transition: opacity 1s and instead of changing style.display change style.opacity to 1(show) and 0(hide)

How can I filter and mark words from an input

I would like to filter and mark words from a page, something similar to the way Google marks words when you type a find query.
I am trying to do the filter and mark simultaneously. There are lots of solutions across the net that give examples of marking and examples of filtering but none that combine the two operations. Is this even possible?
I can show my filter script but not the marking script because I simply can't find one that actually works. I would have to upload dozens of scripts that I have tried.
Can anyone assist in pointing me in the right direction or even better maybe help with a snippet that actually works.
I can't believe it is so difficult to find.
This works wonderfully to filter the words or phrase but it does not mark it in the paragraph.
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDIV *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
Assuming myDIV contains elements only one layer deep, the following code should work:
$(document).ready(function() {
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDIV>*").map(function() {
var el = $(this);
var content = el.html().replace(/(<span class="highlighted">)|(<\/span>)/g, "");
el.html(content);
var hasText = el.text().toLowerCase().indexOf(value) > -1;
el.toggle(hasText);
if (hasText) {
// escape value for use in regex
var textRegex = new RegExp(value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
el.html(content.replace(textRegex, '<span class="highlighted">$&</span>'));
}
});
});
});
.highlighted {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" />
<div id="myDIV">
<p>some text</p>
<p>some filler</p>
<p>I like cheese</p>
<p>this should work</p>
</div>

knockout toggle/expand the text on click of text

Binding data into html table using knockout. One of the column has large text 200 length.. and UI just got scroll long. So just want to show, first 20 length chars and click of, ... it should expand or collapse the text.
so just created a template below,
<script type="text/html" id="templateLongText">
<span data-bind="text: (Comments.length > 20 ? Comments.substring(0, 20) + '<a href=\'#\' data-bind=\'click: toggle(Comments)\'>...</a>' : Comments)"></span>
</script>
It does not work event, just rendering same text as above.
Edit:
How toggle the expand or collapse text(Comments value) on click of ...
You could add a custom binding for this, which you can bind to any simple (observable) string. This custom binding:
initially adds two child elements. A span for the (abbreviated) text and an anchor for toggling.
on every update (or only once if the text is not observable) sets the abbreviated text in the span and adds an onclick handler for toggling the text. The toggle anchor is hidden for texts having less than 20 characters.
ko.bindingHandlers.expandText = {
init: function(element, valueAccessor) {
element.appendChild(document.createElement('span'));
var toggle = document.createElement('a');
toggle.appendChild(document.createTextNode("..."));
toggle.href = "#";
element.appendChild(toggle);
},
update: function(element, valueAccessor) {
var text = ko.unwrap(valueAccessor());
var textElement = element.getElementsByTagName('span')[0];
var toggle = element.getElementsByTagName('a')[0];
var collapsed = true;
toggle.onclick = function() {
collapsed = !collapsed;
ko.utils.setTextContent(textElement, collapsed ? text.substr(0, 20) : text);
}
toggle.style.display = text.length > 20 ? 'inline' : 'none';
ko.utils.setTextContent(textElement, collapsed ? text.substr(0, 20) : text);
}
};
ko.applyBindings({
sample1: '1234567890123456789012345',
sample2: '123456789012345',
sample3: '123456789012345678901234567890'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="expandText: sample1"></div>
<div data-bind="expandText: sample2"></div>
<div data-bind="expandText: sample3"></div>
You can't implement html tag as a text in binding.
<script type="text/html" id="templateLongText">
<span data-bind="text: Comments.length > 20 ? Comments.substring(0, 20) : Comments"> </span>...
</script>

Having a permanent value in an input field while still being able to add text to it

I don't know if this is possible but I would like to have an input field where I would have a value that is not editable by the user.
However, I don't want the input field to be "readonly" because I still want the user to be able to add text after the value.
If you have any idea on how to do this, let me know please that would help me a lot.
EDIT: I use html forms.
You can position the text on top of the input field to make it look as if it is inside it. Something like this:
<input type="text" name="year" style="width:3.5em;padding-left:1.5em;font:inherit"><span style="margin-left:-3em;margin-right:10em;">19</span>
This way your input field will start with "19" which can not be edited, and the user can add information behind this.
Basically what you do is set the input field to a fixed width, so that you know how much negative margin-left to give the span with your text in it in order for it to be positioned exactly at the start of the input field.
You might need to fiddle with the margin-left of the span depending on the rest of your css.
Then also adding pedding-left to the input field, to make sure the user starts typing after your text and not under it.
font:inherit should make sure both your text and the text typed by the user are in the same font.
And if you want to put anything to the right of this input field, do add margin-right to the span with your text, as otherwise other content might start running over your input field as well.
seems a little weird to me ..why not just use a text output and afterwards the input field?
like sometimes used for the birthdate (although, maybe not anymore..)
birthyear: 19[input field]
edit:
with some javascript stuff you could realise something like that you asked for, though
an input field with text and catching keystrokes within that field while only allowing some after what you want to be always there - but, well, you would need to use js ..and if its just for that, Id rather say its not necessary
edit:
if you want to use a trick just for the viewer you could use a background-image/border-style that surrounds a text and the input field, thus making it look like text and input are the same input-box.
Sounds like you want placeholder text. In HTML5 you can set the placeholder attribute on any input element. This will work in modern browsers.
<input type="email" placeholder="jappleseed#appletree.com" name="reg_email" />
Now, for older browsers this won't work. You'll need a JavaScript alternative to provide the same UI value.
This can work for all browsers:
<input type="text" value="Search" onfocus="if (this.value == 'Search') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search';}">
but it's not recommended because there is a better way (really, it's a combination of the first two approaches): Use HTML5 markup for new browsers; jQuery and modernizr for old browsers. This way you can have only one set of code that will support all user cases.
Taken directly from webdesignerwall.com:
<script src="jquery.js"></script>
<script src="modernizr.js"></script>
<script>
$(document).ready(function(){
if(!Modernizr.input.placeholder){
$('[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('');
}
})
});
}
</script>
[You'll need both jquery.js and modernizr.js installed in the same folder as your webpage.]
Note: I have a feeling that a little more research might reveal that modernizr isn't needed for this at all, though I could be wrong about that particular point.
Perhaps, then, you want a select menu?
<select name="mySelectMenu">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
Sorry if this isn't what you want either. I'm grasping at straws because what you are asking for is very vague. Maybe you should give an example of what one of these 'editable but not editable' inputs would be used for.
Also, you could use a select and a text input.
The main problem is to determine the position of the cursor. This can be done e.g. using the following function:
function getCaret(el) {
var pos = -1;
if (el.selectionStart) {
pos = el.selectionStart;
}
else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r != null) {
var re = el.createTextRange();
var rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
pos = rc.text.length;
}
}
return pos;
}
Now you can install an event handler for the key press and check whether the pressed key was inside the immutable part of the value of the textarea. If it was there the event handler returns false, otherwise true. This behavior can be wrapped into a simple object:
function Input(id, immutableText) {
this.el = document.getElementById(id);
this.el.value = immutableText;
this.immutableText = immutableText;
this.el.onkeypress = keyPress(this);
}
function keyPress(el) {
return function() {
var self = el;
return getCaret(self.el) >= self.immutableText.length;
}
}
Input.prototype.getUserText = function() {
return this.el.value.substring(this.immutableText.length);
};
var input = new Input("ta", "Enter your name: ");
var userText = input.getUserText();
You can check it on jsFiddle (use Firefox or Chrome).
I came up with this:
```
if (e.target.value == '' || e.target.value.length <= 3) {
e.target.value = '+91-';
}
```

highlight word in div using javascript

hi i have to implement find and replace functionality in my project. in this functionality there is one find and replace button on the top of contenteditable div. when user click on this button, popup window will open and ask for the search word when specify word and press find it will find word in that div only. and if match found it will highlight that word. so anybody tell me how can i highlight word in div. its urgent so please . thank you.
<div id="test" contenteditable="true">
this is test <font class='classname'> some text test</font>
</div>
i want to high light only test word not else
You will need to search through the div to find the word and then put that word into a span, and change the background color of the span.
Edit: I just noticed that you are not using CSS, so you will need to insert a font tag to change the color.
I just stole this from Sphix, the documentation tool:
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node) {
if (node.nodeType == 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery.className.has(node.parentNode, className)) {
var span = document.createElement("span");
span.className = className;
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this)
});
}
}
return this.each(function() {
highlight(this);
});
}
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('.sidebar .this-page-menu li.highlight-link').fadeOut(300);
$('span.highlight').removeClass('highlight');
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlight');
});
}, 10);
$('<li class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></li>')
.appendTo($('.sidebar .this-page-menu'));
}
},
So, adding this to a js file in your site, any page with it that receives a highlight GET parameter will search and highlight the word in the page.
You can find a demo of the working code in:
http://sphinx.pocoo.org/intro.html?highlight=python
Note: This code needs jQuery, off course...
Its actually pretty easy using the prototype library:
<html>
<head>
<style type="text/css">
#content span {
background-color: yellow;
}
</style>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
Event.observe(window,'load',function(){
var htm = $('content').innerHTML;
$('content').innerHTML = htm.sub('my','<span>my</span>');
});
</script>
</head>
<body>
<div id="content">
This is the div containing my content.
</div>
</body>
</html>
This should get you started so you can implement the rest.
To highlight a word you have to select it somehow. One option is to surround the word with a span tag.
this is <span class="highlight">test</span> some text test
then specify CSS for the highlight class.