skip to Main Content

im using this code to replace <div id="replaceit"></div> with content in my dynamic url
but it does not instant update when i change select option.

how can i make it work.

Thank you!

$(document).ready(function() {
    function updatePreview() {
        var year = $("#year").val();
        var month = $("#month").val();
        var dynamicUrl = "print.php?year=" + year + "&month=" + month;

        $.get(dynamicUrl, function(data) {
            $("#replaceit").replaceWith(data);
        }).fail(function() {
            alert("Failed to fetch preview content. Please try again.");
        });
    }

    $('#year, #month').on('change', function(){
        updatePreview();
    });
    updatePreview();

});

2

Answers


  1. replaceWith removes the selected elements from the dom. I think yuo want to replace the contents of the element, to do this use .html()

    $("#replaceit").html(data);
    
    Login or Signup to reply.
  2. Try Like this

    STEP 1 : set the HTML like this

     <div id="replace">  // if you have not any parent div of #replaceit
        <div id="replaceit">
    
        </div>
    </div>
    

    STEP 2 : Replace your JavaScript code with the following code

    $(document).ready(function() {
        function updatePreview(digit) {
            var year = $("#year").val();
            var month = $("#month").val();
            var dynamicUrl = "print.php?year=" + year + "&month=" + month;
    
            if(digit == 2){
              $('#replace').html('<div id="replaceit"></div>');  // You can target by any parent div (id) if you dont want to create new div (#replace).
            }
            
            $.get(dynamicUrl, function(data) {
                $("#replaceit").replaceWith(data);
            }).fail(function() {
                alert("Failed to fetch preview content. Please try again.");
            });
        }
    
        $('#year, #month').on('change', function(){
            updatePreview(2);
        });
        updatePreview(1);
    
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search