Correctly entered text changes image? - javascript

I am trying to achieve an effect where the correctly entered text will result in the image changing, letting the user know he typed it in correctly. The only problem I am having is if the person types the first two characters correctly, even if the third is incorrect it still stays changed.
Example: Take the word "ate" for instance.
If the user types in " aate " with two A's the image still remains highlighted/changed.
Is it possible to make it somehow stay exact to what the correct text needs to be ?
JSFIDDLE here with google images for example:
http://jsfiddle.net/japaneselanguagefriend/wjx6b/
p.s. I hope I explained things cleary! I have been up and at this for hours and I could use a helping hand. Thanks so much guys!

What you need is to check on the index
$("#test").on('keyup', function() {
var typed = this.value;
$.each(text, function(index, item) {
if (typed[index] == text[index]) {
$('li', 'ul').eq(index).find('img').attr('src', happy[index]);
}else{
$('li', 'ul').eq(index).find('img').attr('src', grumpy[index]);
}
});
});
http://jsfiddle.net/wjx6b/2/
Or exact match would need to compare the the current text with the array letters combined
$("#test").on('keyup', function() {
var typed = this.value;
var theWord = ''
for(i=0;i<typed.length;i++){
theWord += text[i];
}
$.each(text, function(index, item) {
if (typed[index] == text[index] && typed == theWord) {
$('li', 'ul').eq(index).find('img').attr('src', happy[index]);
}else{
$('li', 'ul').eq(index).find('img').attr('src', grumpy[index]);
}
});
});
http://jsfiddle.net/wjx6b/4/
​

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";
});
});

Automatically change a value in a form field

I have a webpage where people enter information (name, job title, address, etc.) and it auto creates a business card for them. I currently have some jQuery that uses .change and looks at a field when a user changes it.
It looks for issues with what they enter, because some things must be in a certain format (ex- They enter the word "Avenue" and it won't let them add the item to their cart until they change it to Ave.)
I am trying to find some way to do this on the fly automatically with JS/jQuery, but I'm not sure what to do. What I would like is for the field to update itself, so if the user puts in "Avenue" it would auto update to "Ave." after the user tabs / exits the field.
Any idea on what JS and/or jQuery can be used to do this?
Here is my current code:
var x = "Clean";
var xD = " ";
$('#cartText4046').change(function () {
if ($(this).val().indexOf("Avenue") > -1) {
x = "Please use Ave. instead of Avenue.";
} else if ($(this).val().indexOf("avenue") > -1) {
x = "Please use Ave. instead of Avenue.";
... Additional rules here, omitted for space.
} else {
x = "Clean";
}
if (x != "Clean") {
$('#cartText4046').addClass("invalid");
xD = x;
} else if (x == "Clean") {
$('#cartText4046').removeClass("invalid");
xD = " ";
}
if (x != "Clean") {
$('.betabutton').html('<span id="addToBaskettext">To add this to the Basket,
please fix the following issue(s):<br><br> ' +xD'</span>');
$('.betabutton').addClass("invalidBtn");
} else if (x == "Clean") {
$('.betabutton').html('<a id="addToBasket" href="#" onclick="actionPageSubmit();return false;"><span id="addToBaskettext">Add to Basket</span></a>');
$('.betabutton').removeClass("invalidBtn");
}
Here is a working sample of what you may be looking for.
$("#textbox").on("change", function() {
$(this).val(function(index, value) {
return value.replace('Avenue', 'Ave.');
});
});
http://jsfiddle.net/decx8sw9/
If you really wanted it to do it after the user has finished making changes ("after the user tabs / exits the field.") you might want to bind to blur (fires when focus is lost/shifted to some other element)...
$('#cartText4046').on( "blur", function() {
$(this).val(function(index, value) {
value = value.replace('Avenue', 'Ave.');
// keep going ... value = value.replace('Street', 'St.') ..
return value;
});
EDIT: I reread the question, and now see that you wanted the correction to happen after the user exits the field. This answer provides inline autocorrection while the user types. I will leave it in case you find it useful after all.
You can lift the code from the jQuery Autocorrect Plugin: jsfiddle.
$("#textbox").autocorrect({
corrections: {
Avenue: "Ave.",
"...": "someWord"
}
});

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

Select previous and next words when double clicking blank space in HTML with Javascript

I was trying to change the behaviour of an HTML page with Javascript so whenever I click a blank space in a text (not textArea) between two words, instead of selecting that blank space, it selects the words before and after the blank space. I was trying to do it this way, but I am not able to do it:
function getBothWords() {
if (window.getSelection()) {
var sel = window.getSelection();
var blank = " ";
if(sel == blank) {
...
}
}
}
I also was trying to play with:
window.getSelection().getRangeAt(0)
But still nothing. Any ideas? Thanks :)
When you only click on a blank space, the selection will be collapsed. You can try something like this:
function getBothWords() {
var sel,
range = document.getSelection().getRangeAt(0);
if (range.collapsed) {
range.setEnd(range.startContainer, range.startOffset + 1);
}
sel = range.toString();
if (sel === ' ') {
...
}
}
A live demo at jsFiddle.
You should introspect the selection object and see that there is an anchorNode element available and an anchorIndex.
See the MDN Docs on selection.
The short is you need to look at your anchorNode and anchorOffset.
sel.anchorNode.nodeValue[sel.anchorNode.anchorOffset] might be the first character of your selection. Log the sel object to the console and start poking around. Some simple math should solve the issue from there. Of course it might not be a text node.
Be sure to read the definitions on the page since there are some gotchas that can be confusing.
More to the point, something like this is a dirty hack job:
var subLen = s.focusNode.nodeValue.substr(s.focusOffset).trim().indexOf(' ')+2;
var selectedWordWitSurroundingSpaces = s.focusNode.nodeValue.substr(s.focusOffset, subLen);
There is an amazing method in class Selection called modify() which is created for that purpose. In my case, the solution would be:
function select() {
if (window.getSelection) {
var s = window.getSelection();
var blank = " ";
if(s == blank) {
selectBothWords(s);
}
}
}
function selectBothWords(s) {
s.modify("move", "backward", "word");
s.modify("extend", "forward", "word");
s.modify("extend", "forward", "word");
}
The function select() checks that the selection is a 'blank space' (loosely). Then, the function selectBothWords() uses modify to move the selection one word backwards, then, extend it two words forward.

When user enters correct text, an image rollovers/changes

I am designing a language learning site. I want to have it when someone enters text into the text box it starts to roll over certain images. Take a look at my sample below
http://imageshack.us/photo/my-images/827/hiraganaquiz2.jpg/
So, when the user enters "na" the first symbol highlights as you see in my sample. When he enters "ma" the second symbol should highlight/rollover. I want all the symbols to stay rolled over while the correct text is entered. so if the user types "nama" the first two symbols should be rolled over to show they got it correct and once the last correct text is entered all three will be rolled over.
Can this by done? I will accept advanced and simple methods.
$(document).ready(function() {
var text = ['na', 'ma', 'ba'];
$("#elemID").on('keyup', function() {
var typed = this.value;
$.each(text, function(index, item) {
if (typed.indexOf(item)!=-1) {
$('li', 'ul').eq(index).find('img').addClass('correct');
}else{
$('li', 'ul').eq(index).find('img').removeClass('correct');
}
});
});
});
FIDDLE
EDIT:
At the top of your page, in the <head> section, add:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Then wrap the code in document.ready, see the edited code above on how to do that ?
On change of the input box, you could do something like this: (totally untested)
var parts = ["na", "ma", "blah"];
var start = 0;
for (var i = 0; i < parts.length; i++) {
var currentPart = parts[i];
var $img = $(".images img:nth-child(" + i + ")");
var end = start + currentPart.length;
if (str.length >= end && str.slice(start, start + currentPart.length) == currentPart) {
$img.addClass("highlight");
} else {
$img.removeClass("highlight");
}
start += currentPart.length;
}

Categories