如何在javascript函数中创建一个动态元素?

时间:2016-01-25 06:36:35

标签: javascript asp.net

我创建了一个功能,可以在选中复选框时启用文本框,并在未选中时禁用它。以下是我创建的功能。但它给了我一个错误“txtelement为null”。以下是我的代码:

 function enableDisable(chk,txt) {
        var txtelement = document.getElementById(txt);

        if (chk.checked) {
            txtelement.disabled = false;
        }
        else {
            txtelement.disabled = true;
            txtelement.value = "";
        }

        if (!txtelement.disabled) {
            txtelement.focus();
        }
    }

我这样调用了上面的javascript函数:

<asp:CheckBox ID="chk1" runat="server" onclick = "enableDisable(this,'txt1');"/>

文本框的id名称是'txt1'。 上述功能有什么问题?

2 个答案:

答案 0 :(得分:0)

您需要在页面中包含ID txt1 的文本元素。

尝试添加<input id ="txt1" />

之类的内容

答案 1 :(得分:0)

更改复选框的声明如下。

package com.yourcompany.yourapp.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Struts 1.3.10 encoding problem
 * 
 * @see http://www.coderanch.com/t/557874/Struts/Struts-encoding
 */
public class CharacterEncodingFilter implements Filter { 
    private FilterConfig fc; 

    @Override
    public void destroy() {
        // TODO Auto-generated method
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req; 
        HttpServletResponse response = (HttpServletResponse) resp; 

        request.setCharacterEncoding("UTF8"); 
        response.setCharacterEncoding("UTF8"); 

        chain.doFilter(request, response); 

        request.setCharacterEncoding("UTF8"); 
        response.setCharacterEncoding("UTF8"); 
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
    }
}

还要确保JS正确加载。如果您在控制台上看到<asp:CheckBox ID="chk1" runat="server" onClick = "enableDisable(this,'txt1');"/> 功能Uncaught reference error。它与JS load有关。

我还建议您参考asp.net文档,详细了解enableDisableOnClientClick差异以及如何呈现它们以便更好地理解。