1

I am having 2 text box.. Value of first text box should been an length of second text box.. Eg: If user gives First text box value as "10", then my second text box should not allow user to type more than 10 characters..

Here is my code..

function field_length() {
  var fieldValue = document.getElementById('Length').value;
  alert(fieldValue);
}
<input type="text" name="Length[]" maxlength="2" class="required" id="Length" onkeypress="return isNumberKey(event);" placeholder="Field length" class="form-control">
<input type="text" name="Label[]" class="required" id="Label" maxlength="" onClick="field_length();" placeholder="Field Label" class="form-control">

In this code what i did was.. if user is gives value for first field as "5", on tap of second field it will alert the value.. But i want that value to be assigned to Maxlenght attribute. Give me some idea..

8
  • try this document.getElementById("yourID").maxLength .. L should be capital. And please do some research before asking such easy questions as there are already so many posts available if you google it .. thanks Commented Oct 27, 2016 at 5:58
  • change .value to .maxlength Commented Oct 27, 2016 at 5:58
  • you should use jquery $('#Length').attr('maxlength','5') Commented Oct 27, 2016 at 6:00
  • @MayankVadiya he wants to achieve this using javascript as per what his code suggests .. Commented Oct 27, 2016 at 6:01
  • @MayankVadiya How's jquery performance? Commented Oct 27, 2016 at 6:03

3 Answers 3

5

Get length and set maxLength attribute.

function field_length(){
   var length = $("#Length").val();
  $("#Label").attr("maxlength", length)
}
Sign up to request clarification or add additional context in comments.

Comments

1
You can use setAttribute
<script type="text/javascript">
     function field_length()
    {
     var fieldValue= document.getElementById('Length').value;
    document.getElementById("Label").setAttribute('maxlength',fieldValue);
     }
    </script>


<input type="text" name="Length[]" maxlength="2"  class="required" id="Length" onkeypress="return isNumberKey(event);" placeholder="Field length"  class="form-control">
<input type="text" name="Label[]" class="required" id="Label" maxlength="" onClick="field_length();" placeholder="Field Label" class="form-control">

Comments

0

Try this:

$("#Label").attr("maxlength", length);

or

$("#Label").prop("maxlength", length);

NOTE:

As of jQuery 1.6. , the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.