Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript get all inputs inside div including select and textarea

I have been trying to figure out how to get all the input elements inside a div including select and textarea and pass them to editor, so far i figured out with input but i am just stuck with the rest.

Here is the code so far

function InsertShortcode(elem) {
        var shortcodeName = elem.parentElement.id;
        var inputs = document.getElementById(shortcodeName).getElementsByTagName('input'), i=0, e;
        var inputs_val = '[' + shortcodeName;
        while(e=inputs[i++]){
            if(e.id){
                inputs_val += ' ' + e.id + '="' + e.value + '"';
            }
        }
        inputs_val += ']';

        window.send_to_editor(inputs_val);
    }

By this i am able to grab all the inputs inside a div where submit button is but still i am not sure how to grab textarea or select inputs.

The problem is that i have to make it dynamic. I will have many "shortcodes" and each will be in it's own div where the button is. But each will have it's own inputs which i can't control so i need to grab them all and send values to editor. Here's example of the code.

    <div class="output-shortcodes">
        <?php foreach( $theme_shortcodes as $key => $name ) { ?>
            <div id="<?php echo $key ?>">
                <p>
                    <h2><?php echo $name ?></h2>
                </p>
                <?php $form = $key . '_form';
                    if(function_exists($form)) {
                        $form(); // this is where the input fields are dynamically created on each shortcode.
                    }
                ?>
                <button class="button-primary" onclick="InsertShortcode(this)">Insert shortcode</button>
            </div>
        <?php } ?>
    </div>
like image 389
lonerunner Avatar asked Dec 08 '15 19:12

lonerunner


1 Answers

Use jQuery and the :input pseudo selector:

$('.output-shortcodes').find(':input');

That simple.

https://api.jquery.com/input-selector/

Or wrap it in a <form>, then you can use:

document.getElementById("outputForm").elements...

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements

like image 169
Kong Avatar answered Oct 30 '22 17:10

Kong