Preventing user from inserting * - javascript

I'm trying to prevent user from inserting * in a textbox.
This is what I was trying to do, but here it only detects * if this is the only inserted character. For example texts like: *, etc.
When allowed characters are mixed with *, then it cannot detect it. For example inputs such as: *hjh, etc..
and maybe how to make it replace only * with "" and not the whole field?
<script type="text/javascript">
function testField(field) {
var regExpr = new RegExp("[^*]");
if(!regExpr.test(field.value)) {
field.value = "";
}
}
</script>
<input type="text" id="searchGamesKeyword" class="searchGamesTextBox"
name="searchGamesKeyword" onblur="testField(this);" />

You forgot to anchor your regexp to the start and end of the string: new RegExp("[^*]")
Try this: var regExpr = /^[^*]*$/ -- it asks for zero or more instances of any character except * anchored at the start and end of the string. Maybe /^[^*]+$/ would be better (note +) if you want to force one or more instances of any character except *.

How about this:
function testField(field) {
field.value = field.value.replace(/\*/g,"");
}
Called from onblur=testField(this) as shown in the question it will take the current value of the field and replace any and all asterisks with an empty string, leaving all other characters untouched. So, e.g., "ab*cde*" would become "abcde".
The g on the end of /\*/g is a flag meaning to match globally - without this flag it would just replace the first match.
The reason your code didn't work is that your regex of [^*] will match (i.e., return true from .test()) if there is a non-asterisk character anywhere in the string.

<script type="text/javascript">
function testField(field, event) {
if (event.charCode == 42) {
event.preventDefault();
}
}
</script>
<input type="text" id="searchGamesKeyword" class="searchGamesTextBox"
name="searchGamesKeyword" onkeypress="javascript:testField(this, event);" />​

This should prevent people typing * and copy and pasting it to. Remember to check on the back-end to, because people may have JS disabled in their browsers.
Javascript:
function testField(f)
{
var o='',i,v=f.value;
for(i=0;i<v.length;i++) if(v[i]!='*')o+=v[i];
f.value=o;
}
HTML:
<input type="text" id="searchGamesKeyword" class="searchGamesTextBox" name="searchGamesKeyword" onkeyup="testField(this);" onchange="testField(this);" />
DEMO: http://jsfiddle.net/martinschaer/Sbg6w/ (manually optimized and minified ;))
EDIT:
Using a flag (c) you can avoid having the caret positioned at the end if you try to edit what you've typed so far. Like this:
function testField(f)
{
var t,c,i=0,o='',x="value",v=f[x],l=v.length;
while(i<l){t=v[i++];if(t!='*')o+=t;else c=1}
if(c)f[x]=o
}
​Test it here: http://jsfiddle.net/martinschaer/Sbg6w/

Related

Regex for negative money format - 2decimal place & can go negative

I have an input and on input change, I change it to the money format.
<input type="number" class="currency" step="0.01">
like this:
$('input[type="number"].currency').on('input', function(e) {
this.value = this.value.match(/^-?\d+\.?\d{0,2}/);
});
However, as this gets triggered on every keypress, it doesn't let me write "-" as first character; so it erases it as soon as I click "-"
What kind of regex can I use for allowing that?
https://jsfiddle.net/4zv9wLr3/ - Here is a fiddle, try to write a negative number, it won't allow you to write.
When "number" input triggers the input event, the value was received blank.
$('input[type="number"].currency').on('input', function(e) {
if (e.target.value.length !== 0) {
this.value = this.value.match(/^-?\d+\.?\d{0,2}/);
}
});
I added a guard like this and it worked.

numeral.js live formatting

I would like to live format an input box with Numeral.js.
I tried something like this.
$('#exchangeInputFirst').keyup(function () {
//eur formatting
numeral.language('sk');
$('#exchangeInputFirst').val(numeral($('#exchangeInputFirst').val()).format('0,0.00$');
//to HUF format $('#exchangeInputSecond').val($('#exchangeInputFirst').val()*$('#first').html());
numeral.language('hu');
var string = numeral($('#exchangeInputSecond').val()).format('0,0.00$');
$('#exchangeInputSecond').val(string);
});
The second function is working perfectly (to HUF format), but the first not.
I think you are missing the numeral language file:
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.5.3/languages.min.js"></script>
I cannot reproduce your situation unless I do not include the languages js file. Try your example and hit a key on the first input box:
var a = false;
$('#exchangeInputFirst, #exchangeInputSecond').click(function () {
$(this).caret(0);
});
$('#exchangeInputFirst, #exchangeInputSecond').keyup(function(){
if(a == false){
$(this).val('');
a = true
} else {
numeral.language($(this).data('language'));
$(this).val(numeral($(this).val()).format('0,0.00$'));
$(this).caret(0);
}
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.5.3/numeral.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.5.3/languages.min.js"></script>
<script src="http://zikro.gr/dbg/html/jquery.caret/dist/jquery.caret-1.5.2.min.js"></script>
<input type="text" data-language="sk" id="exchangeInputFirst">
<input type="text" data-language="hu" id="exchangeInputSecond">
UPDATE
You also have a problem with the cursor position. You can solve this by using this jQuery plugin acdvorak/jquery.caret to set the caret position to the beggining of the input each time characters are typed like this:
$(this).val(numeral($(this).val()).format('0,0.00$'));
$(this).caret(0);
Also, I have included the language in input's data like data-language="sk" and now you can read it directly in the keyup event like this:
numeral.language($(this).data('language'));
See my updated snippet. It should now works as you want.

how do I modify an element with text received from input, and how do I stop the disable input if a character terminator is used?

I'm learning jQuery and having trouble figuring something out.
What I need to do is display an alert or note (I used h3) to a user to input their name followed by # (the character terminator). Anything the user types prior to the # symbol should change the text of a span element with id userName, in the heading. After the # is typed no other text should able to be typed. I wanted to have to ghost writer effect of the user typing out their naming in the header, but I couldn't figure that out so I put an input field in. I'm trying to use the if statement to append the keyspressed to the id, or otherwise stop the text from being input.
This is what I have:
$(document).ready(function() {
$('input').on(function() {
$('input').keypress(function(evt) {
var keyPressed=String.fromCharCode(evt.which);
if (keyPressed !== '#')
{
$("userNameInput").append('userName');
}
else {
return false;
}
});
});
});
html:
<header>
<h1>Lab 6</h1>
<h2>Welcome, <span id="userName">User!</span></h2>
<h3>Please enter your name followed by # i.e. John#</h3>
<input id="userNameInput" type="text">
</header>
You had a bunch of issues... I think this is what you were going for though:
JSFiddle
HTML:
<h1>Lab 6</h1>
<h2>Welcome, <span id="userName">User</span>!</h2>
<h3>Please enter your name followed by # i.e. John#</h3>
<input id="userNameInput" type="text">
JS:
$(document).ready(function() {
var appendName = function(evt) {
var keyPressed = String.fromCharCode(evt.which);
if (keyPressed !== '#') {
$("#userName").text(this.value + keyPressed);
} else {
$(this).off();
}
};
$('#userNameInput').on("keypress", appendName);
});
You could also just disable the input field instead of turning off the listener if you wanted... just change $(this).off(); to $(this).prop("disabled",true);
Some problems that I noted in your code were... it looks like you were trying to just do a keypress event, but you had that nested in an on, and the on had no event type. This didn't really make sense but I assume you just wanted the keypress event listener.
This chunk here $("userNameInput").append('userName'); was saying to look for an <userNameInput> and append the string userName to it.
You ignored # but did nothing to stop any new input afterwards.

Removing trailing whitespace and line returns that don't come before/after other characters

I have a text area that I'd like to adjust on a form's submit by removing line returns that don't come before or another set of characters (basically removing line removing line breaks that don't serve as paragraph breaks). Here are a few examples of the line breaks I want to remove:
Line Returns - Before & After
/* Space */
Text
/* Space */
Line Return - Before
/* Space */
Text
Line Return - After
Text
/* Space */
But if there was ever the case where there was in fact text that came after ONE line return then it would be considered okay.
Actual Text
/* Space */
Actual Text
If for argument's sake there was 5 line returns between text, 4 would be removed.
Actual Text
/* Space */
/* Space - Remove Me */
/* Space - Remove Me */
/* Space - Remove Me */
/* Space - Remove Me */
Actual Text
While exploring some solutions I thought of using trim() for dealing with trailing whitespace but this would presumably also remove all line returns. What would be the best way to do this?
Here is the context in which I'm replacing the text:
$(function() {
$(".form").on("submit", function() {
$("textarea").val().trim();
});
});
You can use:
subject.replace(/(?:\s+)?(^.*?$)\s(?:\s+$)/mg, "$1\n");
$('form').on('submit', function() {
$('textarea').val(function(i, subject) {
return subject.replace(/(?:\s+)?(^.*?$)\s(?:\s+$)/mg, "$1\n");
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<textarea rows="8" cols="50">Actual Text
Actual Text</textarea>
<input type="submit" value="Test Me">
</form>
REGEX DEMO
NOTE
I've tested the above regex and it works with all the examples you've provided.
I suppose the following regular expression will work for you:
text.replace(/^\s+|\s*\r?\n\s*(?=(?:\r?\n){2})|\s+$/g, '');
It will remove all whitespace characters (\r, \n and \r\n) before the actual text (^\s+), trailing new lines (\s+$) and three or more new lines in between (\s*\r?\n\s*(?=(?:\r?\n){2})).
$('form').on('submit', function() {
$('textarea').val(function(i, val) {
return val.replace(/^\s+|\s*\r?\n\s*(?=(?:\r?\n){2})|\s+$/g, '');
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<textarea rows="10" cols="85"></textarea>
<div><input type="submit"></div>
</form>

Special HTML characters injected with JS

I have a button (named Benjamin):
<input type="submit" name="btn_submit" value="Next →" />
And on a click event it says 'Loading' and does cool stuff. However, if there is a problem, I want it to change back to its original text while displaying the error message elsewhere.
$('input[name=btn_submit]').click(function() {
$(this).val('Loading');
// Logicy Stuff...
// Error?
$(this).val('Next →');
return false;
});
Somehow, the literal text → is applied to the button, rather than the cool →. How do I fix this?
Html is evaluated with different rules that JavaScript is. Html entities only parsed by the html parser. Either use the unicode literal, like so:
$(this).val('Next \u2192');
Or better, keep track of the original value and then set it back:
var initalButtonValue = $(this).val();
$(this).val('Loading');
// Stuff
$(this).val(initialButtonValue);
Or perhaps even better, use HTML data attributes to store the states.
<input type="submit" name="btn_submit" value="Next →" data-normal-value='Next →' data-loading-value='Loading...' />
Then:
// Set to loading
$(this).val($(this).data("loading-value"));
// and back to normal
$(this).val($(this).data("normal-value"));
Put the actual → character in there instead of a HTML entity. Using an entity only works if you set HTML content - and form values are not HTML at all.
When using it inside <input value="..."> it only works because in this case the entity is replaced while the HTML is parsed, so the value gets the actual character.
How about storing the value of the element with $.data() and retrieving it later:
$('input[name=btn_submit]').click(function() {
$.data(this, 'value', this.value);
$(this).val('Loading');
// Logicy Stuff...
// Error?
$(this).val($.data(this, 'value'));
return false;
});
Here is a demo: http://jsfiddle.net/39thm/ (the setTimeout is just for demonstration)
Docs for $.data(): http://api.jquery.com/jquery.data
Also you are using thr $(this) selector more than once, if you use it a bunch then it's a good idea to cache the selection:
$('input[name=btn_submit]').click(function() {
var $this = $(this);
$.data(this, 'value', this.value);
$this.val('Loading');
// Logicy Stuff...
// Error?
$this.val($.data(this, 'value'));
return false;
});
if you know the code for the character, you can add it to a JavaScript string with .fromCharCode():
var s = "hello " + String.fromCharCode(1023); // just a made-up number
You can also embed characters in JavaScript strings if you know their hex code:
var s = "string \u1023 string";
$("input[name='btn_submit']").click(function() {
var elem = $(this);
elem.data( "orgText", elem.val() ).val('Loading');
window.setTimeout(
function(){
elem.val( elem.data("orgText") );
}, 1000 );
return false;
});​
jsFiddle

Categories

Resources