2011-07-14 39 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); 
}); 
相關問題