Nithya
Nithya

Reputation: 1121

How to assign javascript variable value to HTML Attribute?

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..

Upvotes: 1

Views: 5835

Answers (3)

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

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.

Upvotes: 0

Rajesh Patel
Rajesh Patel

Reputation: 2036

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">

Upvotes: 1

selami
selami

Reputation: 2498

Get length and set maxLength attribute.

function field_length(){
   var length = $("#Length").val();
  $("#Label").attr("maxlength", length)
}

Upvotes: 5

Related Questions