Search code examples
javascriptjqueryhidden-field

Convert jQuery function insertBefore() to before() for appending a hidden input


I have a block of code that uses jQuery to append a hidden field (with appropriate attributes) created by the attr() function. I'm currently using the insertBefore() function as shown below:

$('<input>').attr({
    name: 'token',
    type: 'hidden',
    value: 'value',
}).insertBefore( $('#form_id :submit') );

This correctly appends a new hidden DOM input element before the submit button of my #form_id form, but I'd like to use before() instead, as selecting my target before defining the content seems more readable to me.


Solution

  • Just before posting my question above, I tried one more time using before() from the ground up, and somehow I succeeded this time. So I decided to post my question and answer (solution) in hopes that it could help someone else trying to do the same in the future:

    $('#form_id :submit').before(
        $("<input>", {
            name: 'token',
            type: 'hidden',
            value: 'value',
        })
    );
    

    This code essentially returns a new DOM input element with the set attributes in the {} object we passed on. This returned element is the content argument we need to pass to before() to insert our hidden field before the element in our selector, the submit button of our ID in this case.