Javascript - 检测第一个字符并提醒用户
问题描述:
我有一个问题。我想在JavaScript中运行一个基本函数,该函数从表单输入字段并检查第一个字符,以确保它没有英镑(GBP)盈方值Javascript - 检测第一个字符并提醒用户
我看起来不像在任何地方找到正确的代码来做到这一点? - 任何人都有任何想法......我对所有这些编程有点小白,说实话,任何帮助都会受到感谢。
答
如果你有一个输入框,你想要得到它的价值和检查值的第一个字符,你可以这样做是这样的:
<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
答
假设你的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
}
}
诀窍到任何代码编写都将一个大问题分解成小代码。一步步。
你编码了什么吗? – talnicolas