next button not highlighting or displaying matches - javascript

The jquery highlight that I have created works well, but for some reason when I type something in the input field and hit the next button it doesn't highlight the terms. It only displays "1 of 0 mathches". I'm not sure why it won't highlight it.
Below is my script:
<script>
$("[data-search=next]").click(function() {
if (variableCounter < totalCount) variableCounter = variableCounter + 1;
else variableCounter = 1;
$(".kwt-count").html(variableCounter + " of " + totalCount + " Matches");
});
</script>
Also when the term is in the field and I hit the enter key it highlights the verbiage, but when I hit the delete key it unmarks the content, but the full string is removed along with the highlight. I want it to remove "all" highlights on delete or backspace key, but not remove the full string from the input field. Not sure why its removing everything in the input field.
<script>
$input.keydown("input", function(e) {
if (e.keyCode === 46 || e.keyCode === 8) {
$content.unmark();
$input.val(" ").focus();
}
});
</script>
I have created a codepen of my code here: https://codepen.io/dude12go8/pen/PoYbdXd

Related

How Can I Only Allow Text Entry at Start of Input Field, and Always Append Text

I previously had a requirement to always prepend (to put at the beginning) some static text to whatever was entered in a text input field, and to never allow that static text to be deleted. I found a solution that works really well.
Not my requirement has changed, and I need to append (to put at the end) some static text, to whatever is entered in a text box. I'd like the static text to be displayed in the text box at all times, and for any text entered to be placed before the static text. Ideally, the cursor would automatically be placed at "position zero" in the text input whenever a user clicks on the input, or tabs into it.
Here's a Fiddle that shows first the working example of the text being prepended, and then the non-working example of the appending:
https://jsfiddle.net/dsdavis/x9d36veu/25/
When one starts typing in the second example, you'll see that only the last character typed is displaying at the beginning of the box.
A slight difference between how I implemented them that is worth pointing out, is that in the working example, I use the "indexOf":
$(document).ready(function() {
$('#prepend').keyup(function(e) {
if (this.value.length < 16) {
this.value = 'Student Worker - ';
} else if (this.value.indexOf('Student Worker - ') !== 0) {
this.value = 'Student Worker - ' + String.fromCharCode(e.which);
}
});
});
and in the non-working example, I use "lastIndexOf":
$(document).ready(function() {
$('#append').keyup(function(e) {
if (this.value.length < 17) {
this.value = ' - Student Worker';
} else if (this.value.lastIndexOf(' - Student Worker') !== 17) {
this.value = String.fromCharCode(e.which) + ' - Student Worker';
}
});
});
Maybe using "lastIndexOf" is totally wrong, but it seemed like the right way to go.
Can anyone help me come up with a way to do this? To always display the static text " - Student Worker" in the text box, and to put any text that is entered before that static text?
Thank you!
Doug
another approach entirely:
$(document).ready(function() {
$('#append').on("input", function(e) {
var s = this.value.replace(" - Student Worker", "");
this.value = s + " - Student Worker";
});
});

How to change ctrl+del behaviour in javascript

I have to restrict user from deleting such words that are in a particular HTML tag (consider I have a custom tag) in a textarea.
<div>
You can Delete Me
<t>
DontDeleteMe
</t>
</div>
The words which are not in a t tag can be deleted.
I tried few logics nothing helps.
Is there any possibilities to get the selection range of ctrl+del keywords do?
case 46:
{ //DEL
if (range.startOffset == startNode.getLength()) {
var ancestor = endNode.$;
while (ancestor != null) {
var next = ancestor.nextSibling;
if (next != null) {
console.log("Next = " + next);
var node = new CKEDITOR.dom.node(next);
cancelEvent = node.isReadOnly();
break;
}
ancestor = ancestor.parentNode;
}
}
break;
}
Unfortunately, your description is quite poor when it comes to describing exactly what you need with examples so nobody really knows what you want to happen to the text.
Here's my Fiddle I just made.
It notes selected text and the ID of the first highlighted text container.
Select the text and press CTRL + Del.
If you use a text area, you can just let the user delete it but then copy it inside again. But why use a text area if the user shouldnt interfere with it? Did i misunderstand the feature you want?
$(document).on('keydown', function(evt) {
if (evt.ctrlKey && evt.keyCode == 46) { // Ctrl + Del key pressed
if (evt.target.id == 'customTextArea') { // Custom tag selected
$('#customTextArea').text('Don't delete me!'); // Copy old text in text area
}
}
});

Autoresize textarea remove rows on backspace

I have the following code for autoresizing a textarea:
HTML:
<textarea class="autoresize" id="txt" rows="2"></textarea>
JS:
$('#txt').keydown(function(e) {
var $this = $(this),
rows = parseInt($this.attr('rows'));
// on enter, add a row
if (e.which === 13)
$this.attr('rows', rows + 1);
// on backspace, remove a row -- THIS IS THE PROBLEM
if (e.which === 8 && rows !== 2)
$this.attr('rows', rows - 1);
});
It works well, but when I hit backspace to erase a letter from a word, it also removes rows, and that's my problem.
I want it to shrink back when the user "deletes" empty rows but I don't know how to achieve it.
If you want, you can check it out in this fiddle.
You need to check if the last line is empty. Demo.
if (e.which === 8 && rows !== 2) {
lines = $(this).val().split('\n');
if(!lines[lines.length - 1]) {
$this.attr('rows', rows - 1);
}
}
Just count the length of the text you've entered (in every keydown) and then when you use backspace check if the last character (get it using the index from the length) is \n, only then delete row.

change text color only of user entered string in AJAX extended textbox

I am extending a texbox control with AJAX Autocomplete and I have successfully implemeted an autocomplete text box where once the user enters 3 characters my database returns a list of records that begin with the first 3 characters entered by the user.
I then changed this feature to use some Fuzzy logic so that the strings that returned contain no less than the 3 characters entered by the user and progressively becomes a shorter more refined list as the user enters a more specific search string.
I then used the inlcluded CSS class of the Autocomplete control to change the backgorund color and selected item color in the extended texbox.
<asp:AutoCompleteExtender
ID="TextBox1_AutoCompleteExtender"
runat="server"
DelimiterCharacters=""
Enabled="True"
EnableCaching="True"
ServiceMethod="GetCompletionList"
ServicePath="~/search/strngSrch.asmx"
TargetControlID="TextBox1"
UseContextKey="True"
CompletionSetCount="30"
CompletionInterval="10"
MinimumPrefixLength="2"
CompletionListItemCssClass="itemHighlighted"
CompletionListHighlightedItemCssClass="itemHighlighted1">
</asp:AutoCompleteExtender>
What I would like to do now is change the color of the text ONLY in each string (list item) that matches what the user is entering after 3 or more characters have been entered.
I have been searching for something like this on the web for 2 days and have not found a similar solution. My efforts have become more than frustrating.
User Enters: fish
Results list should look like:
Fishing (The 4 letters = to Fish should be red in each of these list items)
New Fishing licenses
Renew Fishing License
Fish and hatchery lists
If anyone has any links or similar type of solution I would be very pleased to look it over.
This functionality could best be compared to searching for a text string in a PDF where the word background is highlighted yellow for each occurance within the doc. I don't care if it turns the background a different color ONLY behind the text the user entered, or changes the text color.
thanks,
I would like to thank the link below for providing a solution to the question. I finally found something that almost worked. In the interest of not posting only a link, please review the working code below.
Note some of my minor changes in the below code over the original found in the link at the end.
<script type="text/javascript">
function aceSelected(sender, e) {
var value = e._item.innerText; // get_text();
if (!value) {
if (e._item.parentElement && e._item.parentElement.tagName == "LI")
value = e._item.parentElement.attributes["_innerText"].value;
else if (e._item.parentElement && e._item.parentElement.parentElement.tagName == "LI")
value = e._item.parentElement.parentElement.attributes["_innerText"].value;
else if (e._item.parentNode && e._item.parentNode.tagName == "LI")
value = e._item.parentNode._value;
else if (e._item.parentNode && e._item.parentNode.parentNode.tagName == "LI")
value = e._item.parentNode.parentNode._innerText;
else value = "";
}
var searchText = $get('<%=TextBox1.ClientID %>').value;
searchText = searchText.replace('null', '');
sender.get_element().value = value;
}
function acePopulated(sender, e) {
//Give BehaviourId here
var behavior = $find('AutoCompleteEx');
var target = behavior.get_completionList();
if (behavior._currentPrefix != null) {
var prefix = behavior._currentPrefix.toLowerCase();
var i;
for (i = 0; i < target.childNodes.length; i++) {
var sValue = target.childNodes[i].innerHTML.toLowerCase();
if (sValue.indexOf(prefix) != -1) {
var fstr = target.childNodes[i].innerHTML.substring(0, sValue.indexOf(prefix));
var pstr = target.childNodes[i].innerHTML.substring(fstr.length, fstr.length + prefix.length);
var estr = target.childNodes[i].innerHTML.substring(fstr.length + prefix.length, target.childNodes[i].innerHTML.length);
target.childNodes[i].innerHTML = "<div class='autocomplete-item'>" + fstr + '<B><font color=red>' + pstr + '</font></B>' + estr + "</div>";
}
}
}
}
On your AutoComplete Extender provide the following values....
BehaviorID="AutoCompleteEx"
OnClientPopulated="acePopulated"
OnClientItemSelected="aceSelected"
That is about it, I had to perform some minor changes and debugging. Like the closing java script tag is wrong, and the function to get the value from the textbox did not work with e.get_value() so I changed it to e._item.innerText and seem to be working just fine.
Source of Solution

Limit text area value and cut the rest

I have a textarea which users can enter some tags.
I need to limit this tags to 20 tags.
Tags could be enterer this way
maytag1,mytag2,mytag3
What i wrote is this function
function limitTags()
{
var tags = $("input[type=text][name=tags]").val()
var tag = $.trim(tags);
var selected = new Array();
/**
* replace the last ','
*/
if(tag.substring(tag.length - 1) == ",")
{
*///tag = tag.replace(tag.length - 1, '');
}
var enteredTags = tag.split(",");
if( enteredTags.length > 20 )
{
//$("input[type=text][name=tags]").val(enteredTags.join(",", enteredTags));
alert("Only 20 Tags allowed");
}
}
The alert works just fine but, after the alert box is gone. i can continiue entering tags till the alert box appears.
What i need is cut the text after the messagebox which was entered also the last ","
I hope i could ask my question clear.
Thanks
You can use the slice method to cut the array down to 20 entries before setting the value:
$("input[type=text][name=tags]").val(enteredTags.slice(0,20).join(","));
See: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Slice
Intercept "," pressing, and check how many entries the user inserted so far. If he's trying to insert too many entries just prevent further insertions.
$('input[type=text][name=tags]').keyup(function(e) {
if((e.keyCode == 188) && ($(this).val().split(",").length > 19)) {
alert('Only 20 Tags allowed');
}
});

Categories