jQuery在单击按钮时验证(不提交)

时间:2018-08-03 01:56:03

标签: javascript jquery

我已经阅读了这里和其他页面上的所有解决方案,找不到适合我的情况的解决方案。如果有的话,请提前道歉。

我正在使用jQuery .validate。我有一些动态加载的标签。所以我不能使用“提交”。当我单击“更新”按钮时,我想验证输入,然后提交(如果有效)。

相关代码段为:

动态负载:

// class="tab-pane" is required.
            contents += '<div class="tab-pane fade" id="' + obj.eventId + '">';
            contents += '<form data-toggle="validator" role="form" id="tabForm'+obj.eventId+'">';
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';

            //Column 1
            contents += '<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">';

            //Location of Camp
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
            contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="location'+obj.eventId+'">Location of Camp:<span class="req"> *</span></label>';
            contents += '<input class="row col-lg-8 col-md-8 col-sm-8 col-xs-8" type="text" id="location'+obj.eventId+'" name="location" placeholder="Location of Camp" value="' + obj.eventLocation + '">';
            contents += '</div>';

按钮:

contents += '<button id="'+obj.eventId+'" class="btn btn-large btn-primary update-button" type="button">Update</button>';

验证:

$(document).on('click', '.update-button', function(){
            alert("Update"); //Is fired
            var formName = "#tabform" + this.id;
            $(formName).validate({
                //debug: true,
                rules: {
                    location: {
                        required: true
                    },
                },

                messages: {
                    location: {
                        required: "Please select enter a location."
                    },
                },

                submitHandler : function(formName) {
                    alert('updateCampFunction');

                    alert('this.id: ' + this.id);
                    sessionStorage.setItem('ssCampID', this.id);

                    var dataToBeSent  = {
                            ssCampID : sessionStorage.getItem('ssCampID'),
                    };

                    $.ajax({
                        url: "UpdateCampView",
                        data : dataToBeSent,
                        type: "POST",
                        cache: false,
                    })
                    .fail (function(jqXHR, textStatus, errorThrown) {
                        $('#ajaxGetUserServletResponse').text('An error occured updating the Camp');
                    })
                    .done(function(responseJson1a) {
                        $('#ajaxGetUserServletResponse').text('Updated.');

                    });
                }
            });
        });

请注意,我要添加“ obj.eventId”以使每个表单唯一。控制台中没有错误。

完整js:

for(var i = 0; i < responseJson1a.length; i++) {
            var obj = responseJson1a[i];
            // class="tab-pane" is required.
            contents += '<div class="tab-pane fade" id="' + obj.eventId + '">';
            contents += '<form data-toggle="validator" role="form" id="tabForm'+obj.eventId+'">';
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';

            //Column 1
            contents += '<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">';

            //Dates of Camp
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
            //Start Date
            var dateStart = moment(obj.eventDateStart).format("DD/MM/YYYY")
            contents += '<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">';
            contents += '<div class="form-group">';
            contents += '<label class="control-label control-label-left col-lg-5 col-md-5 col-sm-5 col-xs-5" for="startDate'+obj.eventId+'">Start Date<span class="req"> *</span></label>';
            contents += '<div class="input-group date" id="datepicker1">';
            contents += '<input type="text" class="form-control" id="startDate'+obj.eventId+'" name="startDate" placeholder="Start Date" value="' + dateStart + '">';
            contents += '<span class="input-group-addon">';
            contents += '<span class="glyphicon glyphicon-calendar"></span>';
            contents += '</span>';
            contents += '</div>';
            contents += '</div>';
            contents += '</div>';
            //End Date
            var dateEnd = moment(obj.eventDateEnd).format("DD/MM/YYYY")
            contents += '<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">';
            contents += '<div class="form-group">';
            contents += '<label class="control-label control-label-left col-lg-5 col-md-5 col-sm-5 col-xs-5" for="endDate'+obj.eventId+'">End Date<span class="req"> *</span></label>';
            contents += '<div class="input-group date" id="datepicker2">';
            contents += '<input type="text" class="form-control" id="endDate'+obj.eventId+'" name="endDate" placeholder="End Date" value="' + dateEnd + '">';
            contents += '<span class="input-group-addon">';
            contents += '<span class="glyphicon glyphicon-calendar"></span>';
            contents += '</span>';
            contents += '</div>';
            contents += '</div>';
            contents += '</div>';
            contents += '</div>';

            //Location of Camp
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
            contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="location'+obj.eventId+'">Location of Camp:<span class="req"> *</span></label>';
            contents += '<input class="row col-lg-8 col-md-8 col-sm-8 col-xs-8 location" type="text" id="location'+obj.eventId+'" name="location" placeholder="Location of Camp" value="' + obj.eventLocation + '" required>';
            contents += '</div>';

            //Details of Camp
            contents += '<div>';
            contents += '<label class="control-label control-label-left col-lg-12 col-md-12 col-sm-12 col-xs-12" for="details'+obj.eventId+'">Details of Camp:<span class="req"> *</span></label>';
            contents += '</div>';
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
            contents += '<textarea class="summernote" id="details'+obj.eventId+'" name="details" rows="3">' + obj.eventDetails + '</textarea>';
            contents += '</div>';

            //Nights in camp
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
            contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="nights'+obj.eventId+'">Nights in Camp:<span class="req"> *</span></label>';
            contents += '<input class="row col-lg-8 col-md-8 col-sm-8 col-xs-8" type="text" id="nights'+obj.eventId+'" name="nights" placeholder="Nights in Camp" value="' + obj.eventNights + '">';
            contents += '</div>';

            //Night in a building
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
            contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="building'+obj.eventId+'">Nights in a building:<span class="req"> *</span></label>';
            contents += '<input class="row col-lg-8 col-md-8 col-sm-8 col-xs-8" type="text" id="building'+obj.eventId+'" name="building" placeholder="Nights in a building" value="' + obj.eventNightsBuilding + '">';
            contents += '</div>';

            //Nights under canvas
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
            contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="canvas'+obj.eventId+'">Nights under canvas:<span class="req"> *</span></label>';
            contents += '<input class="row col-lg-8 col-md-8 col-sm-8 col-xs-8" type="text" id="canvas'+obj.eventId+'" name="canvas" placeholder="Nights under canvas" value="' + obj.eventNightsCanvas + '">';
            contents += '</div>';

            //Actual KM travelled
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
            contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="actualKM'+obj.eventId+'">Kilometres Travelled:<span class="req"> *</span></label>';
            contents += '<input class="row col-lg-8 col-md-8 col-sm-8 col-xs-8" type="text" id="actualKM'+obj.eventId+'" name="actualKM" placeholder="Kilometres Travelled" value="' + obj.eventKmActual + '">';
            contents += '</div>';

            //Offset for mode of travel
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
            contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="offset'+obj.eventId+'">Offset:<span class="req"> *</span></label>';
            contents += '<input class="row col-lg-8 col-md-8 col-sm-8 col-xs-8" type="text" id="offset'+obj.eventId+'" name="offset" placeholder="Offset" value="' + obj.eventKmOffset + '">';
            contents += '</div>';

            //Outcome
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
            contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="outcome'+obj.eventId+'">Outcome:</label>';
            contents += '<input class="row col-lg-8 col-md-8 col-sm-8 col-xs-8" type="text" id="outcome'+obj.eventId+'" name="outcome" placeholder="Outcome" value="' + obj.eventKm + '" disabled>';
            contents += '</div>';

            //Process buttons
            contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
            contents += '<button id="'+obj.eventId+'" class="btn btn-large btn-primary update-button" type="button">Update</button>';
            contents += '<button id="'+obj.eventId+'" class="btn btn-large btn-primary delete-button" type="button">Delete</button>';
            contents += '</div>';

            contents += '</div>';//End of column 1

            //Column 2 to contain the image
            contents += '<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">';
            contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="'+obj.eventId+'">Photograph:</label>';
            contents += '<input class="form-control-file col-lg-8 col-md-8 col-sm-8 col-xs-8 photo-input" type="file" id="'+obj.eventId+'" name="photo" placeholder="Photograph">';
            contents += '<img id="campImage'+obj.eventId+'" src="' + obj.eventPicture + '" alt="Camp image" class="img-thumbnail">';
            contents += '</div>';

            contents += '</div>';
            contents += '</form>';
            contents += '</div>';

            $("#tabContent").append(contents);
            contents = '';
        }

2 个答案:

答案 0 :(得分:0)

var formName = "#tabform" + this.id;#tabform123456,但标记的ID为tabForm

答案 1 :(得分:0)

看看下面的代码
我将规则动态添加到了动态内容
希望对您有帮助

$(document).ready(function(){
	$(document).on('click', '.update-button', function(){
		var formName = "#tabForm" + this.id;
		$(formName).validate();
		$("input").each(function() { //replace selector with relevant data
			$(this).rules("add",
			{
			    required: true,
			    messages: {
			    required: "This field is required" //replace text with dynamic data if needed
			    }
			});
		});

		if($(formName).validate().form()) {
			console.log('Validated.');
			//this is where you do your ajax
		} else {
			console.log("Form not validated.");
		}
	});
	
	function BuildHTML(){ //hard-coded appender just for this example
		obj = {'eventId':123}; 
		var contents = '';
		contents += '<div class="tab-pane fade" id="' + obj.eventId + '">';
		contents += '<form data-toggle="validator" role="form" id="tabForm'+obj.eventId+'">';
		contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';

		//Column 1
		contents += '<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">';

		//Location of Camp
		contents += '<div class="row col-lg-12 col-md-12 col-sm-12 col-xs-12">';
		contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="location'+obj.eventId+'">Location of Camp:<span class="req"> *</span></label>';
		contents += '<input class="row col-lg-8 col-md-8 col-sm-8 col-xs-8" type="text" id="location'+obj.eventId+'" name="location" placeholder="Location of Camp">';
		contents += '<br>';
		contents += '<label class="control-label control-label-left col-lg-4 col-md-4 col-sm-4 col-xs-4" for="location'+obj.eventId+'">Another Field:<span class="req"> *</span></label>';
		contents += '<input class="row col-lg-8 col-md-8 col-sm-8 col-xs-8" type="text" id="anotherField'+obj.eventId+'" name="anotherField" placeholder="Sample Placeholder">';
		contents += '</div>';
		contents += '<button id="'+obj.eventId+'" class="btn btn-large btn-primary update-button" type="button">Update</button>';
		
		$('#content').append(contents);
	}
	
	BuildHTML();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>

<body>
<div id="content">
</div>
</body>