2011-07-14 41 views
1

下面这个jQuery代码是一个文本输入框,以帮助用户在一个格式化的方式输入时间。我在哪里添加这个jQuery代码到我的页面中的表单?

我已经测试了这里

http://jsfiddle.net/nNpjm/2/

我现在希望把它列入我的HTML表单然而现在,我不知道它会去吗?

如果它在Onchange标签去?

input.click(function() { 

     $(this).prop({ 
      selectionStart: 0, //moves cursor to poition zero in input box 
      selectionEnd: 0 
     }); 

    }).keydown(function() { 

     var sel = $(this).prop('selectionStart'), 
      val = $(this).val(), 
      newsel = sel === 2 ? 3: sel; 
      newsel = sel === 5 ? 6: newsel; 

     $(this).val(val.substring(0, newsel) + val.substring(newsel + 1)) 

     .prop({ 
      selectionStart: newsel, 
      selectionEnd: newsel 
     }); 
    }); 

感谢

回答

0

要让球滚动,只需将JavaScript下方的表单放在同一页面上即可。您最终想要将所有javascript放在外部.js文件中,并通过<script src="my_javascript_file.js"></script>包含它们

我已经在下面包含了您的脚本。你会发现,it's wrapped in CDATA tags - 这是一个故障安全处理的XHTML文档类型,使得XML解析器完全忽略了脚本,并在遇到不熟悉的字符不会失败:

<form id="form" method="post" action="whatever.html"> 
    <!-- additional fields, submit button, etc --> 
</form> 
<script type="text/javascript"> 
/* <![CDATA[ */ 
    var input = $("<input>", { //this bit will be removed in the form 
     name: 'time', 
     val: '00:00:00', 
     maxlength: '8', 
     size: '5' 
    }); 

    input.click(function() { 

     $(this).prop({ 
      selectionStart: 0, 
      selectionEnd: 0 
     }); 

    }).keydown(function() { 

     var sel = $(this).prop('selectionStart'), 
      val = $(this).val(), 
      newsel = sel === 2 ? 3: sel; 
      newsel = sel === 5 ? 6: newsel; 

     $(this).val(val.substring(0, newsel) + val.substring(newsel + 1)) 

     .prop({ 
      selectionStart: newsel, 
      selectionEnd: newsel 
     }); 
    }); 

    $(function(){ 
     $('#form').append(input); 
    }); 

/* ]]> */ 
</script> 
+0

感谢元素,但使用PHP即时通讯让我的形式-1,我只是希望脚本互动与我的PHP生成的输入由codeigniter php制作的字段。 感谢 – giedrere

+0

你只粘在你看来这个代码,并用您在您的控制器指定任何变量包含的形式'' HTML。只要形式有'ID =“形式”'那么你可以使用'$(“#形式”)追加(输入);'。如果你决定使用另一个表单,只需用#表单的id替换表单的id即可。 – AlienWebguy

+0

感谢我得到它的工作 – giedrere

1

嵌入代码中的script标签内,并改变第一行:这样

$(function(){ 
    $('#inputId').click(... 
}); 
+0

你能告诉我?感谢 – giedrere

+0

如果你看看他的小提琴他引用'input'作为变量,因为他是动态创建 – AlienWebguy

0

将其放置在文件加载函数:

$(document).load(function(){  
    var input = $("<input>", { //this bit will be removed in the form   
     name: 'time',   
     val: '00:00:00',   
     maxlength: '8',   
     size: '5'  
    });  
    input.click(function() {   
     $(this).prop({    
      selectionStart: 0,    
      selectionEnd: 0   
     });  
    }).keydown(function() {   
     var sel = $(this).prop('selectionStart'),    
     val = $(this).val(),    
     newsel = sel === 2 ? 3: sel;    
     newsel = sel === 5 ? 6: newsel;   
     $(this).val(val.substring(0, newsel) + val.substring(newsel + 1)).prop({    
      selectionStart: newsel,    
      selectionEnd: newsel   
     });  
    });  
    $('body').append(input); 
}); 
相关问题