2011-11-16 25 views
0

我有一個問題。我想在JavaScript中運行一個基本函數,該函數從表單輸入字段並檢查第一個字符,以確保它沒有英鎊(GBP)盈方值Javascript - 檢測第一個字符並提醒用戶

我看起來不像在任何地方找到正確的代碼來做到這一點? - 任何人都有任何想法......我對所有這些編程有點小白,說實話,任何幫助都會受到感謝。

+0

你編碼了什麼嗎? – talnicolas

回答

0

charAt應該這樣做

var str = "Foo"; 

var firstChar = str.charAt(0); 
+0

邪惡的,我會給它一個旋轉,非常感謝:-) – netties

4

如果你有一個輸入框,你想要得到它的價值和檢查值的第一個字符,你可以這樣做是這樣的:

<input type="text" id="price"> 


var str = document.getElementById("price").value; 
if (str.charAt(0) == "£") { 
    // do whatever you need to do if there's a £ sign at the beginning 
} 

如果英鎊符號不應該在那裏,也許你可以安全地刪除它或忽略它,而不是讓最終用戶這樣刪除它:

var el = document.getElementById("price"); 
if (el.value.charAt(0) == "£") { 
    el.value = el.value.substr(1); 
} 
+0

優秀,謝謝:-) – netties

2

假設你的HTML是這樣的:

<input type="text" id="my_input" /> 
<button onClick="checkInput();">Check input</button> 

然後你想建立你的腳本是這樣的:

function checkInput() { 
    var inp = document.getElementById('my_input'); // get the input field 
    inp = inp.value; // get the value 
    inp = inp.charAt(0); // get the first character 
    if(inp == "£") { 
     // do something 
    } 
} 

都可以濃縮成:

function checkInput() { 
    if(document.getElementById('my_input').value.charAt(0) == "£") { 
     // do something 
    } 
} 

訣竅到任何代碼編寫都將一個大問題分解成小代碼。一步步。