我的代码的功能是在ptype
文本字段为空时提醒用户。
$("input[name*='ptype']").each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
但是,我需要添加另一个标准,其中另一个字段amount
不是0.这样在ptype="" && amount!=0
时触发该函数。我是jQuery的新手,我不知道如何在这里使用AND
运算符。我试图根据其他问题做一些但似乎没有用。
$(“input [name * ='ptype'] [amount!='0']”)。each(function(){
$(“input [name * ='ptype'],[amount!='0']”)。each(function(){
我错过了什么?
答案 0 :(得分:1)
代码$("input[name*='ptype'][amount!='0']").each(function() {
有效。您必须查看CSS selectors list。
问题可能出在*=
选择中。 input[name*="ptype"]
表示选择name属性值包含子字符串“ptype”的每个元素。
$('input[name*="ptype"][amount!="0"]').each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
答案 1 :(得分:0)
您可以使用&& 符号进行操作。代码取决于您的金额字段的位置及其含义。如果我猜对了,它应该是这样的:
$("input[name*='ptype']").each(function() {
if ($(this).val() == "" && $(this).parent().find(input[name='amount']).val() != 0) {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
答案 2 :(得分:0)
您可以在按钮中使用此功能。
function check(e){
var verror = false;
$("input[name*='ptype']").each(function(index, value) {
var amount = $($("input[name='amount[]']").get(index)).val();
var ptype = $(this).val();
if(ptype.length <= 0 && amount.length > 0 ){
verror = true;
$(this).focus();
return false;
}
});
if(verror){
e.preventDefault();
alert("Enter Value!");
}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="1"> <br>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="2"> <br>
<button type="button" onclick="check(event)">Click</button>
</form>
&#13;
答案 3 :(得分:0)
«其他字段 是有问题的关键。
因此,您需要一个选择器来检查所选元素是否为空且另一个元素不为零。
HOLA!
逻辑问题在这里。
使用$(selector)
,您可以查找一些元素。
对于许多匹配元素集,选择器中没有AND / OR 选择器是 ONE 匹配元素集。
此选择器无法检查另一组的属性value
。
所以你必须知道你的标记并导航一下...... 和处理变量类型。
$("input[name*='ptype']").each(function() {
if ( parseInt( $(this).next("input").val() ) != 0) {
$(this).css({"background-color" : "red"});
alert("Enter Value!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ptype: <input type="text" name="ptype"><br>
amount: <input type="text" name="amount" value="1">
根据我的理解,你必须在这里看获取另一个元素的值。所以你必须知道什么是“其他”元素,使用的方法可能会有很大差异,具体取决于你的HTML ......