javascriptformszend-frameworkzend-form

how can I get the code to be in single line when viewing the source code?


I'm trying to create a button which dynamically add input and since I'm using Zend framework I use this method to get the input from the Form file : <?php echo $this->formm->getElement('refA'); ?>

but I get this error : Uncaught SyntaxError: Unexpected identifier

and the jquery function for that add button is :

$(document).ready(function (){
    var j = "<?php echo $this->formm->getElement('refA'); ?>";
    $("#add-more").click(function(){   
        $(".row").append(j);
    });
});

and when I click on that error it shows me where I have the error it seems like that it uses:

$(document).ready(function (){
    var j = "<label for="refA" class="optional">Article:</label>
             <select name="refA" id="refA" class="form-control">
               <option value="test1" label="test1">test1</option>
             </select>";
    $("#add-more").click(function(){   
        $(".row").append(j);
    });  
});

is it possible to get the code generated in single line so I can make the button to work ?


Solution

  • As said by Kyle, you're facing a quoting issue. But, unlike what he said, quotes inside PHP tag must not be escaped, since they are rendered server side.

    This should do the trick:

    window.onload = function() {
        $(document).ready(function (){
            var j = '<?php echo  preg_replace("/\r|\n/", "", $this->formm->getElement('refA')); ?>';
            $("#add-more").click(function(){   
                $(".row").append(j);
            });
        });
    }
    

    Edit: looking at your screenshots and other comments, it seems that you are trying to access jQuery ($) before loading (I suppose you are loading all the JS dependencies at the end of the layout). Since you can't use PHP code in JS files, you have two options:

    1. You create a JS variable inside your template (ajouter.phtml), like var inputTemplate = <?php echo preg_replace(....);?>;, and use that variable in your JS file
    2. You make sure that that JS snippet is executed only when the page has been fully loaded (hence the use of window.onload = function(){}

    Personally, I'd suggest you the first option. Inserting JS code inside the phtml is conceptually wrong, because if you somehow you decide to not use jQuery anymore, you won't have to go inside all templates to find those snippets.