I am trying to disable the textbox using keyup functionality. I have a TextArea and a Text Box. Now i use a keyup operation on backspace key, like if the length of content inside textarea is 3 it should disable the textbox. I also have an alert message which pops when the length of content in text area is 3. Code worked for the pop up but it doesnot worked for the textbox. What am i missing? Please help. Here is my code:
$('#comment').keyup(function() {
if (event.which == 8) {
var txt = $('#comment').val().length;
if(txt == 3)
{
alert("backspace");
$("#text1").attr("diasbled", "diasbled");
}
}
});
And here is the JSfiddle for the purpose.
You have some typo here it should be disabled not diasbled
Try this
$('#comment').keyup(function () {
var len = $(this).val().length;
if (len >= 3) {
$("#text1").prop("disabled", true);
}
else{
$("#text1").prop("disabled", false);
}
});
DEMO
You need to do:
1) this.value.length to get the total characters length of your textarea
2) From jQuery version 1.6 , use .prop() instead of .attr() to set the properties of an element
3) Correct the typo: it should be disabled not diasbled
$('#comment').keyup(function () {
if (this.value.length >= 3) {
$("#text1").prop("disabled", true);
} else {
$("#text1").prop("disabled", false);
}
});
Updated Fiddle
Your code is fine.. but you mispelled the "disabled" in your code. Here's the sample..
<html>
<head>
<title>js test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<input type="text" value="" id="comment" />
<input type="text" value="" id="text1" />
<script type="text/javascript">
$(document).ready(function()
{
$('#comment').keyup(function(e) {
if (e.which == 8) {
var txt = $('#comment').val().length;
if(txt == 3)
{
alert("backspace");
$("#text1").attr("disabled", "disabled");
}
}
});
});
</script>
</body>
Use prop instead of attr also pass event to function
$('#comment').keyup(function (event) { //and event here
if (event.which == 8) {
if ($(this).val().length >= 3) {
$("#text1").prop("disabled", true);
}
}
});
Related
So I have an input bar, where text can be typed in.
I am trying to get the console.log to run as soon as the user clicks on backspace and because of that leaves the input with no value.
Right now the console.log only runs if the backspace is clicked while there isn't any value in the input.
GOAL - The console should ONLY run if clicking on backspace CAUSES the input to be empty.
$("#friendsNames").keydown(function(event){
if (event.keyCode == 8) {
if ($("#friendsNames").val() == "") {
console.log("Works!");
}
}
});
<input type="text" name="namesOfFriend" id="friendsNames" value="" />
I'd recommend not tracking key strokes at all, but monitoring the content of the box using the input event which fires when that content changes:
$("#friendsNames").on('input', function(event) {
if (this.value.length === 0) {
console.log("Works!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="namesOfFriend" id="friendsNames" value="" />
This ensures that any interaction that results in the input becoming empty will trigger your code.
Try to make event on keyup coz if input field empty and you're going to enter first character in it console.log() calls. So try this code or go through mention link JSFiddle
JAVASCRIPT Code -
$("#friendsNames").keyup(function(event) {
if (event.keyCode == 8 && $(this).val() == "") {
console.log("Works!");
}
});
$("#friendsNames").keypress(function(event) {
if (event.keyCode == 8 || $(this).val() != "") {
alert("Works!");
}
});
As I understand, you want console.log to execute only where this is any value in the input box, else it shouldn't execute, right? Based on this, below is the code:
$("#friendsNames").on('input', function(){
var inputValue = $(this).val();
if(inputValue.length == 0)
console.log("Works!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="namesOfFriend" id="friendsNames" value="" />
I have just begun my exploration of javascript and jquery, and would sincerely appreciate any help with my current dilemma. The feature that I am trying to build involves a number of steps:
The 'enter' key triggers an event.
The appropriate value ('About', 'Contact', or 'Extra') within the input field will open a new page.
The input field (residing within a <p> element) is then cloned and inserted, allowing the user to input another value.
My dilemma involves binding. Once the input field has been cloned, the page that was first opened will continue to open regardless of a new input value. Meaning, if the 'About' page was first opened, then the 'About' page will continue to open even when a new value ('Contact' or 'Extra') is added to the inserted input field. Here is the code that I have written:
javascript
$(function() {
function cloneInput() {
var clonedElement = $("p").last().clone(true);
$("input").last().prop("disabled", true);
clonedElement.insertAfter($("p").last()).prop("id", "seven");
$("input").last().prop("value", "").focus();
}
$("#input-text").keydown(function(event) {
var keypressed = event.keyCode || event.which;
var text = $("#input-text").val();
if (keypressed == 13) {
if (text == "About") {
window.open("about.html", "_blank");
cloneInput();
} else if (text == "Contact") {
window.open("contact.html", "_blank");
cloneInput();
} else if (text == "Extra") {
window.open("extra.html", "_blank");
cloneInput();
} else {
$("<p>Command not found</p>").insertAfter("#six").prop("id", "error");
}
}
});
});
html
<!DOCTYPE html>
<html>
<head>
<link href="css/stylesheet.css" type="text/css" rel="stylesheet"/>
<script src="js/jquery-3.1.0.js"></script>
<script src="js/scripts.js"></script>
</head>
<body id="index-body">
<p id="one">Hello friend. My name is $%^&*$^%. Welcome to ##$%%%*&.</p>
<p id="two">To learn more, please enter a command:</p>
<p id="three">> About</p>
<p id="four">> Contact</p>
<p id="five">> Extra</p>
<p id="six">> %<input type="text" maxlength="40" autofocus id="input-text"></p>
</body>
</html>
result
<p id="six">
<input type="text" maxlength="40" autofocus id="input-text" disabled>
</p>
<p id="seven">
<input type="text" maxlength="40" autofocus id="input-text">
</p>
I have searched stackoverflow and learned about .on(), .off(), and .change(). In addition, I have utilized these methods when refactoring my code. Still, I cannot find a solution. Thank you in advance.
Note: I am aware that my naming conventions need to be cleaned up.
bind your event on document itself not on the element you want to trigger
$(document).on('keydown', "#input-text", function(event) {
e.preventDefault();
// all your code..
});
see my other answer.
If you want to call a function on dynamically created elements, you should use
$(document).on(<event>, <object>, function(event) {
});
Example : This will perform the action on clicking the elements with class class1 ( even on dynamically created elements )
$(document).on('click', '.class1', function(event) {
/* do something here */
});
In your case :
$(document).on("click", "#input-text", function(event) {
var keypressed = event.keyCode || event.which;
var text = $("#input-text").val();
if (keypressed == 13) {
if (text == "About") {
window.open("about.html", "_blank");
cloneInput();
} else if (text == "Contact") {
window.open("contact.html", "_blank");
cloneInput();
} else if (text == "Extra") {
window.open("extra.html", "_blank");
cloneInput();
} else {
$("<p>Command not found</p>").insertAfter("#six").prop("id", "error");
}
}
});
Everything is looking good only one issue is accessing filed value instead of $('#input-text').val() use $(this).val() always gets current element value..
$(function() {
function cloneInput() {
var clonedElement = $("p").last().clone(true);
$("input").last().prop("disabled", true);
clonedElement.insertAfter($("p").last()).prop("id", "seven");
$("input").last().prop("value", "").focus();
}
$("#input-text").keydown(function(event) {
var keypressed = event.keyCode || event.which;
var text = $(this).val();
if (keypressed == 13) {
if (text == "About") {
window.open("about.html", "_blank");
cloneInput();
} else if (text == "Contact") {
window.open("contact.html", "_blank");
cloneInput();
} else if (text == "Extra") {
window.open("extra.html", "_blank");
cloneInput();
} else {
$("<p>Command not found</p>").insertAfter("#six").prop("id", "error");
}
}
});
});
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 am using jquery to validate textbox value.
I have 2 textbox, txt1 & txt2. now, i wrote a jquery function.
$("#txt1").blur(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
$("#txt1").focus();
}
else {
$("#scarriername").hide();
}
});
$("#txt2").blur(function () {
if ($("#txt2").val() == "") {
$("#sscaccode").show();
$("#txt2").focus();
}
else {
$("#sscaccode").hide();
}
});
Now, issue is. when i run the project. my position is on txt1 and when u use Tab to go txt2 with null or blank value. Focus event fire for both one & browser become hang due to infinite loop of FOCUS.
so, how can i handle it?
You should insert a setTimeout in order to set the focus after the blur event.
Second, you should insert a semaphore in order to avoid a loop (see code and comments):
var status = "valid"; // semaphore
$("#txt1").blur(function (e) {
// if we are in programmatically focus, ignore this handler
if(status == "invalid")
return ;
if ($("#txt1").val() == "") {
$("#scarriername").show();
// set semaphore
status = "invalid";
// use setTimeout in order to set focus in the right moment
setTimeout(function() {$("#txt1").focus(); status = "valid"},0);
}
else {
$("#scarriername").hide();
}
});
// same as txt1
$("#txt2").blur(function () {
if(status == "invalid")
return ;
if ($("#txt2").val() == "") {
$("#sscaccode").show();
setTimeout(function() {$("#txt2").focus(); status = "valid"},0);
}
else {
$("#sscaccode").hide();
}
});
DEMO http://jsfiddle.net/SszUf/
try this
<input type="text" id="txt1" />
<input type="text" id="txt2" />
$("#txt2").focus(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
$("#txt1").focus();
}
//alert(1);
});
hope this help you
Apparently when you hit the tab button you trigger blur event for both text boxes. With your code when txt1 gets blurred and has no content you get the focus on txt1, but when you do that you also trigger the blur event for txt2 and since it does not have any text in it you get the focus back to txt2. This keeps on going and going, focusing on txt1 and then txt2 and then txt1 and then txt2... You could put a simple if check on the second blur event handler to see if txt1 is still empty, and if so keep the focus on txt1 not allowing the client to pass to txt2:
$("#txt1").blur(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
$("#txt1").focus();
}
else {
$("#scarriername").hide();
}
});
$("#txt2").blur(function () {
if ($("#txt2").val() == "" && $("#txt1").val() != "") {
$("#sscaccode").show();
$("#txt2").focus();
}
else {
$("#sscaccode").hide();
}
});
This is also one of the approach to solve your problem on pressing tab key.
$("#txt1").bind('keydown',function(e)
{
if(e.keyCode == 9)
{
if ($("#txt1").val() == "") {
$("#scarriername").show();
return false;
}
else {
$("#scarriername").hide();
}
}
});
$("#txt2").bind('keydown',function(e)
{
if(e.keyCode == 9)
{
if ($("#txt2").val() == "") {
$("#sscaccode").show();
return false;
}
else {
$("#sscaccode").hide();
}
}
});
$("#txt1").blur(function () {
if ($("#txt1").val() == "") {
$("#scarriername").show();
if ($("input:focus").length == 0)
$("#txt1").focus();
}
else {
$("#scarriername").hide();
}
});
Just add a line can solve this problem
By the way, the #scarriername should not be something like popup window, which will trigger other blur events
You can test the file below:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<input id="txt1"><input id="txt2"><input id="txt3"><input id="txt4">
<hr>
<h1 id="h1"></h1>
</body>
<script type="text/javascript">
$(function(){
$("input").blur(function () {
if ($(this).val() == "") {
document.getElementById("h1").innerHTML += "123";
$(this).focus();
}
});});
</script>
</html>
I want to change the maxlength of a textbox with JavaScript or jQuery: I tried the following but it didn't seem to help:
var a = document.getElementsByTagName('input');
for(var i=0; i<a.length; i++) {
if((a[i].type!= 'radio')||(a[i].type!= 'checkbox'))
a[i].maxlength = 5;
}
document.getElementsByTagName('input')[1].maxlength="3";
$().ready(function()
{
$("#inputID").maxlength(6);
});
What am I doing wrong?
Not sure what you are trying to accomplish on your first few lines but you can try this:
$(document).ready(function()
{
$("#ms_num").attr('maxlength','6');
});
The max length property is camel-cased: maxLength
jQuery doesn't come with a maxlength method by default. Also, your document ready function isn't technically correct:
$(document).ready(function () {
$("#ms_num")[0].maxLength = 6;
// OR:
$("#ms_num").attr('maxlength', 6);
// OR you can use prop if you are using jQuery 1.6+:
$("#ms_num").prop('maxLength', 6);
});
Also, since you are using jQuery, you can rewrite your code like this (taking advantage of jQuery 1.6+):
$('input').each(function (index) {
var element = $(this);
if (index === 1) {
element.prop('maxLength', 3);
} else if (element.is(':radio') || element.is(':checkbox')) {
element.prop('maxLength', 5);
}
});
$(function() {
$("#ms_num").prop('maxLength', 6);
});
without jQuery you can use
document.getElementById('text_input').setAttribute('maxlength',200);
set the attribute, not a property
$("#ms_num").attr("maxlength", 6);
$('#yourTextBoxId').live('change keyup paste', function(){
if ($('#yourTextBoxId').val().length > 11) {
$('#yourTextBoxId').val($('#yourTextBoxId').val().substr(0,10));
}
});
I Used this along with vars and selectors caching for performance and that did the trick ..
For those who are facing problem like me with accepted answer:
$(document).ready(function()
{
$("#ms_num").attr('maxlength','6');
});
You may use on focus instead of ready function:
$(document).on('focus', '#ms_num', function() {
{
$(this).attr('maxlength','6');
});
This will make sure to set the maxlength attribute when the input field is focused or selected.
You can make it like this:
$('#inputID').keypress(function () {
var maxLength = $(this).val().length;
if (maxLength >= 5) {
alert('You cannot enter more than ' + maxLength + ' chars');
return false;
}
});
<head>
<script type="text/javascript">
function SetMaxLength () {
var input = document.getElementById("myInput");
input.maxLength = 10;
}
</script>
</head>
<body>
<input id="myInput" type="text" size="20" />
</body>
<head>
<script type="text/javascript">
function SetMaxLength () {
var input = document.getElementById ("myInput");
input.maxLength = 10;
}
</script>
</head>
<body>
<input id="myInput" type="text" size="20" />
</body>