Aniruddha Raje Aniruddha Raje - 4 months ago 9
HTML Question

Dynamically remove Characters from Textarea

I have a textarea which will have a dynamic maxlength, depending on the Dropdown.

I have a situation in which,

If the User chooses to select an option with longer maxlength ie. "b" in by case,

Then types in characters

and later

chooses an option with shorter maxlength, ie. "a" in my case



I need to remove the extra number of characters from the textarea, typed in when longer option from dropdown was selected.

Here's a sample code:



var maxLen;

function lengthChange() {
var id = $('#ta').attr("id");
var dropdown = $('#choice').val();
var taValue = $('#ta').val();
var len = taValue.length;
if (dropdown == "a") {
maxLen = "5";
$('#' + id).attr("maxlength", maxLen);
} else {
maxLen = "10";
$('#' + id).attr("maxlength", maxLen);
}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="choice" name="choice" onchange="lengthChange()">
<option value="a">a</option>
<option value="b">b</option>
</select>

<textarea id="ta" name="ta" rows="4" cols="20" maxlength="5">
</textarea>




Answer

var maxLen;

function lengthChange()
{
    var $ta = $('#ta');
    var dropdown = $('#choice').val();
    var taValue = $ta.val();

    maxLen = dropdown === 'a' ? 5 : 10;
    $ta
        .attr('maxlength', maxLen)
        .val(taValue.substr(0, maxLen));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="choice" name="choice" onchange="lengthChange()">
  <option value="a">a</option>
  <option value="b">b</option>
</select>

<textarea id="ta" name="ta" rows="4" cols="20" maxlength="5">
</textarea>

Comments