我正在尝试使用两个数字输入字段创建一个小表单,输入二将依赖于输入一,如下两个=一个+/- x
<form id="test" class="form-horizontal">
<input type="number" step="any" class="form-control" name="v1" id="v1"/>
<input type="number" step="any" class="form-control" name="v2" id="v2"/>
</form>
<script>
$(document).ready(function() {
$('#test').formValidation({
fields: {
v1: {
validators: {
between: {
min: 10,
max: 50,
message: ''
}
}
},
var temp = document.getElementsByName("v1")[0].value,
a1 = temp -1,
a2 = temp +1,
v2: {
validators: {
between: {
min: 'a1',
max: 'a2',
message: ''
}
}
}
}
});
});
</script>
我做错了什么?
答案 0 :(得分:1)
你正在使用字符串而不是变量值
validators: {
between: {
min: 'a1',
max: 'a2',
message: ''
}
它应该喜欢这个
validators: {
between: {
min: a1,
max: a2,
message: ''
}
为什么会发生这里解释
a1 = temp -1,
a2 = temp +1,
console.log(a1) // show value of a1
console.log('a1') // show a1 in output because it will considered as string
答案 1 :(得分:0)
通过这样做得到它: 主页
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
<form id="test" class="form-horizontal">
<div class="form-group">
<label class="col-xs-3 control-label">V1</label>
<div class="col-xs-5">
<input type="number" step="any" class="form-control" name="v1" id="v1" onkeyup="showHint(this.value)"/><p>10 to 50</p>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">V2</label>
<div class="col-xs-5">
<input type="number" step="any" class="form-control" name="v2" id="v2"/><div id="txtHint"></div>
</div>
</div>
</form>
<script>
$(document).ready(function() {
$('#test').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
v1: {
validators: {
between: {
min: 10,
max: 50,
message: ''
}
}
},
v2: {
validators: {
between: {
min: 'v2a',
max: 'v2b',
message: ''
}
}
}
}
});
});
</script>
gethint.php
if($_GET['q'] == null || $_GET['q'] == ""){}else{
$min = $_GET['q']-1;
$max = $_GET['q']+1;
echo"<p>".$min." to ".$max."</p>
<input type=\"hidden\" name=\"v2a\" id=\"v2a\" value=\"".$min."\">
<input type=\"hidden\" name=\"v2b\" id=\"v2b\" value=\"".$max."\">";
}
我确信可能有更好或更简单的方法,但这可以满足我的需求。