I have to define an input text which accepts only integer numbers.
I tried with a regular expressions but the decimal part of the value is still visible.
I used this function:
$(document).on("input","input", function(e) {
this.value = this.value.replace(/[^\d\\-]/g,'');
})
How about this one?
$('input').on('input blur paste', function(){
$(this).val($(this).val().replace(/\D/g, ''))
})
<input>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Simple and easy to use. Try it:
edited: also call in onblur event to prevent paste.
function numOnly(selector){
selector.value = selector.value.replace(/[^0-9]/g,'');
}
<input type="text" onkeyup="numOnly(this)" onblur="numOnly(this)">
You can detect on keydown if is numeric and you can check on paste event if is numeric and remove all non-numeric. This remove dot too.
Original source : keydown detect : Paste remove
This code below has been modified from the original source.
Please try:
$( "#input" ).on("paste", function() {
setTimeout(function(){
if ($('#input').val() != $('#input').val().replace(/\D/g,""))
{
$('#input').val($('#input').val().replace(/\D/g,""));
}
},10)
});
$('#firstrow').on('keydown', '#input', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13])||/65|67|86|88/.test(e.keyCode)&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firstrow">
<input id="input" type="text">
</div>
Finally I solved the above issue with my requirement to type only number is
$(document).on("input", ".skilltxt", function(e) {
this.value = this.value.replace(/[^\d]/g,'');
});
$(".skilltxt").on('paste',function(e) {
if(gBrowser=='IE') {
var clipboardData, pastedData;
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
}
else if((gBrowser=='Firefox')|| (gBrowser=='Chrome')){
var pastedData = (e.originalEvent || e).clipboardData.getData('text/plain');
window.document.execCommand('insertText', false, pastedData)
}
if(Math.floor(pastedData) == pastedData && $.isNumeric(pastedData)){
$(this).val($(this).val().replace(/[^\d]/g,''));
}
else{
return false;
}
});
Related
I am trying to get value of a text area on pressing enter but getting value undefined.
jQuery(".comment-form .comments-text").on('keypress', function (e) {
if(e.which === 13 && !e.shiftKey) {
e.preventDefault();
var text = jQuery(this).value;
console.log(e);
}
});
on keypress is working fine but cannot get the text I am entering.
This code should work:
HTML
<form class="comment-form">
<textarea class="comments-text"></textarea>
</form>
JQuery
$(".comment-form .comments-text").on('keypress', function(e) {
if (e.which === 13 && !e.shiftKey) {
e.preventDefault();
var text = e.target.value;
console.log('text', text);
}
});
you can get value of textArea with val(); method in jquery
let value = $("textArea").val();
alert(value);
I have an input field that should switch all spaces entered to a '_' in real time. Meaning when the user hits the spacebar in that input field a underscore is being displayed instead of a space. I am quite new to javascript/jquery so please don't judge my setTimeout-n00bidity to hard:
$( "#inputId" ).keydown(function (key){
var code = key.keyCode || key.which;
if( code == 32 ) { //Space key code
$( this ).val(
function( index, value ){
return value.substr( 0, value.length - 1 );
})
setTimeout(
function(){
$(this).val($(this).val() + "_");
}, 10
)
}
})
You may listen to the input event and then replace the spaces with underscores in the listener. This way, you don't need to have a timeout.
$("#inputId").on('input', function(key) {
var value = $(this).val();
$(this).val(value.replace(/ /g, '_'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputId">
No jQuery, simple solution:
var input = document.getElementById("inputId");
input.oninput = function (e) {
e.target.value = e.target.value.replace(' ', '_');
}
<input type="text" id="inputId" />
Use the keyup event rather than keydown, and simply replace all spaces with _. The keyup event runs after the value has been modified based on what the user typed, so you don't need to check the charCode.
$("#inputId").keyup(function() {
$(this).val(function(i, oldval) {
return oldval.replace(/ /g, '_');
});
});
You can use Change value of key board input
ex:
<div>
<label>Test:</label>
<input type="text" id="test">
</div>
$("#test").on("keypress", function (e) {
if (32 == e.keyCode) {
e.preventDefault();
var newString = $("#test").val() + "_";
$("#test").val(newString);
}
});
Related: jQuery: Change keyboard value when input
$( "#inputId" ).keyup(function (key){
var code = key.keyCode || key.which;
if( code == 32 ) { //Space key code
$(this).val($(this).val().replace(/ /g,"_"));
}
});
I have a textbox which needs to be filled with website URL. So when user places the cursor in the textbox then the textbox should prefill with "http://" (Not a placeholder).
If the user does not enter anything and moves to the next textbox then the textbox have empty value
If the user fills the textbox then the value is unchanged
I tried below Javascript code but did not work:
if (document.activeElement.id == 'input-textbox-id' && !document.activeElement.value) {
document.querySelector("#input-textbox-id").value="http://";
} else if (document.activeElement.id != 'input-textbox-id' && (!document.activeElement.value || document.activeElement.value == 'http://')) {
document.querySelector("#input-textbox-id").value="";
}
You can use the focus and blur events for this.
Assuming that the variable textBox contains the reference to your textBox element, you can use the following code:
let textBox = document.getElementById("a");
textBox.addEventListener("focus", function() {
if (!this.value) {
this.value += "http://";
}
});
textBox.addEventListener("blur", function() {
if (this.value == "http://") {
this.value = "";
}
});
<input type="text" id="a">
You will need to attach event listener by using addEventListener. Events you need: focus and focusout.
We add .http-prefill class for all inputs. We iterate over inputs array and attach event.
Please do not forget to remove eventListener when you are done eg. you unload the form.
To do so, just copy the code for adding listeners and replace addEventListener with removeEventListener.
inputs.forEach(function(input) {
input.removeEventListener('focus', onFocus);
input.removeEventListener('focusout', onFocusOut);
});
Example code:
var fillValue = 'http://';
var onFocus = function() {
this.value = fillValue;
}
var onFocusOut = function() {
if (this.value === fillValue) {
this.value = '';
}
}
var inputs = document.querySelectorAll('.http-prefill');
inputs.forEach(function(input) {
input.addEventListener('focus', onFocus);
input.addEventListener('focusout', onFocusOut);
});
.http-prefill {
width: 100%;
margin-bottom: 5px;
}
<input class="http-prefill" name="input-0" />
<input class="http-prefill" name="input-1" />
<input class="http-prefill" name="input-2" />
<input class="http-prefill" name="input-3" />
you can use some key events like onKeyDown and when keydown you can get hold of old value and append it with new value.
let keyPressed = true
function onKeyDown(event) {
if(keyPressed && event.keyCode !== 8)
{
keyPressed = false;
let oldvalue = document.getElementById('input-textbox-id').value;
document.getElementById('input-textbox-id').value = "http://"+oldvalue
}
if(!document.getElementById('input-textbox-id').value)
{
keyPressed = true;
}
}
here is working code. http://jsbin.com/zoxiwokepi/edit?html,output
Below code disables 0 as the first character in #foo.
However, you can bypass this by typing 123, then drag to select 123 and putting 0. (or ctrl+a on input)
Is there a way to block this scenario?
$('input#foo').keypress(function(e){
if (this.value.length == 0 && e.which == 48 ){
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" />
I would handle the input, propertychange, and paste events. Then use regex to match for anything that begins with 0 and replace the current value with the value minus the leading 0.
http://jsfiddle.net/SeanWessell/5qxwpv6h/
$('input ').on('input propertychange paste', function (e) {
var val = $(this).val()
var reg = /^0/gi;
if (val.match(reg)) {
$(this).val(val.replace(reg, ''));
}
});
Bug fix reported by Kevin/Updated per recommendations of canon:
http://jsfiddle.net/SeanWessell/5qxwpv6h/2/
$('input').on('input propertychange paste', function (e) {
var reg = /^0+/gi;
if (this.value.match(reg)) {
this.value = this.value.replace(reg, '');
}
});
I think you're looking for the keydown jQuery event as opposed to the keypress event. Here's some move info on the difference between the two. Try regex to get rid of leading zeroes:
$('input#foo').keydown(function(e){
this.value = this.value.replace(/^0+/, '');
});
Here's the fixed version :
<input id="foo" />
$('input#foo').keyup(function(e){
if(this.value.substring(0,1) == "0")
{
this.value = this.value.replace(/^0+/g, '');
}
});
jsfiddle : http://jsfiddle.net/ewmb1yq9/4/
This could work:
$('input#foo').keyup(function(e) {
if((this.value+'').match(/^0/)) {
this.value = (this.value+'').replace(/^0+/g, '');
}
});
The only thing that could bother you with this solution is that zero is displayed for a second and then deleted, since we are using keyup event.
A quick demo
Accept only numeric values not prefixed by zero. Supports Ctrl + A:
var escapeKeys = [8, 46];
$('input#foo').keyup(function (e) {
if ($.inArray(e.keyCode, escapeKeys) != 0) {
if ((this.value + String.fromCharCode(e.keyCode)).match(/^[1-9][0-9]*$|^$/) != null) {
this.lastValidValue = this.value + String.fromCharCode(e.keyCode);
} else if (this.lastValidValue) {
this.value = this.lastValidValue;
} else {
this.value = "";
}
} else {
this.lastValidValue = this.value;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" />
If you want to catch the changes to the input's value (including the changes made by dragging part of the text for example), you can watch the input event.
$('input#foo').on("input", function(){
alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" />
You could add a "submit" event to validate whether it's entered or not, regardless of how it could have gotten there:
$( "form" ).submit(function( event ) {
if ( $( "input:first" ).val() != 0 ) {
$( "span" ).text( "Validated..." ).show();
return;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<p>Type 'Anything but 0' to validate.</p>
<form action="javascript:alert( 'success!' );">
<div>
<input type="text">
<input type="submit">
</div>
</form>
<span></span>
jQuery's working is example is last on page here (https://api.jquery.com/submit/)
NOTE: The most important part will be to add the "event.preventDefault()" action, because that will keep the form from accidentally submitting.
I made simple web chat, bubles ( messages) above one text field (input message) and send button. How to make that input text field holds focus and not to lose when I click on something else (to focus always be on input with id="input_message") ?
var el = document.getElementById('input_message');
el.focus();
el.onblur = function () {
setTimeout(function () {
el.focus();
});
};
Here's the fiddle: http://jsfiddle.net/MwaNM/
Here's a dirty hack.
<input type="text" id="input_message" />
<script type="text/javascript">
with (document.getElementById('input_message')) {
onblur = function(e) {
var elm = e.target;
setTimeout(function(){elm.focus()});
}
onkeydown = function(e) {
var key = e.which || e.keyCode;
if (key == 9) e.preventDefault();
// code for tab is 9
}
}
</script>
var inputElement = document.getElementById("input_message");
inputElement.focus();
inputElement.addEventListener("blur", function(event){
inputElement.focus();
});
http://jsfiddle.net/653w1mpv/