user123456789
user123456789

Reputation: 2004

How to set value of textbox created in code behind in javascript

I'm creating a textbox in the code behind:

TextBox txt = new TextBox();
txt.ID = "txtRef" + count + dr["DataField"].ToString();
div.Controls.Add(txt);

And I'm trying to set the value for this textbox in a jquery function but nothing I have tried so far is updating the textbox.

Using document.getElementById('txtRef1j.3rdPartRef').value = 'test'; returns the error Cannot set property 'value' of null.

I also tried $('#txtRef1j.3rdPartRef').val('test') and $('[id$="txtRef1j.3rdPartRef"]').value = 'test'; but the textbox doesn't update.

Upvotes: 0

Views: 268

Answers (3)

Petrashka Siarhei
Petrashka Siarhei

Reputation: 732

Try it: $('[id$="txtRef1j.3rdPartRef"]')[0].value = 'test'; or document.getElementById('txtRef1j.3rdPartRef')[0].value = 'test'; or $('[id$="txtRef1j.3rdPartRef"]').get(0).value = 'test'; or

    document.querySelector('[id$="txtRef1j.3rdPartRef').value = 'test'

or

$('[id$="txtRef1j.3rdPartRef"]').val('test');`

You have errors because jquery object don't has property value,only Dom element has proerty value . When you use document.getElementById, you get NodeList , it is not a Dom-Element. You can read: https://developer.mozilla.org/en-US/docs/Web/API/NodeList

Upvotes: 1

Chidambaram
Chidambaram

Reputation: 444

Check whether the textbox name you set is same in the HTML DOM. Right click the textbox and see the ID by inspect element. If it is not same as you built in c#, then add a line of code txt.ClientIDMode = ClientIDMode.Static; The ID will not be same as it generates dynamic textbox ID.

If the ID is same and still if not working, then run the given jquery and javascript statements in browser console and try they are working or not.

F12, goto console, paste $("#ctl00_ContentPlaceHolder1_txtRef1j.3rdPartRef").val('test'); and press enter. If the value is getting set, then its because of dynamic ID. just add the client id mode as static and it will work.

Upvotes: 0

y.hussain
y.hussain

Reputation: 19

You can try this.

$('#txtRef1j.3rdPartRef').text('test')

Upvotes: 0

Related Questions