在事件处理器中获取表单元素 [英] Getting Form Element in event handler

查看:81
本文介绍了在事件处理器中获取表单元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为所有 HTML表单添加一个 onSubmit 事件来验证提交文件大小并防止它通过 javascript 提交。

I want to add an onSubmit event to ALL of the HTML Forms to validate submitting File Size and prevent its submission via javascript.

问题是我没有 id 表格,既不是文件输入元素的那些。现在,我如何访问所需的输入

the problem is that I do not have the id of the form, neither those of the file input element. Now, How can I access to the value of the desired input?

的值可能有几个<$ c $每个页面中都有 id ,但每个 form 都只有一个 文件输入元素。元素的 id 也是未知的。

It may be several forms in each page with unknown id's but each form has just one file input element. The id of the element is also unknown.

示例 form

example form:

<form onSubmit="checkSize(1000000)" enctype="multipart/form-data" action="changedata.php" method="post" >
      <input class="user_upload_file" type="file" name="file" />
      <input type="submit" value="submit" />
 </form>

以及我使用的javascript:

and the javascript I use:

function checkSize(max_img_size)
{

    //file_input_id is unknown so, the following input could not be defines:
    var input = document.getElementById("file_input_id");
    // check for browser support (may need to be modified)
    if(input.files && input.files.length == 1)
    {           
        if (input.files[0].size > max_img_size) 
        {
            alert("File size is too big. ");
            return false;
        }
    }
    return true;
}

另外,我不可能更改所有文件输入 s>的id> ,这非常耗时。我也不使用 jQuery

Also, it is not possible for me to change the id of all the file inputs, It's really time consuming. I also DO NOT use jQuery.

感谢您的意见

Thanks for your ideas

推荐答案

通过内部事件属性包含的事件处理程序在它们所连接的元素的上下文中调用,您可以像其他变量一样传递它。 b
$ b

Event handlers included via intrinsic event attributes are called in the context of the element to which they are attached, you can pass that around like any other variable.

onsubmit="checkSize(1000000, this)"

从那里你可以使用标准的DOM方法,比如 getElementsByTagName querySelector code>元素属性来查找后代元素。

From there you can use standard DOM methods like getElementsByTagName and querySelector along with the elements property to find descendent elements.

这篇关于在事件处理器中获取表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆