我现在拥有的是这个代码,当点击add.png图像时,它会附加新的下拉列表。 我需要的是点击remove.png图片逐个删除下拉列表。
<tr>
<td valign="top">Order</td>
<td colspan="3">
<div id="salesPersonList">
<select name="sales[]" id="sales" class="sales" style="margin-bottom:1px;">
<option></option>
<?php
require_once '../model/sales.php';
@$result2=Sales::getAllSalesPerson();
while($value2=mysql_fetch_assoc($result2)){
?>
<option value="<?php echo $value2['id']; ?>">
<?php echo $value2['name'] ?>
</option>
<?php } ?>
</select>
<span class="salesPersonEr" style="display:none;color:red;margin-left:30px;">Select the Sales Person Order</span>
<img src="../../common/images/add.png" width="20" height="20" name="add" value="Add" onclick="addSalesPerson()" style="margin-left:323px;margin-top:-23px;"/>
<img src="../../common/images/remove.png" width="18" height="18" name="del" id="del" value="del" onclick="removeSalesPerson()"/>
</div>
</td>
剧本: -
function addSalesPerson(){
var salesPersonListt=$('#sales').html();
$('#salesPersonList').append("<select name='sales[]' id='sales' class='sales' style='margin-bottom:1px'>"+salesPersonListt+"</select>");
}
function removeSalesPerson(){
//Please Help
}
附加部分是完美的,它的工作原理。我需要的是移除部分。 我需要的另一个细分是当我点击提交按钮(#submit)时,必须验证表单,以便不应该有一个下拉选项: -
非常感谢任何帮助!!!
答案 0 :(得分:0)
您可以使用jQuery对象的length
属性检查是否存在多个匹配元素,并使用.remove()
方法删除该元素:
function removeSalesPerson(){
if($('#salesPersonList select').length > 1)
$('#salesPersonList select:last').remove();
}
对于验证,如果使用submit()
方法验证成功,您可以使用event.preventDefault()
方法阻止正常表单提交过程并稍后手动提交表单:
$("#submit").click(function(e){
e.preventDefault(); // prevent normal form submission
var failure = false,
emptySelects = $("#salesPersonList select").filter(function(){ // loops through all selects
return !this.value; // returns empty selects
});
if(emptySelects.length) // if there are empty selects, simply return.
return;
else{
// loop through each select and compare it's value with the rest of selects
$("#salesPersonList select").each(function(){
var val = this.value, // store the value of current select
matches = $("#salesPersonList select").not(this).filter(function(){ // loops through rest of the selects
return this.value == val; // return selects whose value match the saved value
});
if(matches.length){ // if there is any other select with matching value
failure = true; // set a boolean indicating loop is exited with a match
return false; // exits the each loop since a match is found, no need of further iteration
}
});
}
if(!failure) // checks whether the loop exited with or without a match
$("form")[0].submit(); //if there are no matches submit the form manually
});
其他参考资料:
附注:您添加了具有相同id
的元素,这是无效的...从动态模板中移除id
属性...