2013-04-05 54 views
0

我是JavaScript新手,我一直在做一些工作,在HTML和JavaScript中創建表單。在這項工作中,我一直試圖根據輸入到前一個字段的文本限制字段的字符串。輸入的數據改變了字符串長度

什麼,我一直在嘗試是如果該國「澳大利亞」被輸入到比「郵編」文本框「國家」文本框中僅限於4個數字(澳大利亞郵編標準)

我有做了這麼多,到目前爲止函數:

document.getElementById('txtcountry').onblur = function postcode() 
{ 
var country = document.getElementById('txtcountry').value; 
if (country == "Australia" || category == "australia") 
{ 
    document.getElementById('txtpostcode').maxLength = 4; 
    } 
    else 
{ 
    document.getElementById('txtpostcode').maxLength = 9; 
} 
} 

這裏是我使用的功能與初始HTML的段:

<b>Postcode:</b> <input type="text" id="txtpostcode" name="postcode"> 
<br> 
<b>Country:</b> <input type="text" id="txtcountry" name="country"> 

我打電話ŧ他的功能使用:

<form name="rego" action="submit.htm" onsubmit="return !!(validateText() & validateCheckBoxes(this) & validateRadioButton() & validateEmail() & populateInstitution() & postcode());" method="POST"> 

任何幫助真的會很感激!

UPDATE:我有我的功能更新一些幫助後,要完成的功能,因爲它似乎並沒有工作,我需要它的一些進一步的幫助

回答

0

你們是不是要設置maxLength屬性:

var pc = document.getElementById('txtpostcode'); 
pc.maxLength = 4; 
pc.value = pc.value.substr(0,4); // remove any extra characters already entered 

...然後添加else條件將maxLength設置爲其他國家/地區的默認值。

然後,您會致電txtcountry字段的blur事件中的postcode()函數。

編輯:請注意,您所顯示的功能已在測試if的第二部分未定義的變量category - 應該是country。正如我已經提到的,你需要從某個地方調用該函數。

+0

最大長度正是我一直在尋找除了一些原因,當我完成它似乎沒有工作 – bigsenator 2013-04-05 09:16:37

+1

見我的編輯功能。當然,您確實需要實際調用該函數。這是一個工作示例:http://jsfiddle.net/nnnnnn/hk6bE/ – nnnnnn 2013-04-05 09:17:59

+0

嗯仍然似乎沒有爲我工作:/ – bigsenator 2013-04-05 09:30:07

0

我會用

var country = document.getElementById('txtcountry'); 
if (country.value == "Australia" || category == "australia") 
{ 
    country.setAttribute("maxlength","4"); 
    country.value = country.value.substr(0,4); 
}