Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

maxlength not working if value is set from js code

I am having the following HTML block in my page.

<input type="text" id="fillingInput"/>
<input type="text" id="filledInput" maxlength="5"/>
<input type="button" onclick="$('#filledInput').val($('#fillingInput').val());"/>

when the button is clicked, the value of fillingInput is set as value for filledInput. But the maxlength is not considered while setting value like this. Any solution?

like image 711
Sureshkumar Natarajan Avatar asked Aug 30 '13 10:08

Sureshkumar Natarajan


People also ask

Why Maxlength is not working in react?

Props in React are case sensitive, so make sure to use maxLength (camelCase), and not maxlength . Notice that the `type` attribute of the input field is set to text . This wouldn't work if the field's type were set to number .

How do you limit the input value of a number?

Complete HTML/CSS Course 2022 To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field. After limiting the input box to number, if a user enters text and press submit button, then the following can be seen “Please enter a number.”

How do you use Maxlength?

The maxlength attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an <input> or <textarea> . This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the input or textarea has no maximum length.

How do you limit input value in HTML?

The max attribute specifies the maximum value for an <input> element. Tip: Use the max attribute together with the min attribute to create a range of legal values. Note: The max and min attributes works with the following input types: number, range, date, datetime-local, month, time and week.


2 Answers

Try slice:

<input type="button"
  onclick="$('#filledInput').val($('#fillingInput').val().slice(0,5));"/>
like image 126
skolima Avatar answered Sep 30 '22 14:09

skolima


Try this

$(document).ready(function () {
$('#add').click(function () {
    var str = $('#fillingInput').val();
    if (str.length > 5) {
        str = str.substring(0, 5);
        $('#filledInput').val(str);
    }

   });
});
like image 27
Boss Avatar answered Sep 30 '22 15:09

Boss