简体   繁体   中英

add html only once on button click

I'm injecting some html, a span tag to display an error message, on a button click. I only want to add the html once. Every time the button is clicked it add the html again. How can I add the html only once?

Here is the code:

<script type="text/javascript">
    var j$ = jQuery.noConflict();

    j$(document).ready(function() {
        var submitButton = j$('[id$=btnSubmit]');
        var emailButton = j$('[id$=btnEmail]');
        var shippingMethod = j$('[id$=shippingMethod]');
        var alternateAddress = j$('[id$=chkbxAlternateAddress]');
        var alternateStreet = j$('[id$=alternateaddress]');
        var alternateCity = j$('[id$=alternatecity]');
        var alternateState = j$('[id$=alternatestate]');
        var alternateZip = j$('[id$=alternatezip]');
        submitButton.click(function(e){
            j$('[id$=documentQuantity]').each(function(index){
                if(j$(this).text() == '0') {
                    j$("#contentQtyError").css({"display":"inline"});
                    j$(this).parent().parent().css({"background-color":"#FFFFCC"});
                    e.preventDefault();
                }
            });             
            if(shippingMethod.val() == '') {
                shippingMethod.after("<span class='shippingMethodErrorMsg'>Error: A Shipping Method is Required</span>");
                e.preventDefault();
            }
            else {
                j$(".shippingMethodErrorMsg").remove();
            }
            if(alternateAddress.attr("checked")) {
                alternateStreet.after("<span class='alternateStreetErrorMsg'>Error: A Street Address is Required</span>");
                alternateCity.after("<span class='alternateCityErrorMsg'>Error: A City is Required</span>");
                alternateState.after("<span class='alternateStateErrorMsg'>Error: A State is Required</span>");
                alternateZip.after("<span class='alternateZipErrorMsg'>Error: A Zip is Required</span>");
                e.preventDefault();
            }
            else {
                j$(".alternateStreetErrorMsg").remove();
                j$(".alternateCityErrorMsg").remove();
                j$(".alternateStateErrorMsg").remove();
                j$(".alternateZipErrorMsg").remove();
            }
        });
        shippingMethod.change(function(){
            if(shippingMethod.val() == 'Email') {
                emailButton.css({"display":""});
                submitButton.css({"display":"none"});
                j$('#containerAltAddressToggle').css({"display":"none"});
                j$('[id$=chkbxAlternateAddress]').attr('checked',false);
                j$('[id$=alternateAddressPanel]').css({"display":"none"});
                j$('#containerCustomKitToggle').css({"display":"none"});
                j$('[id$=chkbxCustomKit]').attr('checked',false);
                j$('[id$=customKitPanel]').css({"display":"none"});             
                j$('#containerPersonalNoteToggle').css({"display":"none"});
                j$('[id$=chkbxPersonalNote]').attr('checked',false);
                j$('[id$=personalNotePanel]').css({"display":"none"});
                j$('#containerFollowUpTaskToggle').css({"display":"none"});
                j$('[id$=chkbxScheduleTask]').attr('checked',false);
                j$('#recurrence').css({"display":"none"});
                j$('[id$=commentsBlock]').css({"display":"none"});
            }
            else {
                emailButton.css({"display":"none"});
                submitButton.css({"display":""});
                j$('#containerAltAddressToggle').css({"display":""});
                j$('#containerCustomKitToggle').css({"display":""});                
                j$('#containerPersonalNoteToggle').css({"display":""});
                j$('#containerFollowUpTaskToggle').css({"display":""}); 
                j$('[id$=nextTask]').val("");   
                j$('[id$=commentsBlock]').css({"display":""});      
            }                           
        });
        alternateAddress.change(function() {
            if(alternateAddress.attr("checked") != "checked") {
                j$(".alternateStreetErrorMsg").remove();
                j$(".alternateCityErrorMsg").remove();
                j$(".alternateStateErrorMsg").remove();
                j$(".alternateZipErrorMsg").remove();
            }
        });
    });  
</script>

Thanks for any help!

create a boolean in the scope of submitButton.Click(...). check the boolean in submitButton.Click(...). the ref to that boolean will be saved in the function associated to submitButton.Click(...) as part of that function's closure.

Even prettier, create a decorator function to save the boolean in its closure so you do not pollute the parent namespace with your boolean:

submitButton.Click(
(function() { 
var notDoneYet = true; 
return function(){/** function to insert the html, checking notDoneYet**/}
})()
);

You could wrap the inserted html in a div with a specific id using .wrap()

and then on your click do something like this:

if ($('#idofwrap').length == 0) {
    //wrap content and insert here
}

or put each of your afters in an if eg:

if ($('.alternateStreetErrorMsg').length == 0) {
    alternateStreet.after("<span class='alternateStreetErrorMsg'>Error: A Street Address is Required</span>");
}

Initaialize any global variable say var i = 0; and in the function which executes to insert html , put that inside if(i<1) and inside if do i++ . Hope this helps.

Use .one()

$("elem").one("click", function() {
    //only runs once!
});

Ref: http://api.jquery.com/one/

You can check size like

if ($('.classofspan').size() == 0) {
//add span
}
var j$ = jQuery.noConflict(); j$(document).ready(function() { var submitButton = j$('[id$=btnSubmit]'); var emailButton = j$('[id$=btnEmail]'); var shippingMethod = j$('[id$=shippingMethod]'); var alternateAddress = j$('[id$=chkbxAlternateAddress]'); var alternateStreet = j$('[id$=alternateaddress]'); var alternateCity = j$('[id$=alternatecity]'); var alternateState = j$('[id$=alternatestate]'); var alternateZip = j$('[id$=alternatezip]'); submitButton.click(function(e){ j$('[id$=documentQuantity]').each(function(index){ if(j$(this).text() == '0') { j$("#contentQtyError").css({"display":"inline"}); j$(this).parent().parent().css({"background-color":"#FFFFCC"}); e.preventDefault(); } }); if(shippingMethod.val() == '') { shippingMethod.after("Error: A Shipping Method is Required"); e.preventDefault(); } else { j$(".shippingMethodErrorMsg").remove(); } if(alternateAddress.attr("checked")) { alternateStreet.after("Error: A Street Address is Required"); alternateCity.after("Error: A City is Required"); alternateState.af ter("Error: A State is Required"); alternateZip.after("Error: A Zip is Required"); e.preventDefault(); } else { j$(".alternateStreetErrorMsg").remove(); j$(".alternateCityErrorMsg").remove(); j$(".alternateStateErrorMsg").remove(); j$(".alternateZipErrorMsg").remove(); } }); shippingMethod.change(function(){ if(shippingMethod.val() == 'Email') { emailButton.css({"display":""}); submitButton.css({"display":"none"}); j$('#containerAltAddressToggle').css({"display":"none"}); j$('[id$=chkbxAlternateAddress]').attr('checked',false); j$('[id$=alternateAddressPanel]').css({"display":"none"}); j$('#containerCustomKitToggle').css({"display":"none"}); j$('[id$=chkbxCustomKit]').attr('checked',false); j$('[id$=customKitPanel]').css({"display":"none"}); j$('#containerPersonalNoteToggle').css({"display":"none"}); j$('[id$=chkbxPersonalNote]').attr('checked',false); j$('[id$=personalNotePanel]').css({"display":"none"}); j$('#containerFollowUpTaskToggle').css({"display":"none"}); j$('[id$=chkbxScheduleTask]').attr('checked',false); j$('#recurrence').css({"display":"none"}); j$('[id$=commentsBlock]').css({"display":"none"}); } else { emailButton.css({"display":"none"}); submitButton.css({"display":""}); j$('#containerAltAddressToggle').css({"display":""}); j$('#containerC ustomKitToggle').css({"display":""}); j$('#containerPersonalNoteToggle').css({"display":""}); j$('#containerFollowUpTaskToggle').css({"display":""}); j$('[id$=nextTask]').val(""); j$('[id$=commentsBlock]').css({"display":""}); } }); alternateAddress.change(function() { if(alternateAddress.attr("checked").= "checked") { j$(".alternateStreetErrorMsg");remove(). j$(".alternateCityErrorMsg");remove(). j$(".alternateStateErrorMsg");remove(). j$(".alternateZipErrorMsg");remove(); } }); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM