當前位置:軟件學堂 > 資訊首頁 > 網(wǎng)絡編程 > 編程其他 > JS驗證列表框中的值是否重復

JS驗證列表框中的值是否重復

2012/11/8 21:08:16作者:佚名來源:網(wǎng)絡

移動端

【實例名稱】

JS驗證列表框中的值是否重復

【實例描述】

為了方便用戶填寫資料,可以下拉框的形式讓用戶選擇值代替直接填寫。但有時候下拉框并不能提供全部數(shù)據(jù),此時需要用戶自己填寫。本例用來判斷用戶填寫的數(shù)據(jù)是否已經(jīng)存在于下拉框中。

【實例代碼】

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>標題頁-學無憂(www.yzddtk.cn)</title> <script language="javascript"> function chk() {     var txtValue = document.getElementById("txtValue"); //獲取文本框的值     var sel = document.getElementById("sel");          //找到下拉框     for (var i=0; i<sel.length; i++)                    //遍歷下拉框中的所有數(shù)據(jù)     {         if (txtValue.value==sel.options[i].text){       //如果輸入的值等于下拉框中的值             alert("該值已經(jīng)存在");         }     } } </script> </head> <body> <div id="mydiv"> <select id="sel" name="sel"> <option>China</option> <option>England</option> <option>German</option> </select> <input type="text" name="txtValue" id="txtValue"><br/> <input type="button" value="檢測是否存在" onclick="chk();"> </div> </body> </html>

【運行效果】

 驗證列表框中的值是否重復運行效果

【難點剖析】

本例首先獲取文本框的值,然后對下拉框中的值進行遍歷,這使用的是“for”循環(huán)語句?!皊el.options[i].text用來獲取下拉框中的當前值,用此值比較用戶輸入的值,如果相等,則表示用戶輸入的數(shù)據(jù)重復。

【源碼下載】

為了JS代碼的準確性,請點擊:JS驗證列表框中的值是否重復 進行本實例源碼下載 

標簽: 驗證  重復