10個jQuery表單操作代碼片段
代碼片段1: 在表單中禁用“回車鍵”
大家可能在表單的操作中需要防止用戶意外的提交表單,那么下面這段代碼肯定非常有幫助:
$("#form").keypress(function(e) {</pre> <pre class="javascript" style="color: #000000;">if (e.which == 13) { return false; } });
代碼片段2: 清除所有的表單數據
可能針對不同的表單形式,你需要調用不同類型的清楚方法,不過使用下面這個現成方法,絕對能讓你省不少功夫。
function clearForm(form) { // iterate over all of the inputs for the form // element that was passed in $(':input', form).each(function() { var type = this.type; var tag = this.tagName.toLowerCase(); // normalize case // it's ok to reset the value attr of text inputs, // password inputs, and textareas if (type == 'text' || type == 'password' || tag == 'textarea') this.value = ""; // checkboxes and radios need to have their checked state cleared // but should *not* have their 'value' changed else if (type == 'checkbox' || type == 'radio') this.checked = false; // select elements need to have their 'selectedIndex' property set to -1 // (this works for both single and multiple select elements) else if (tag == 'select') this.selectedIndex = -1; }); };
代碼片段3: 將表單中的按鈕禁用
下面的代碼對于ajax操作非常有用,你可以有效的避免用戶多次提交數據,個人也經常使用:
禁用按鈕:
$("#somebutton").attr("disabled", true);
啟動按鈕:
$("#submit-button").removeAttr("disabled");
代碼片段4: 輸入內容后啟用遞交按鈕
這個代碼和上面類似,都屬于幫助用戶控制表單遞交按鈕。使用這段代碼后,遞交按鈕只有在用戶輸入指定內容后才可以啟動。
$('#username').keyup(function() { $('#submit').attr('disabled', !$('#username').val()); });
代碼片段5: 禁止多次遞交表單
多次遞交表單對于web應用來說是個比較頭疼的問題,下面的代碼能夠很好的幫助你解決這個問題:
$(document).ready(function() { $('form').submit(function() { if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') { jQuery.data(this, "disabledOnSubmit", { submited: true }); $('input[type=submit], input[type=button]', this).each(function() { $(this).attr("disabled", "disabled"); }); return true; } else { return false; } }); });
代碼片段6: 高亮顯示目前聚焦的輸入框標示
有時候你需要提示用戶目前操作的輸入框,你可以使用下面代碼高亮顯示標示:
$("form :input").focus(function() { $("label[for='" + this.id + "']").addClass("labelfocus"); }).blur(function() { $("label").removeClass("labelfocus"); });
代碼片段7: 動態方式添加表單元素
這個方法可以幫助你動態的添加表單中的元素,比如,input等:
//change event on password1 field to prompt new input $('#password1').change(function() { //dynamically create new input and insert after password1 $("#password1").append("&lt;input type='text' name='password2' id='password2' /&gt;"); });
代碼片段8: 自動將數據導入selectbox中
下面代碼能夠使用ajax數據自動生成選擇框的內容
$(function(){ $("select#ctlJob").change(function(){ $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){ var options = ''; for (var i = 0; i &lt; j.length; i++) { options += '&lt;option value="' + j[i].optionValue + '"&gt;' + j[i].optionDisplay + '&lt;/option&gt;'; } $("select#ctlPerson").html(options); }) }) })
代碼片段9: 判斷一個復選框是否被選中
代碼很簡單,如下:
$('#checkBox').attr('checked');
代碼片段10: 使用代碼來遞交表單
代碼很簡單,如下:
$("#myform").submit();
本文由用戶 cdop 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!