Developer Developer - 2 months ago 7
jQuery Question

Get Value From Dynamic textarea

In the given code i have create a dynamic textarea, now when i try to get insert value from that textarea. It gives me null value.

<form name="myForm">
<textarea name="fname" <%#!((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).Code.Equals("OTH", StringComparison.InvariantCultureIgnoreCase) ? "style='display: none;'" : string.Empty%> id="text<%#((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).ID%>" maxlength="50" placeholder="Enter other item details"></textarea>
</form>


Given is my function to get value from textarea box:

function ValidateData() {
if ($("textarea").is(":visible")) {
//var x = document.forms["myForm"]["fname"].value;
var x = document.getElementsByName("fname").value;
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}

Answer

Your textarea was dynamic so you can used textarea change event. You can use given code on load, so whenever you input text it sets on OtherItemValue:

var OtherItemValue;
 $("textarea").on('input change keyup', function () {
                if (this.value.length) {
                    OtherItemValue = this.value;
                } else {
                    OtherItemValue = "";
                }
            });

And then you can used below code:

function ValidateData() {
    if ($("textarea").is(":visible")) {
 if (OtherItemValue == null || OtherItemValue == "") {
            alert("Please Enter Other Item Details");
            return false;
        }
    }
    else return true
}