动态添加表单字段和更新名称属性

时间:2014-12-04 20:03:59

标签: javascript jquery html

所以我有一部分我正在构建的报价表格,用户可以添加多个具有不同选项的摄像头:http://jsfiddle.net/83n8ttt3/

一切正常,除非您开始删除相机,然后选项的名称属性开始下降:例如,相机3将具有诸如Indoor之类的功能,其名称属性为“Camera 5”

我需要功能的所有名称属性来匹配相同的相机进行处理

$(document).ready(function() {
    var max_fields      = 32; //maximum input boxes allowed
    var wrapper         = $(".cameras"); //Fields wrapper
    var add_button      = $(".add-camera"); //Add button ID
    
    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div class="form-group"><input type="text" name="Camera '+ x +'" value="Camera '+ x +'" class="form-control camerasCounter" readonly /><label>Indoor <input name="Camera '+ x +'" value="Indoor" type="checkbox" /></label> <label>Outdoor <input name="Camera '+ x +'" value="Outdoor" type="checkbox" /></label> <label>Nightvision <input name="Camera '+ x +'" value="Nightvision" type="checkbox" /></label> <label>Vari-Focal Lens <input name="Camera '+ x +'" value="Vari-Focal" type="checkbox" /></label> <label>PTZ <input name="Camera '+ x +'" value="PTZ" type="checkbox" /></label> <label>Audio <input name="Camera '+ x +'" value="Audio" type="checkbox" /></label> <a href="#" class="remove-camera">remove</a></div>'); //add input box
        }
    });
    
       $(wrapper).on("click",".remove-camera", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove();
       
       $(".camerasCounter").each(function(elm){
            var count = elm + 1
            $(this).attr("name", "Camera " + count);
            $(this).attr("value", "Camera " + count);    
			x = elm+ 1;            
        });	
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h4>Add Cameras + Features</h4>
			<div class="cameras">
				<div class="camera-field"><button class="add-camera btn btn-primary">+ Add Camera</button></div>
				<div style="clear:both;"></div>
				
				<div class="form-group"><input type="text" name="Camera 1" value="Camera 1" class="form-control camerasCounter" readonly /><label>Indoor <input name="Camera 1" value="Indoor" type="checkbox" /></label> <label>Outdoor <input name="Camera 1" value="Outdoor" type="checkbox" /></label> <label>Nightvision <input name="Camera 1" value="Nightvision" type="checkbox" /></label> <label>Vari-Focal Lens <input name="Camera 1" value="Vari-Focal" type="checkbox" /></label> <label>PTZ <input name="Camera 1" value="PTZ" type="checkbox" /></label> <label>Audio <input name="Camera 1" value="Audio" type="checkbox" /></label></div>
				
				</div>

谢谢!

0 个答案:

没有答案