使用JQuery/Javascript在保存在线表单之前对其进行预处理

Using JQuery/Javascript to pre-process online forms before saving them

本文关键字:预处理 表单 JQuery Javascript 在线 保存 使用      更新时间:2023-09-26

在提交和存储数据库之前,我需要一些帮助来预处理在线表单输入。这个表单实际上是在Joomla 3.1中的ChronoForms组件的帮助下完成的。表单是使用HTML制作的,处理是使用JQuery/JavaScript使用'OnLoad'事件中的'Load JS'动作完成的(对于那些熟悉ChronoForms的人来说)。

简化形式如下:

<form name="online_form" id="online_form">
    <select name="period_year" id="period_year">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
    <select name="period_month" id="period_month">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
    <input type="hidden" name="period" id="period"/>
    <input type="submit" id="submit_form"/>
</form>

我想做的是当用户提交表单时,period_year和period_month的值被组合成一个文本字符串"x年和y个月",并作为period的值。数据库最终将只存储period,而不是period_year和period_month。

我尝试使用事件监听器提交的形式,但它似乎没有工作:

window.addEvent('domready', function() {
    $('online_form').addEventListener('submit', 
        function() { 
            var period_year = $('period_year').value;
            var period_month = $('period_month').value;
            $('period').value=period_year+' year and '+period_month+' months';
        }
    );
}

另一种选择是在select元素上使用onchange属性,如下所示,但它似乎对我也不起作用:

....
<select name="period_year" id="period_year" onchange="process()">...</select>
<select name="period_month" id="period_month" onchange="process()">...</select>
....

头部:

function process() {
    $('period').value=period_year+' year and '+period_month+' months';
};

我做错了什么?还是有其他正确的方法?

需要#选择id为

的元素
$('#online_form').submit(function() {   
//-^---here
     $('#period').val(period_year+' year and '+period_month+' months');
     //-^---here
)};

您需要使用#为ID选择器(" # ID ")也改变valueval()。value用于DOM对象,选择器将返回jQuery对象。如果你想使用值,那么使用[0]索引器将jQuery对象转换为DOM对象。

$('#online_form').addEventListener('submit', 
    function() { 
        $('#period').val(period_year+' year and '+period_month+' months');
        //$('period')[0].value=period_year+' year and '+period_month+' months';
    }
);