Search code examples
javascriptjquerybookmarklet

Bookmarklet to auto fill textarea with random element name


I am trying to build a bookmarklet to auto-fill the textarea with attribute name="param[random-number][details]" with text.

enter image description here

The random-number is generated on the server and is different each time. The page HTML looks like:

<table>
<tbody>
<tr>
<td>Video Title:</td>                                                
<td>                            
<input type="text" name="param[30301754][title]" value="VIDEO TITLE" autocomplete="on">
</td>
</tr>

<tr>
<td>File name:</td>
<td>
<input type="text" name="param[30301754][filename]" value="FILE NAME" autocomplete="on">.3gp
</td>
</tr>
<tr>
<td>Description: </td>
<td><textarea name="param[30301754][description]"></textarea>
</td>
</tr>
</tbody></table>

Solution

  • Assuming there's only one element like <textarea name="param[xxx][description]"> on the page, you can use a jQuery wildcards as a selector.

    $("textarea[name$=\\[description\\]]").val("test");
    

    Update

    To do this as a simple bookmarklet, you'll need to prompt the user for the text they want to auto-populate (or get it from somewhere else), and wrap the whole thing in an anonymous function. You also need a reference to the jQuery library. (See this article for more information on how to create a bookmarklet.)

    This should do it for your case:

    javascript: (function () {
        if (!($ = window.jQuery)) {
            script = document.createElement('script');
            script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
            script.onload = doAutoFill;
            document.body.appendChild(script);
        } else {
            doAutoFill();
        }
    
        function doAutoFill() {
            var textToFill = prompt("Enter text to fill:");
            if (textToFill != null) $("textarea[name$=\\[description\\]]").val(textToFill);
        }
    })();
    

    Here's an updated fiddle as an example: jsfiddle