简体   繁体   中英

Html & jquery dialog issue for showing in the page

i am trying to show dialog through jquery. first i remove div and then append the div in the form. first time when i am searching and if no data comes then a my dialog is showing properly but suppose first time i search and got the data but when second time search with another keyword and got no data then my dialog is not showing properly. if you scroll the page at end then you will see the dialog is appended. i guess i am making some mistake interns of html,css or jquery related but not being able to capture where is the problem.

this is a small snippet of my code by which i am showing dialog.

function Search(SearchTerm, PageIndex) {
        var flag = 0;
        $('form').remove('#SrchDialog').append('<div id="SrchDialog"></div>');

        if (SearchTerm != '') {
            block();
            var Data = '{"SearchTerm":' + JSON.stringify(SearchTerm) + ',"PageIndex":' + JSON.stringify(PageIndex) + '}';
            $.ajax({
                type: "POST",
                url: "pnpsrch.aspx/StartSearch",
                data: Data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    enableAllLinks();
                    unBlock();
                    if (data.d["HasData"] > 0) {
                        datafound = 1;
                        $("[id$=lblTopPager],[id$=lblBottomPager]").html(data.d["Pager"]);
                        $('#SearchResult').html(data.d["Repeater"]);
                    }
                    else {
                        datafound = 0;
                        message(SearchTerm);
                    }
                    flag = 1;
                },
                error: function (request, status, error) {
                    enableAllLinks();
                    unBlock();
                    alert(request.responseText);
                    flag = 0;
                }
            });
        }
        return false;
    }

if you like to see the problem then go to this url http://www.bba-reman.com/search/search.aspx and write audi in the search box and press enter then you see result is coming and again put gcu as search keyword in the textbox and press enter then you will see no dialog and just go to the end of the page then you will see the dialog.

again refresh the page and put gcu as search keyword in the textbox and press enter then you will see dialog is coming.

actually i want show dialog when no data will come after search. so please see my issue and guide me what to change to get rid of this problem. i want dialog should show properly.

thanks

Search.js full code

$(document).ready(function () {

    var keyword = getParameterByName('keyword');
    var watermark = 'Part search in English';
    var SearchTerm = '';
    $.blockUI.defaults.overlayCSS.opacity = 0.3;
    SearchTerm = $("input[id*='txtSearch']").val();

    //init, set watermark text and class
    if (keyword == '' && $('[id*=txtSearch]').val().length == 0) {
        $('[id*=txtSearch]').val(watermark).addClass('watermark');
    }

    //if blur and no value inside, set watermark text and class again.
    $('[id*=txtSearch]').blur(function () {
        if ($(this).val().length == 0 || SearchTerm == '') {
            $(this).val(watermark).addClass('watermark');
        }
    });

    //if focus and text is watermrk, set it to empty and remove the watermark class
    $('[id*=txtSearch]').focus(function () {
        if ($(this).val() == watermark) {
            $(this).val('').removeClass('watermark');
        }
    });

    $('[id*=txtSearch]').keypress(function (event) {
        SearchTerm = $("input[id*='txtSearch']").val();
        if (event.keyCode == 13) {
            $(".search-box :button").trigger('click');
            return false;
        }
    });

    $(".search-box :button").click(function () {
        if ($('[id*=txtSearch]').val() != watermark && $('[id*=txtSearch]').val().length > 0) {
            SearchTerm = $("input[id*='txtSearch']").val();
            //block();
            if ($.trim(SearchTerm) != '') {
                $(".search-box").data('inputVal', $.trim(SearchTerm));
                setHistory(0, SearchTerm);
                Search(SearchTerm, 1);
            }
        }
        return false;
    });

    // Read a page's GET URL variables and return them as an associative array.
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null)
            return "";
        else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    }


    if ($.trim(SearchTerm) != '') {
        $(".search-box").data('inputVal', $.trim(SearchTerm));
    }

    function disableAllLinks() {
        $('[id$=lblTopPager] a, [id$=lblBottomPager] a').addClass('disabled');
    }

    function enableAllLinks() {
        $('[id$=lblTopPager] a, [id$=lblBottomPager] a').removeClass('disabled');
    }

    function setHistory(pageIndex, SearchTerm) {
        $.bbq.pushState({ pageIndex: pageIndex, keyword: SearchTerm });
    }

    $(window).bind('hashchange', function (e) {
        var searchTerm = '';
        var pageIndex = e.getState("pageIndex") || 0;
        pageIndex = parseInt(pageIndex);
        searchTerm = e.getState("keyword") || '';
        if (searchTerm != null && searchTerm != '') {
            $("input[id*='txtSearch']").val(searchTerm);
            Search(searchTerm, pageIndex);
        }
        return false;
    });

    $(window).trigger('hashchange');


    $('[id$=lblTopPager] a, [id$=lblBottomPager] a').live("click", function (e) {
        e.preventDefault();
        SearchTerm = $("input[id*='txtSearch']").val();
        //block();
        if (!$(this).hasClass('disabled')) {
            disableAllLinks();
            if ($.trim(SearchTerm) != '') {
                if ($(".search-box").data('inputVal') != null) {
                    if ($(".search-box").data('inputVal').toLowerCase() == $.trim(SearchTerm).toLowerCase()) {
                        setHistory(parseInt($(this).attr('page')), SearchTerm);
                        Search(SearchTerm, $(this).attr('page'));
                    }
                    else {
                        setHistory(1, SearchTerm);
                        Search(SearchTerm, 1);
                    }
                }
                else {
                    setHistory(parseInt($(this).attr('page')), SearchTerm);
                    Search(SearchTerm, $(this).attr('page'));
                }
            }
        }
        return false;
    });


    function Search(SearchTerm, PageIndex) {
        var flag = 0;
        $('form').remove('#SrchDialog').append('<div id="SrchDialog"></div>');

        if (SearchTerm != '') {
            block();
            var Data = '{"SearchTerm":' + JSON.stringify(SearchTerm) + ',"PageIndex":' + JSON.stringify(PageIndex) + '}';
            $.ajax({
                type: "POST",
                url: "Search.aspx/StartSearch",
                data: Data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    enableAllLinks();
                    unBlock();
                    if (data.d["HasData"] > 0) {
                        datafound = 1;
                        $("[id$=lblTopPager],[id$=lblBottomPager]").html(data.d["Pager"]);
                        $('#SearchResult').html(data.d["Repeater"]);
                    }
                    else {
                        datafound = 0;
                        message(SearchTerm);
                    }
                    flag = 1;
                },
                error: function (request, status, error) {
                    enableAllLinks();
                    unBlock();
                    alert(request.responseText);
                    flag = 0;
                }
            });
        }
        return false;
    }

    function message(SearchTerm) {
        var markup = "<ul><li><div class='no_results'><span>No results found for [${Name}] </span></div></li></ul>";
        $("[id$=lblTopPager],[id$=lblBottomPager]").html('');
        $("#SearchResult").empty();
        $.tmpl(markup, { "Name": SearchTerm }).appendTo("#SearchResult").fadeIn('slow');
        EnquiryDialog();
        return false;
    }

    var datafound = 1;
    function block() {
        if ($('#SearchResult').children().find('.no_results').length <= 0) {
            if ($('#SearchResult').children('ul').length > 0) {
                $('div#SearchResult').block({ message: '<div style="text-align: center; width:133px; height:36px; margin: 5px 50px;"><img  src="../images/ajx-loader.gif" style="float: left;"/><span style="float: left; font-weight: bold; margin: -21px 44px;">Processing...</span></div>',
                    centerY: false,
                    css: {
                        border: '5px solid #CCCCCC',
                        height: '50px',
                        top: '200px'
                    }
                });
            }
        }
    }

    function unBlock() {
        $('div#SearchResult').unblock();
    }

    var _height = 542, _width = 314, _subwidth = 248, _subheight = 520;

    function EnquiryDialog() {
        if ($("#feed_dialog").is(":visible")) {
            return false;
        }

        if ($("#new_feed_dialog").is(":visible")) {
            return false;
        }

        $("#SrchDialog")
        .html('<div class="Srchloading"></div>')
            .dialog({
                autoOpen: false,
                bgiframe: true,
                height: 'auto',
                width: 314,
                modal: false,
                draggable: true,
                resizable: false,
                position: 'center',
                closeOnEscape: false,
                show: {
                    effect: "fade",
                    duration: 600
                },
                hide: {
                    effect: "fade",
                    duration: 500
                },
                open: function (type, data) {
                    $("#SrchDialog").closest(".ui-dialog").css({ position: 'fixed', height: '580px', background: 'white', top: '50%', left: '50%', marginleft: '-100px', margintop: '-50px' });
                    $("#SrchDialog").css({ overflow: 'hidden' });
                    var t = $(this).parent(), w = window;
                    t.offset({
                        top: (($(window).height() - 542) / 2),
                        left: (($(window).width() - 314) / 2)
                    });
                },
                close: function () {
                    $(this).dialog('destroy').remove();
                    $('form').remove('#SrchDialog')
                }
            });


        $("#SrchDialog").load('SearchFeedback.aspx', function (responseTxt, statusTxt, xhr) {
            if (statusTxt == "success") {
                sHtml = responseTxt;
                sHtml = $(sHtml).find('#SrchExtract').html();
                $sHtml = $(sHtml);
                $("#SrchDialog").html(sHtml);
                $("#SrchDialog").dialog('open').show();
                BindEvent();
            }

            if (statusTxt == "error") {
                alert("Error: " + xhr.status + ": " + xhr.statusText);
            }
        });

    }

    function BindEvent() {
        var _AdjustHeight = 0;
        var flag = true;

        $("input[id*='btnsrchSubmit']").live("click", function () {

            if (jQuery.trim($("input[id*='txtsrchpartName']").val()) == "") {
                $('#srchfeed_loader').html('<span>Part Name Required</span>').fadeIn('slow');
                $("input[id*='txtsrchpartName']").focus()
                flag = false;
                return false;
            }

            if (jQuery.trim($("input[id*='txtsrchpartNumber']").val()) == "") {
                $('#srchfeed_loader').html('<span>Part Number Required</span>').fadeIn('slow');
                $("input[id*='txtsrchpartNumber']").focus()
                flag = false;
                return false;
            }

            if (jQuery.trim($("input[id*='txtsrchfaultinfo']").val()) == "") {
                $('#srchfeed_loader').html('<span>Fault Info Required</span>').fadeIn('slow');
                $("input[id*='txtsrchfaultinfo']").focus()
                flag = false;
                return false;
            }

            if (jQuery.trim($("input[id*='txtsrchcustname']").val()) == "") {
                $('#srchfeed_loader').html('<span>Customer Name Required</span>').fadeIn('slow');
                $("input[id*='txtsrchcustname']").focus()
                flag = false;
                return false;
            }

            if (jQuery.trim($("input[id*='txtsrchcustemail']").val()) == "") {
                $('#srchfeed_loader').html('<span>Customer Email Required</span>').fadeIn('slow');
                $("input[id*='txtsrchcustemail']").focus()
                flag = false;
                return false;
            }

            if (!isValidFeedbackEmailAddress(jQuery.trim($("input[id*='txtsrchcustemail']").val()))) {
                $('#srchfeed_loader').html('<span>Invalid Email</span>').fadeIn('slow');
                $("input[id*='txtsrchcustemail']").focus()
                flag = false;
                return false;
            }

            if (jQuery.trim($("input[id*='txtsrchcustphone']").val()) == "") {
                $('#srchfeed_loader').html('<span>Phone Number Required</span>').fadeIn('slow');
                $("input[id*='txtsrchcustphone']").focus()
                flag = false;
                return false;
            }

            if (jQuery.trim($("textarea[id*='txtsrchDetails']").val()) == "") {
                $('#srchfeed_loader').html('<span>Request Details Required</span>').fadeIn('slow');
                $("textarea[id*='txtsrchDetails']").focus()
                flag = true;
                return false;
            }

            if (flag) {
                $('#srchfeed_loader').fadeIn('slow').html("<img src='../images/big-ajax-loader.gif' border='0'/>");

                var FeedCrd = {};
                FeedCrd["PartName"] = $("[id*=txtsrchpartName]").val();
                FeedCrd["PartNumber"] = $("[id*=txtsrchpartNumber]").val();
                FeedCrd["FaultInfo"] = $("input[id*='txtsrchfaultinfo']").val();
                FeedCrd["CustomerName"] = $("input[id*='txtsrchcustname']").val();
                FeedCrd["CustomerEmail"] = $("input[id*='txtsrchcustemail']").val();
                FeedCrd["CustomerPhone"] = $("input[id*='txtsrchcustphone']").val();
                FeedCrd["Details"] = $("textarea[id*='txtsrchDetails']").val();
                var DTO = { preq: FeedCrd };

                $.ajax({
                    type: "POST",
                    url: "SearchFeedback.aspx/ProcessData",
                    data: JSON.stringify(DTO),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data.hasOwnProperty("d")) {
                            if (data.d == "SUCCESS") {
                                setTimeout(function () {
                                    $('#srchfeed_loader').html('<span>Data Successfully Sent</span>').fadeIn('slow');
                                    setTimeout(function () {
                                        $("#SrchDialog").closest('.ui-dialog-content').dialog('close');
                                        $('form').remove('#SrchDialog');

                                    }, 2000);

                                }, 2000);

                            }
                            else {
                                $('#srchfeed_loader').html('<span>Error occured</span>').fadeIn('slow');
                            }
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }

                });
            }

            return false;
        });

        $("#imgSrchclose").live("click", function () {
            $("#SrchDialog").closest('.ui-dialog-content').dialog('close');
            return false;
        });

        function isValidFeedbackEmailAddress(emailAddress) {
            var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
            return emailPattern.test(emailAddress);
        };

    }

    if ($('#SearchResult').children().find('.no_results').length > 0) {
        $('form').remove('#SrchDialog').append('<div id="SrchDialog"></div>');
        EnquiryDialog();
    }

});

EDIT

after inspecting code i found dialog was not disposing properly. so i add this line of code and problem solved.

$("form #SrchDialog").each(function () {
    $(this).remove();
  });

  $("form").append('<div id="SrchDialog"></div>');

在删除对话框时,需要在显示对话框之前再次对其进行初始化。

$("#SrchDialog").dialog();

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