user1848942
user1848942

Reputation: 355

Error in javascript code if I wrote runat="server"

Code in html:

        <input type="text" name="fileName" id="fileName" class="file_input_textbox" readonly="readonly" />

        <div class="file_input_div">
          <input type="button" value="Search files" class="file_input_button" />
          <input type="file" class="file_input_hidden" onchange="javascript: document.getElementsByName('fileName')[0].value = this.value" />
        </div>

It's work correctly. But if i will write like this:

<input runat="server" type="text" name="fileName" id="fileName" class="file_input_textbox" readonly="readonly" />

    <div class="file_input_div">
      <input type="button" value="Search files" class="file_input_button" />
      <input type="file" class="file_input_hidden" onchange="javascript: document.getElementsByName('fileName')[0].value = this.value" />
    </div>

it doesnt't work woth error: document.getElementsByName(...).0' is null or not an object

Upvotes: 2

Views: 1974

Answers (2)

user123456
user123456

Reputation: 2659

You can use the id of the control but the problem if you have master page, and you are using a template or grid then the id will be changed. So you can set the client id mode to static so that in this case it will not be changed

Example

< input runat="server" type="text" name="fileName" id="fileName" class="file_input_textbox" readonly="readonly" />

Or you can get the client id of the control.

Example :

document.getElementById(<%= fileName.ClientID %>);

Hope this is helpful..

Upvotes: -1

Aristos
Aristos

Reputation: 66641

When you add the runat="server" then the id and the name is rendered different and may change by asp.net

To get the rendered name you use the UniqueID and get it as <%=fileName.UniqueID%>, so your code as it is must be done:

<input runat="server" type="text" name="fileName" id="fileName" class="file_input_textbox" readonly="readonly" />

    <div class="file_input_div">
      <input type="button" value="Search files" class="file_input_button" />
      <input type="file" class="file_input_hidden" 
         onchange="javascript: document.getElementsByName('<%=fileName.UniqueID%>')[0].value = this.value" />
    </div>

I verify it and thats the way, the name and ids change when this is added inside a master page. If they are alone on a page with out master page, then they stay as it is, but if you added them on a master page, they change and you need to get them by the rendered id.

Note that the clientidmode="Static" on the input control is not working for the name but only for the id so if you add it and try to keep the id the same, then you must get your element by id and not by name.

Upvotes: 5

Related Questions