Prevent user from entering additional characters when maximum length reached - javascript

Using angularjs, I'm not satisfied with the ng-maxlength tag. I want the input field to block the user from entering additional characters when the max length has been hit. So instead of ng-maxlength, I tried writing a directive that would validate the input on keydown/keypress:
.directive('vldMaxLength', function() {
return function (scope, element, attr) {
element.bind('keydown keypress', function (event) {
if(event.target.value.length >= 10 && (event.which !== 8 && event.which !== 46)) {
event.preventDefault();
}
});
};
})
This works decently, but the user is unable to highlight a portion of the string and replace with different characters. Maybe there's something I can add to the directive to allow for this? Or maybe there's an easier way to get this functionality instead of using a directive.
JSFiddle: http://jsfiddle.net/DwKZh/147/

You could use the straight HTML version:
<form action="demo_form.asp">
Username: <input type="text" name="usrname" maxlength="10"><br>
<input type="submit" value="Submit">
</form>

Related

how do I get javascript function to run on enter key, as opposed to click?

When I click this button, it runs the function and all is well.
<input id="input_listName" /><button id="btn_createList">add</button>
when I click it, it runs this:
$('#btn_createList').click(function(){
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
});
When I press it, it appends the value in the input to the <li> element.
How do I redo this so that instead of running function on click, the function runs when I click the 'enter key'?
I'd like to hide the submit key all together. Please note, there are no form tags around input and submit, as this is an API app and I'm just trying to filter and not really submit anything.
Don't.
You have a form. Treat it as such.
document.getElementById('input_listName').addEventListener('submit', function(e) {
e.preventDefault();
const li = document.createElement('li');
li.append(this.listName.value);
document.querySelector(".ul_current").append(li);
// optionally:
// this.listName.value = ""
}, false);
<form id="input_listName">
<input type="text" name="listName" />
<button type="submit">add</button>
</form>
<ul class="ul_current"></ul>
Making it a form provides all of the benefits that a browser does for you. On desktop, you can press Enter to submit it. On mobile, the virtual keyboard may also provide a quick-access submit button. You could even add validation rules like required to the <input /> element, and the browser will handle it all for you.
I think what you want is a check for which key was pressed, correct?
To do that, you simply need to check for
event.keyCode === 13
So your code would be something similar to the following:
$('#btn_createList').keypress(function(event){
if (event.keyCode === 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
});
Hopefully that does the trick!
With the help of the event, you can catch the pressed enter (keycode = 13) key, as in my example.
Was it necessary?
$('#btn_createList').keypress(function(event){
if (event.keyCode == 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
});
<input id="input_listName" /><button id="btn_createList">add</button> this syntax is technically wrong, your tag is starting with <input> and ending with </button>. Also you can add a simple check to your function that if user haven't entered anything into the input field that should return nothing.
you can also have a look at this cheat sheet to know more about keycodes https://css-tricks.com/snippets/javascript/javascript-keycodes/
$('#btn_createList').keypress(function(event){
if($('#input_listName').val()) {
if (event.keyCode == 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
}
});
<div id="btn_createList">
<input id="input_listName" type="text">
<ul class="ul_current">
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>

How to avoid using white space in react input field, when "onChange" is already reserved for different function?

I have an input field with the "onChange" event on them, that fetches elements of an array with the "forEach" method, and it works pretty well. But I also want to add one additional feature to input fields - to avoid typing blank spaces. How should I attach this additional feature?
I tried to use "onKeyDown" event to avoid white spaces but probably it gives me an error. Below is a code of input field:
mainList.js
<input
type="text"
className="form-control"
value={sprNotDeleted.value}
onKeyDown=
{this.AttributeValidation(sprNotDeleted.value)}
onChange={this.inputChanged.bind(
this,
sprNotDeleted.id
)}
/>
inputChanged()
inputChanged = (index, e) => {
const { sprNotDeleted } = this.state;
sprNotDeleted.forEach(point => {
point.value = point.id === index ? e.target.value : point.value;
});
this.setState({ sprNotDeleted, isEdit: false });
};
AttributeValidation()
AttributeValidation(value) {
this.setState({
sprNotDeleted: value.replace(/\s/g, "")
});
}
Here is a corresponding error if I will use "onKeyDown":
TypeError: sprNotDeleted.map is not a function
Observed that, for the onKeyDown you are not binding the event to this.
onKeyDown= {this.AttributeValidation.bind(
this,
sprNotDeleted.value
)}
<input
type="text"
className="form-control"
value={sprNotDeleted.value}
onKeyDown= {this.AttributeValidation.bind(
this,
sprNotDeleted.value
)}
onChange={this.inputChanged.bind(
this,
sprNotDeleted.id
)}
/>
As you are accessing the this scope recommending to use this bind()
Instead of handling through onKeyDown() can you try using pattern regex handling as its a input type text you can handle it through pattern itself?
<input
type="text"
pattern="[^\s]+"
/>
Happy Coding!!
I haven't really tried ur code, but it seems like u have several problems here:
In onKeyDown event handler, function this.AttributeValidation is called directly without being passed as an event handler. So that function is executed which most likely not what u want.
When this.AttributeValidation is executed, sprNotDeleted becomes a String instead of an array, which does not have foreach method attached in its prototype.
This is for suggestion:
In onChange handler, consider creating an arrow function instead of bind the function, since u used arrow function for defining the function, binding to this will be unnecessary.
you can use keydown on input,for first word. for react hooks
const handleKeyDown = (e) => {
if (e.key === " " && name.length===0) {
e.preventDefault();
}
};
<!-- begin snippet: js hide: false console: true babel: false -->
<input type="text" name="name" onKeyDown={handleKeyDown}/>
<input type="text" name="name" onKeyDown={handleKeydown}/>
this will prevent space on first but you cant add spaces in any sentence afterwards for that you can give condition of length
I used this for my use case,
I had a controlled state
Wanted the user to allow typing empty spaces/white spaces
Can validate the state on external event like a button click
<form action=''>
<InputComponent
placeholder="Enter a name"
value={folderName}
onChange={(value) => {
setFolderName(value);
}}
/>;
<ButtonComponent
variant={"primary"}
disabled={folderName.length === 0 || folderName.trim().length === 0}
onClick={handleClick}
>
SAVE
</ButtonComponent>;
</form>

Username Length Verification jQuery

I am attempting to create jQuery form which is automatically updated every time the user clicks.
At the moment I am working on querying if the username is correct length; if it is not, it will make the input box outlined red.
This is my current code (which does not seem to function at all).
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$(document).click(function(e) {
if (!$(e.target).closest('#jq-user-getval').length) {
if ( $('#jq-user-getval').val() != '' ) {
if( $("#jq-user-getval").val() < 4) {
$("#jq-user-getval").addClass('border-force');
}
}
}
})
})
</script>
as you can see, I have made it so that when the user clicks away from the input box, it will check if the box is empty. If it is empty, it will check if the length is less than 4 characters, then it is supposed to add a class forcing the red outline. This is not working, however.
this is the HTML, I am unsure if the problem lies here or not:
<form action="" method="post">
<input id="jq-user-getval jq-user-class" type="text" name="username">
</form>
I am trying to replicate Microsoft's "Hotmail" registration form, if you can suggest any changes.
Your id value is incorrect. Technically, id cannot contain spaces. Change your <input /> to:
<input id="jq-user-getval" class="jq-user-class" type="text" name="username" />
The way you are using .val() < 4 is also wrong. You cannot compare like that with a string:
"hello" < 4; // This is meaningless.
"hello".length < 4; // You should use this.
Use .blur() function for this:
$(function () {
$("#jq-user-getval").blur(function () {
if (this.value.trim().length !== 0 && this.value.trim().length < 4)
$(this).addClass("border-force");
});
});
If you are dynamically loading the <input />, then you can delegate the event this way:
$(function () {
$(document).on("blur", "#jq-user-getval", function () {
if (this.value.trim().length !== 0 && this.value.trim().length < 4)
$(this).addClass("border-force");
});
});
I have added .trim() for extra security, like people might get away putting spaces.
There's no real reason for you to use the .click() function anywhere here. The clicking away really triggers blur event on the <input />.
You can use Jquery Validation.
Basic Example :
<input id="username" name="username" maxlength="4" type="text" required>
$("#yourFormID).validate();
if input is not valid and then you addClass red outline
you must use errorPlacement,errorClass properties in validate() function

disable enable button on keypress

i want to enable button when there is some value in text box
this is working fine all most but for one value it will fail
like is enter 1 in text box
http://jsfiddle.net/akash4pj/YhQN4/
js
<script>
$(document).ready(function(){
$("#textbx").keypress(function(){
if ($("#textbx").val().length > 0) {
$("#btn").removeAttr('disabled');
}
});
$("#textbx").blur(function(){
if ($("#textbx").val().length ==0) {
$("#btn").attr('disabled','disabled');
}
});
});
</script>
html code
<input id="textbx" type="text" /><button id="btn" disabled="disabled">go</button>
Use keyup instead of keypress, like this:
$("#textbx").blur(function () {
if ($("#textbx").val().replace(/\s{1,}/g, "").length == 0) {
$("#btn").attr('disabled', 'disabled');
}
});
Also, I've added .replace(/\s{1,}/g, "") in the code as well. This ensures (indirectly) that if the user only types spaces, the button will still be disabled when the text input is blurred.
Fiddle.
The keypress event occurs before the browser processes the key, i.e. before the character is appended to the input value, so when the first key is pressed, the textbox is still empty when your functions checks the value length.
The keyup event occurs after the browser has appended the character to the input, so if you trigger on keyup instead of keypress your code should function the way you want.
I'd suggest:
$("#textbx").on('keyup blur', function() {
$("#btn").prop('disabled', $.trim(this.value).length === 0);
});
As mentioned in other answers you should use keyup, but you don't need to listen for blur as well:
$("#textbx").keyup(function(){
if ($("#textbx").val().trim().length > 0) {
$("#btn").removeAttr('disabled');
}
else
$("#btn").attr('disabled','disabled');
});
Fiddle

jquery: event for simulating live typing

Part 1:
Is there any event I can use to get a callback when the user 'change' the input field. My definition of change is to simulate the following effect. say, I want to update a label while the user typing in the input box. I tried jquery "change" event. It works, but doesn't have the live effect. Once the input field is updated, I have to click on somewhere in the screen to update the label.
Part 2:
well, if this is not a good idea, I may prevent the form being submitted on enter key. Not sure about a good way to do it either. Quick search found this answer.
<form action="" method="post" onsubmit="return false;">
not tested yet, but hopefully the submit button may still works.
EDIT: tested, and onsubmit="return false;" prevents even the submit button.
thanks,
bsr.
This should do it:
input.bind('keydown keypress', function() {
setTimeout(function() {
label.text(input.val());
}, 0);
});
Live demo: http://jsfiddle.net/simevidas/qTBxv/
Part 1
You can just update it every keyUp, but I would suggest you at least wait 1 second after the user finishes typing.
var timer;
var changeTxt = function(){
// Change label text here.
};
$("#myInput").keyup(function(){
clearTimeout(timer);
timer = setTimeout(changeTxt, 1000);
});
Part 2
That example you posted stops a form from submitting. Is that your goal?
EDIT:
I think you are trying to control the form's submission?
$("#myForm").submit(function(){
if(/* Your condition here */){
return false;
//Only if your condition is true, stop form submission
}
});
Did you try out the keydown or keypress event?
I would prefer a combination of both, form and field validation:
Find working sample here: http://jsfiddle.net/ezmilhouse/9mNc4/1/
your html:
<form method="post" action="post.php">
<input type="text" name="" value="" />
<label>Name</label>
<div></div>
</form>
your js:
// prevent form from being posted empty
$('form').live('submit', function(evt){
if ( $('input', this).val() === "" ) {
evt.preventDefault();
alert('Field is required!');
}
});
// validate form field on the fly
var min = 3;
$('input').live('keyup change', function(){
if ($(this).val().length < min) {
$('div').html('<span class="invalid">min. 3 characters.</span>');
} else {
$('div').html('<span class="valid">ok!</span>');
}
});
there is something called oninput that you can use.
<form oninput="xx.value=aa.value">
<input type="text" name="aa" value="">
<output name="xx" for="aa"> </output>
</form>

Categories