Search code examples
javascripthtmljqueryprepend

JQuery Prepend does not paste usable html code


I am trying to use recaptcha v3 for the website im creating right now. The problem I Have is, that everytime i use the jquery prepend function like this:

grecaptcha.ready(function () {
    // do request for recaptcha token
    // response is promise with passed token
    grecaptcha.execute('6Lf8MasZAAAAAPM2b9qSmFSwy4nOXMNbu9MxrZbx', {action: 'create_comment'}).then(function (token) {
        // add token to form
        document.getElementById('login-form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
    });
});

It does this on the site:

<form id="login-form" class="login-form">&lt;input type="hidden" name="g-recaptcha-response" value="03AGdBq24R7iIJoeIQecS7iwknDmE1wZI3I9cNs789wbkIdYCHaXeLXrM2N15zmKFqi026YKrrxpA-0wGlXlXwP0rVOkYbOQYWodkjP5YFDs6aWE35tdqg_4JP7WskTh75SDWa5DCSWkJBPxynLR2x1nWlUgie4MCo8SIS6C3XmSewf9uHfJvVb6z6Un0aW6Jnm1Ee4qMNsSlZKRd94sLecXWXA-pdEqA31VN13FFPZNVs5d_LR59zf5217F7NlAoO5WpNJ5ey-qT51ChhqLOrRpihZ9rW3xbi7G-shOcgwcX8Tapz02BW6V4mQuA8tAkHt00buI9Ylb1pSE4wK5RCYgkEppds3FDzRhcPgWDH2q8LyuGueNVi_J832S2jXy-qi6E-4ZpZThpg-Fo3G31xwB2mwiekT2wH_tIICngzv3w3oXsHl8LgsdHcv_yFsgKUWTuZjXqBlMnQU-PbyWffAtzGG7heJH-42A"&gt;
                <div class="field">
                    <div class="control">
                        <input class="input is-medium" name="email" type="email" placeholder="Email">
                    </div>
                </div>

                <div class="field">
                    <div class="control">
                        <input class="input is-medium" name="password" type="password" placeholder="Password">
                    </div>
                </div>
                <a href="#"><button id="login-button" type="button" class="button is-block is-primary is-fullwidth is-medium">Submit</button></a>
                <br>
                <small><em>Lorem ipsum dolor sit amet consectetur.</em></small>
            </form>

Do you guys have any idea how to fix this? Because right now it looks like this:

enter image description here


Solution

  • for pure js prepend work wit nodes not with string you can do like below with purejs

    var form=document.getElementById('login-form');
    form.innerHTML='<input type="hidden" name="g-recaptcha-response" value="' + token + '"/>'+form.innerHTML;
    

    or you can import jquery and use it like below

    $("#login-form").prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '"/>')