Setting maxlength of textbox with JavaScript or jQuery - javascript

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>

Related

How to set two jquery functions with one identify

I need use two jQuery functions with one ID working on edge and chrome browsers. Chrome works perfect but edge don't.
$("#myInput").keyup(function() {
$("#myInput").val($(this).val().replace(",", "."));
});
$("#myInput").change(function() {
alert("hello world");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" type="text" />
Can you explain me why and how to solve it.
Perhaps you mean this:
Change entering a comma to entering a fullstop and trigger the hello after 1 second of inactivity
var tId;
$("#myInput").on("keypress", function(e) {
clearTimeout(tId);
if (String.fromCharCode(e.which) == ",") {
this.value += ".";
e.preventDefault();
}
tId = setTimeout(function() {
console.log("Hello")
}, 1000);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="myInput" />
It seems that in the Edge browser, the change event will not trigger, you could try to trigger the change function in the jquery focusout event, code as below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" type="text" />
<script type="text/javascript">
$(function () {
$("#myInput").keyup(function () {
$("#myInput").val($(this).val().replace(",", "."));
console.log("keyup event trigger");
});
$("#myInput").focusout(function () {
//check whether it is Edge browser
var ua = window.navigator.userAgent;
var edge = ua.indexOf('Edge/');
if (edge > 0) {
$("#myInput").trigger("change");
}
});
$("#myInput").change(function () {
//alert("hello world");
console.log("change event triger");
});
})
</script>
the result as below:

jquery keyup function: enabling/disabling a textbox using keyup()

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);
}
}
});

Adding keyup events to dynamically generated elements using jquery

I have a button which creates text boxes dynamically and there is another button 'Clear'.
If there is no text in any of the text field then the clear button is disabled or else it will be enabled. It works for the text box that is created when the dom is loaded but for the dynamically created textboxes it does not work.
Here is the HTML
<input type="button" value="Click Me" class="a" />
<input type="button" value="Clear" class="a" id="clearBasicSearch" />
<div id="basicSearchFields">
<input type="text" />
</div>
Javascript
$(".a").click(function () {
$("#basicSearchFields").append("<input type='text' class='b' />");
});
/*$(".b").live("keyup", function () {
//alert('you pressed ' + $(this).val());
$(this).val($(this).val().toUpperCase());
});*/
var toValidate = $("#basicSearchFields input[type='text']");
$("#clearBasicSearch").removeClass('hidden').removeClass('button').attr('disabled', true);
toValidate.live('keyup', function () {
console.log("hi");
var valid = false; //default is false
toValidate.each(function () {
if ($(this).val().length > 0) {
valid = true; //non-empty element found
return false; //break
}
});
$("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
});
JSfiddle link - http://jsfiddle.net/TpExS/
Please help me out!!
Try this
$(document).on('keyup', "#basicSearchFields input[type='text']",function () {
console.log("hi");
var valid = false; //default is false
var toValidate = $("#basicSearchFields input[type='text']");
toValidate.each(function () {
if ($(this).val().length > 0) {
valid = true; //non-empty element found
return false; //break
}
});
$("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
});
$(document).on('keyup', "input#basicSearchFields",function () {
// do something here
}
Here is another possible solution http://jsfiddle.net/TpExS/2/
Note: JQuery 2.0.2 used
Javascript
$(document).ready(function(){
var fields = $('input[class=b]');
for(var i = 0; i < fields.length; i++){
$(fields[i]).on('keyup', validateFields);
}
});
$(".a").click(function () {
var newField = $('<input/>').attr('type', 'text').attr('class', 'b');
$(newField).on('keyup', validateFields);
$("#basicSearchFields").append(newField);
});
function validateFields(){
if($(this).val().length){
$('#clearBasicSearch').attr('disabled', false);
return;
}
$('#clearBasicSearch').attr('disabled', true);
var fields = $('input[class=b]');
for(var i = 0; i < fields.length; i++){
if($(fields[i]).val().length){
$('#clearBasicSearch').attr('disabled', false);
return;
}
}
}
Try
$("#basicSearchFields").delegate("input[type='text']", 'keyup', function () {
validate();
});
function validate(){
console.log("hi");
var valid = false; //default is false
var toValidate = $("#basicSearchFields input[type='text']");
toValidate.each(function () {
if ($(this).val().length > 0) {
valid = true; //non-empty element found
return false; //break
}
});
$("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
}
Demo: Fiddle
Simple, Updates your global "toValidate" variable when you add more elementson the click.
$(".a").click(function () {
$("#basicSearchFields").append("<input type='text' class='b' />");
toValidate = $("#basicSearchFields input:text");
});
Why? The time you set toValidate, it will return an array at that moment, you should updates it in each time there are new elements, or check for all of then inside the live event.

jQuery toggle not work when the argument are functions

I'm trying to use toggle() to complete my click events. In this case, I read the API, and use toggle(function1, function2, ...). But it was weird. The tag a just hide when I click it, rather than execute those functions inside.
Here is my javascript code.
function clickMe(){
$("#lime").toggle(
function(){
var names = document.getElementsByName("selectOne");
var len = names.length;
if (len > 0) {
var i = 0;
for (i = 0; i < len; ++i) {
names[i].checked = true;
}
}
},function(){
var names = document.getElementsByName("selectOne");
var len = names.length;
if (len > 0) {
var i = 0;
for (i = 0; i < len; ++i) {
names[i].checked = false;
}
}
}
) ;
}
And here is HTML code.
selectAll
<form>
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
</form>
I'm waiting for the comments. Thanks advance!
This functionality has been removed in jQuery 1.9.
Use this instead (works for older versions too):
$(function ($) {
var inputs = $('input[name=selectOne]');
$("#lime").click(function () {
inputs.prop( 'checked', ! inputs.prop('checked') );
});
});
Here's the fiddle: http://jsfiddle.net/3GQDU/
As pointed out by #Andre, if the first is checked by hand, it will then uncheck all. If that's not what you want, use this:
$(function ($) {
var inputs = $('input[name=selectOne]'),
flag = true;
$("#lime").click(function () {
inputs.prop( 'checked', flag );
flag = ! flag;
});
});
Here's the fiddle: http://jsfiddle.net/3GQDU/1/
$(function(){
var check = true;
$("#lime").click(function(){
$('input[name=selectOne]').prop('checked', check);
check = !check;
});
});
By doing this, you won't need the 'onclick' attribute in #lime element. Just remove it, and let jQuery bind the click handler for you. This is usually a good thing, as it separates structure and behaviour.
Edit:
If you need a function that reproduces old jQuery toggle behaviour, here's it:
(function($){
$.fn.toggleHandlers = function(eventType){
var i = 0;
var handlers = $.makeArray(arguments).slice(1);
return this.bind(eventType, function() {
handlers[i].apply(this, arguments);
if(i < handlers.length -1)
i++;
else
i = 0;
});
};
})(jQuery);
The difference from jQuery toggle is that it gets one extra parameter (the first one), that is the event type. So, it works with events other than click. Call it as:
$("#myElement").toggleHandlers('click', handler1, handler2[, handler3]);
See fiddle: http://jsfiddle.net/andreortigao/j9MH2/

Focus Input Box On Load

How can the cursor be focus on a specific input box on page load?
Is it posible to retain initial text value as well and place cursor at end of input?
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />
There are two parts to your question.
1) How to focus an input on page load?
You can just add the autofocus attribute to the input.
<input id="myinputbox" type="text" autofocus>
However, this might not be supported in all browsers, so we can use javascript.
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
2) How to place cursor at the end of the input text?
Here's a non-jQuery solution with some borrowed code from another SO answer.
function placeCursorAtEnd() {
if (this.setSelectionRange) {
// Double the length because Opera is inconsistent about
// whether a carriage return is one character or two.
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
// This might work for browsers without setSelectionRange support.
this.value = this.value;
}
if (this.nodeName === "TEXTAREA") {
// This will scroll a textarea to the bottom if needed
this.scrollTop = 999999;
}
};
window.onload = function() {
var input = document.getElementById("myinputbox");
if (obj.addEventListener) {
obj.addEventListener("focus", placeCursorAtEnd, false);
} else if (obj.attachEvent) {
obj.attachEvent('onfocus', placeCursorAtEnd);
}
input.focus();
}
Here's an example of how I would accomplish this with jQuery.
<input type="text" autofocus>
<script>
$(function() {
$("[autofocus]").on("focus", function() {
if (this.setSelectionRange) {
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
this.value = this.value;
}
this.scrollTop = 999999;
}).focus();
});
</script>
Just a heads up - you can now do this with HTML5 without JavaScript for browsers that support it:
<input type="text" autofocus>
You probably want to start with this and build onto it with JavaScript to provide a fallback for older browsers.
$(document).ready(function() {
$('#id').focus();
});
function focusOnMyInputBox(){
document.getElementById("myinputbox").focus();
}
<body onLoad="focusOnMyInputBox();">
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" onfocus="this.value = this.value;" value = "initial text">
A portable way of doing this is using a custom function (to handle browser differences) like this one.
Then setup a handler for the onload at the end of your <body> tag, as jessegavin wrote:
window.onload = function() {
document.getElementById("myinputbox").focus();
}
very simple one line solution:
<body onLoad="document.getElementById('myinputbox').focus();">
Working fine...
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
Try:
Javascript Pure:
[elem][n].style.visibility='visible';
[elem][n].focus();
Jquery:
[elem].filter(':visible').focus();
This is what works fine for me:
<form name="f" action="/search">
<input name="q" onfocus="fff=1" />
</form>
fff will be a global variable which name is absolutely irrelevant and which aim will be to stop the generic onload event to force focus in that input.
<body onload="if(!this.fff)document.f.q.focus();">
<!-- ... the rest of the page ... -->
</body>
From: http://webreflection.blogspot.com.br/2009/06/inputfocus-something-really-annoying.html
If you can't add to the BODY tag for some reason, you can add this AFTER the Form:
<SCRIPT type="text/javascript">
document.yourFormName.yourFieldName.focus();
</SCRIPT>
Add this to the top of your js
var input = $('#myinputbox');
input.focus();
Or to html
<script>
var input = $('#myinputbox');
input.focus();
</script>

Categories

Resources