填充表单onkeydown ENTER并阻止表单提交

时间:2012-12-27 07:32:09

标签: javascript jquery forms javascript-events onsubmit

JS

$('.add_to_list').live('keydown',function (e){
    if(e.keyCode == '13'){
        var holder=$(this).attr('hold'),
            val=$(this).val();
            if(holder == 'mf' ||holder == 'mp'){
                    var v='#'+holder;   
                    h='<li class="entery deletable"><input type="hidden" name="'+holder+'[]" value="'+val+'">'+val+'</li>';
                    $(v).append(h);
                    $(this).val('');
            }
        e.prevent_default();    
        return false;
    }
    $('#save_clinic').submit(function(){return false;});
    });

HTML

<form accept-charset="utf-8" method="post" id="save_clinic" action="#">
<p>
<b>Findings</b>
<ol id='mf'></ol>
<input type="text" hold="mf" class="add_to_list" value="" name="">
<!--the input hv no name cause i dont want it to be submitted, this is for adding only-->
</p>
<p>
<b>Medical Procedures:</b>
<ol id=mp></ol>
<input type="text" hold="mp" class="add_to_list" value="" name="">
<!--the input hv no name cause i dont want it to be submitted, this is for adding only-->
</p>
<input type=submit>
</form>

问题: 我想阻止在按键ENTER上提交,只允许提交按钮点击提交 但我现在的js阻止提交两者,如果我删除     $(&#39; #save_clinic&#39;)。submit(function(){return false;}); 从js然后当用户尝试填充表单时,表单自动汇总。

有人可以告诉我wt是这里的问题吗? example

3 个答案:

答案 0 :(得分:1)

该函数称为preventDefault(无下划线,大写'D'),而不是prevent_default。试一试,删除这一行:

$('#save_clinic').submit(function(){return false;});

答案 1 :(得分:0)

我认为这应该在外面:

$('.add_to_list').live('keydown',function (e){
   if(e.keyCode == '13'){
    var holder=$(this).attr('hold'),
        val=$(this).val();
        if(holder == 'mf' ||holder == 'mp'){
                var v='#'+holder;   
                h='<li class="entery deletable"><input type="hidden" name="'+holder+'[]" value="'+val+'">'+val+'</li>';
                $(v).append(h);
                $(this).val('');
        }
   }
   e.prevent_default(); // take this out from the if   
   $('#save_clinic').submit(function(){return false;});
});

答案 2 :(得分:0)

$('.add_to_list').live('keydown',function (e){
        if(e.keyCode == '13'){
            var holder=$(this).attr('hold'),
                val=$(this).val();
                if(holder == 'mf' ||holder == 'mp' ||holder == 'orders'){
                        var v='#'+holder;   
                        h='<li class="entery deletable"><input type="hidden" name="'+holder+'[]" value="'+val+'">'+val+'</li>';
                        $(v).append(h);
                        $(this).val('');
                }
            //return false;
            e.preventDefault(); 

http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx

现在都工作正常..谢谢所有