如題,由於input是動態生成,起先也可以給id設置成不同的動態名,但是為了盡量不改后台代碼。於是嘗試了幾種方法。
需求,有一個【增加】按鈕,用戶每按一次,增加一個input輸入框,要實現判斷input框是否輸入。但由於id一樣,所以網上找了一些方法。
環境,JS:
// 處理加載 輸入框 var pcInputIndex = 1 ; function autoLoadInput(par) { if(par != null && par != "") { var html = "" ; if(par == "pc") { // 處理批次按鈕 var $pc = $("#pc") ; html = "<tr id = 'pc_" + pcInputIndex + "' >" ; html += "<td>" ; html += "<input type='text' name='pcv' id='pcv' class='text' maxlength='200' style='width: 400px;' />" ; html += " <a href=javascript:delAutoLoadInput('pc_',"+pcInputIndex+"); >刪除</a>" ; html += "</td>" ; html += "</tr>" ; $pc.append(html) ; // 添加元素 pcInputIndex ++ ; } } } html += "<input type='text' name='pcv" + pcInputIndex + "' id='pcv" + pcInputIndex + "' class='text' maxlength='200' style='width: 400px;' />" ;
JSP:
<tr> <th> 批次號: </th> <td> <input type="button" class="button" onclick="autoLoadInput('pc') ;" value=" + 新增批次" /> </td> </tr>
①最開始,想法是有動態的值pcInputIndex,那么input的id也可以動態設置。
於是:
html += "<input type='text' name='pcv" + pcInputIndex + "' id='pcv" + pcInputIndex + "' class='text' maxlength='200' style='width: 400px;' />" ;
function submitForm(n) { if(n != "0") { var pcn = $("table #pc").find("tr").length ; if(pcn == null || pcn <= 0) { $.message("warn","請填寫商品進貨批次信息 !"); return false; } if(pcInputIndex > 1){ for(var i = 1; i < pcInputIndex; i++){ var pcvId = 'pcv'+i; var pcv = $("#"+pcvId+"").val(); if($("#"+pcvId+"").length > 0){ if(pcv == null || pcv == ""){ $("#"+pcvId+"").focus(); $.message("warn","請填寫商品進貨批次信息 !"); return false; } } } } } }
由於pcInputIndex只做了++處理,但是刪除按鈕沒有做--處理,所以多了判斷
if($("#"+pcvId+"").length > 0){
但是,后台代碼也要隨之改變,我想應該還有不變更的ID的方法。畢竟不想改動太大
// 批次號 String[] pcvs = null ; // 判斷是否草稿件 if(state.equals(ProductQuality.ProductQualityState.Quality_State_1.getCode())) { // 批次號 pcvs = request.getParameterValues("pcv") ; if(pcvs == null) { return Constants.ERROR_VIEW; } // 此處代碼省略 }
②於是又找到了這個方法,本來是很好的方法,簡單明了,但是不知道為什么,明明方法可以進,光標都到位了,message卻顯示不出來,不知道是不是和作用域有關,現在的我還是懂的太少,只能記錄下來,以后再解惑了
if(pcInputIndex > 1){ $('input[id="pcv"]').each(function(){ var pcv=$(this).val(); if(pcv == null || pcv == ""){ $(this).focus(); $.message("warn","請填寫商品進貨批次信息 !"); return false; } }); }
③網上找的也是ByName,我自己嘗試了用ById,發現不行,最后還是這個方法,完美解決
if(pcInputIndex > 1){ var pcvs = document.getElementsByName("pcv"); var info = ""; for (var i = 0; i< pcvs.length; i++) { info = pcvs[i].value; if (info == null || info == "") { pcvs[i].focus(); $.message("warn","請填寫商品進貨批次信息 !"); return false; } } }
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。