Austin Muts

Austin Muts

  • 1.4k
  • 333
  • 126.5k

Move cursor and limit characters using JQUERY

Feb 19 2018 10:48 PM
The code below is working but needs to be modified to move a cursor to the newly created textbox so that a user can continue typing when a maximum of 40 characters is reached in each textbox.Also to limit the number of characters when they reach 1000 and be able to display all typed characters in another textbox.(EventNature).
 
@{
ViewBag.Title = "Home Page";
}
<br/>
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<span id="charsLeft"></span>
<br/>
<input id="btnAdd" type="button" value="New Line" onclick="AddTextBox()"/>
<div class="form-group">
@Html.TextArea("EventNature",new { maxlength=50, // or other value
style = "width: 200px; height: 100px;" })
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function GetDynamicTextBox(value) {
var div = $("<div />");
var textBox = $("<input />").attr("type", "textbox").attr("name", "DynamicTextBox").attr("maxlength", "40").attr("onKeyUp", "CallScript(this)");
textBox.val(value);
div.append(textBox);
var button = $("<input />").attr("type", "button").attr("value", "X");
button.attr("onclick", "RemoveTextBox(this)");
div.append(button);
return div;
}
function AddTextBox() {
var div = GetDynamicTextBox("");
$("#TextBoxContainer").append(div);
}
function RemoveTextBox(button) {
$(button).parent().remove();
}
$(function () {
var values = eval('@Html.Raw(ViewBag.Values)');
if (values != null) {
$("#TextBoxContainer").html("");
$(values).each(function () {
$("#TextBoxContainer").append(GetDynamicTextBox(this));
});
}
});
function CallScript(vale) {
var len = vale.value.length;
if (len == 40) {
var div = GetDynamicTextBox("");
$("#TextBoxContainer").append(div);
//move cursor to the next textbox
}
var contents = $(vale).val();
$("#EventNature").val(contents);
}
$(function () {
$('#TextBoxContainer').keypress(function () {
//return this.value.length < 6
if($(this).attr('maxlength'))
{
AddTextBox();
}
//var charsLeft = this.value.length;
//$("#charsLeft").text(charsLeft);
});
});
</script>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
$(function () {
alert("@ViewBag.Message")
});
</script>
}

Answers (1)