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"
}
});
Related
I am checking the validity of five unique inputs to prevent form submission when invalid inputs remain.
sE.addEventListener("input", (e) => {
if (
Number.isNaN(e.target.valueAsNumber) ||
sE.valueAsNumber >= Number(sE.max) ||
sE.valueAsNumber <= Number(sE.min)
) {
e.preventDefault();
calcButton.disabled = true;
} else {
calcButton.disabled = false;
}
This does appear to work to prevent the calculation button from being enabled, but only when the input (ie sE) is being looked at. This doesn't look at all the other inputs.
So I thought it would be better to try this:
sE.addEventListener("input", (e) => {
let reportS = sE.reportValidity();
let reportU = uE.reportValidity();
let reportV = vE.reportValidity();
let reportA = aE.reportValidity();
let reportT = tE.reportValidity();
console.log(reportS, reportU, reportV, reportA, reportT);
if (
Number.isNaN(e.target.valueAsNumber) ||
sE.valueAsNumber >= Number(sE.max) ||
sE.valueAsNumber <= Number(sE.min)
) {
e.preventDefault();
calcButton.disabled = true;
} else {
calcButton.disabled = false;
}
});
This gives me the appropriate true/false relationship between all five inputs. But, when you click on one of the inputs on the HTML form and enter a number, the cursor then jumps to the last selected input. This makes input impossible.
When I removed the let statements and put them outside of the function they do not call the correct true/false relationship as they aren't updated as each input has new data added. However, when the let statements are outside of the function, even though they do not accurately reflect the true/false relationship, the cursor does not jump from input to input.
I am very much a beginner so I am not sure what to look for when it comes to troubleshooting this strange phenomenon.
I made a JSBin for this https://jsbin.com/gowulec/edit?html,js,output
When you click all three checkboxes and then try to add data into the input.
I've got a system generated input field that expects it's value to be numeric & over 1,000.
This the HTML for the field
<input type="text" name="fr_goal" id="fr_goal" value="" size="15" maxlength="15">
I've got this JS running on it that gets me almost all the way there, BUT I can't actually tell if the value is greater or equal than the 1000 minimum value I require.
$('#fr_goal').on('keyup', function(evt) {
$("#fr_goal").removeClass('don-active');
var value = evt.target.value;
if (value.length === 0) {
evt.target.className = 'invalid-amount';
return;
}
else if ($.isNumeric(value) && value >= 1000) {
evt.target.className = 'valid-amount';
}
else {
evt.target.className = 'invalid-amount';
$(this).val('');
$(this).attr('placeholder', 'VIP goal must be greater than $1,000');
}
});
Now the else if is my desired outcome, ideally I know it's numeric and over 1000.
But what's happening is that as soon as I enter a number it defaults to my else case since the number is less than 1000.
Does anyone know of a way to listen in on that input once it's not "active" or in use to see what's been put inside it?
Ideally, I don't have to rely on a form submission to get the contents of the field and then present an error message. I'd like to be able to do it all "real-time"
Any help is much appreciated!
Thanks to Calvin for suggesting blur.
I kept everything from the original question almost exactly the same, just tweaked the else if to only look for numeric.
Once the input field is inactive this function runs, and solves my problem perfectly.
$('#fr_goal').blur(function(eval) {
var userInput = eval.target.value;
console.log("the inputted amount was" + userInput);
if (userInput >= 1000) {
eval.target.className = 'valid-amount';
}
else {
eval.target.className = 'invalid-amount';
$(this).val('');
$(this).attr('placeholder', 'VIP goal must be greater than $1,000');
}
});
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";
});
});
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
I see examples for this all over, but for some reason, mine isn't working. I have a textbox that is added dynamically if a certain value is selected in a select list.
The part where the field shows up is working, but I am also trying to add some text to the box, which I can't get to work. I'm also trying to use JS to select the text once it's entered - but haven't gotten that far yet!
Is there something blatantly wrong with this?
function showBox() {
if (document.getElementById("ctl00_Content_WhereFound").value == "Other" || document.getElementById("ctl00_Content_WhereFound").value == "Friend/Employee Referral")
{
document.getElementById('ctl00_Content_WhereDetails').style.display = "inline";
if (document.getElementById("ctl00_Content_WhereFound").value == "Other") {
document.getElementById('ctl00_Content_WhereDetails').innerHTML += 'Enter Other';
} else {
document.getElementById('ctl00_Content_WhereDetails').innerText += "Enter Referral";
}
}
}
First thing I noticed was that you used 'innerHTML' in your if clause and 'innerText' in your else clause. Was that on purpose? They do different things...
It's a pain, but it might be worth using the document.createElement() etc functions to build/modify the dynamic content.
I've had trouble with similar stuff... in general, using the DOM functions rather than innerHTML often fixes it, though it is significantly more verbose. JQuery has some very helpful functions for this.
try this..
function showBox()
{
$Found = document.getElementById("ctl00_Content_WhereFound");
$Where = document.getElementById('ctl00_Content_WhereDetails');
if($Found.value == "Other" || $Found.value == "Friend/Employee Referral")
{
$Where.style.display = "inline";
if($Where.value == "Other")
{
$Where.value = 'Enter Other';
}else
{
$Where.value = "Enter Referral";
}
}
}
You can always assign elements to variables to shorten your code.
This looks like you're attempting to make a change to Asp.Net rendered controls. Make sure you have the actual id of the controls formatted correctly. Typically the UniqueID is formatted like ctl00_Content_WhereFound but the ClientID is formatted ctl00$Content$WhereFound.
innerText isn't supported by at least Firefox. Is there a reason you can't use innerHTML in both cases?
Also, you might want to store the element references to make your code cleaner and faster:
function showBox() {
var eFound = document.getElementById("ctl00_Content_WhereFound");
if (eFound.value == "Other" || eFound.value == "Friend/Employee Referral")
{
var eDetails = document.getElementById('ctl00_Content_WhereDetails');
eDetails.style.display = "inline";
if (eFound.value == "Other") {
eDetails.innerHTML += 'Enter Other';
} else {
eDetails.innerHTML += "Enter Referral";
}
}
}