jQuery-Filling an Input Box in WordPress Admin

Though I have somehow managed to produce some relatively complex scripts, I am still at the stage with jQuery that, when I manage to achieve some elementary thing, I throw a little celebration in my trusty old Aeron.

I also tend to forget what I’ve figured out until the next time I have to achieve the same effect. So, here are some notes for future reference, or for the sake of other jQuery hackers, on how I think a textbox should be filled in WordPress Admin… from simple anchor links… and when the content – in this instance long image links –  is too long to be nicely contained.

The Specific Problem

In WP-RUBI, there’s a point where I want to give the user the option to employ some alternative versions of a default image.

Before I decided to spruce things up, the part of the draft version of the “Set Replacement” section in which we’re interested looked something like this:

wp-rubi-settings-3

(Just as a probably at this late date unnecessary reminder: All of the images in this post can be “embiggened,” as we used to say, with a click…)

Now, I could add these default images to the sequence of radio buttons (partially shown) which provide still more options for “Replacement Mode,” but the additional default images are more like “sub-alternatives” than major alternatives, and the options page is already long enough.

A reasonably sophisticated user probably knows to highlight the text, in this case a filename beginning http://localhost…, to be copied, then paste it into the box, but that’s kind of a lame, painstaking process even if you know to do it. Other users will try typing out the characters one by one. Either way, the work will be made more difficult or uncertain by the fact that the text box is too short for a long URL: Users will want check the link, and few users will also suspect that they can produce a look at the textbox contents – or, formally, the “type ‘url’ input box” – just by double-clicking on them.

double_click_text_box_to_sh

I don’t think I was aware I could (sometimes!) double-click to show full textbox contents until today, and I’ve been doing this since before there were computers almost.

I could style the input text to a smaller font-size, but doing so might cause eyestrain, and, anyway, we’re having fun with jQuery: So, let’s do it differently.

Basic Solution

Looking ahead, first we’ll add the elements we’re going to be acting on in the PHP/HTML mark-up, in the form of CSS selectors for jQuery to find. Since I already had an ID for input box (upload_image), the only things I needed to add specific to this objective were the def_image_link classes in the highlighted lines, which add two new image-link choices:

…which is going to output like this:

text-to-textbox-links-new_output

I won’t go into all the whats and whys of the PHP/HTML or the general approach I’m taking here, except to say that it’s all for use in a plug-in options page, this specific plug-in options page, and that, in case it isn’t obvious, plugins_url( 'REST OF LINK', __FILE__ ) converts the whole part of the link prior to REST OF LINK and adds them together: As already noted, the resultant image-links are already long, like, what?, 75 characters? I’m not going to count them, and don’t you do it either! Life’s too short.

Our jQuery script is going to make it so that all that the user has to do is click on any one of those links to transfer it instantly to the textbox.

Simple, right? Too simple for anyone much to bother to document it… until right here!

Actually, I think the problem is more that it’s so simple it was already primitive when jQuery was new, and that was 9 years and 11 months ago.

Our new script (which we’ll register and enqueue separately in its own file, since that seems to work better across installations in initial testing) gets the value of the selected link item def_image_link and puts it into the input textbox id’d as upload_image in the mark-up. Except for those class and id names, the following has hardly been modified from a ready example among many I ran across:

The main difference otherwise between the above and the most basic references you’ll find in jQuery documentation is the use of the “this” keyword on the third line. Otherwise, code doesn’t get much simpler, although non-WordPressers stumbling onto this post might be wondering why I’m typing “jQuery” over and over again, and might also be wondering why the script is being written out instead of attached as it were in situ to the click function. (Short answers: 1) You can’t use the $ sign, or, if you want to, you have to tell WP you’re going to, and, 2), in WordPress it’s preferred and often necessary and actually works out nicely to enqueue even the simplest scripts in separate .js files.)

So, it works, but it’s not very good. Specifically, the results will be sub-optimal in two ways:

  1. When you click on the link, the page “jumps” – or jumps or reloads or travels, etc. – depending on what kind of link you use after “href.” Even if you pointed it directly to upload_image (<a href="#upload_image"…), it would still jump distractingly. Since I want the links actually to link to the image files, but not take the user to them, the action would be even more problematic.
  2. When the textbox is filled, the only part of the image filename that’s actually changing as a result of the operation (_background or _white) is hidden – meaning you can’t tell immediately that the desired exchange of the new filename for the old one was in fact achieved. As already discussed above, users are going to end up looking at the textbox and clicking on it or side-scrolling to be sure it’s what they wanted.

So: Slightly more sophisticated solution

Solving these two problems was almost as simple as creating them was, although one involved using a CSS argument – direction - that I’d never used before.

To solve the first problem, we just need to stop the default click action from occurring. For this purpose, jQuery provides the aptly method event.preventDefault().

To solve the second problem, we just need to add a CSS class and style it.

Putting them together:

To style the addClass added class “url-rtl” in my plug-in admin css file:

So, now, when the user clicks on one of the links, the textbox gets filled with the live-clicked link’s html, formatted right to left (rtl) instead of left to right (ltr), which latter is the style previously set for all input[type=url]s… And now also, thanks to preventDefault, there isn’t any jumping around.

text-to-textbox-links-for-j

Just after clicking…

Close-up on the rtl part:

text-to-textbox-links-cu

That’s about all there is to it…

…except for one thing: When you thereafter want to work with the url/textbox (#upload_image), dealing with an “rtl”-formatted box in a “ltr” language will be confusing – for instance, if I change my mind and try a shorter URL, it’ll look like it has a bunch of spaces at the beginning…

text-to-textbox-links-rtl-confusion

…and the text itself will behave unexpectedly when and if I try to change it manually. Don’t ask. You just don’t want to deal with it. Luckily, it’s easy to remove the just-added class as soon as anyone clicks on the box – and this time let’s recuperate the familiar “$” sign, since now the re-typing of “jQuery” is getting distracting, at least to me – heck, and while we’re at it let’s add extra readability spaces just because we can:

That works.

(updated 17 July 2016)


WordPresser
Home Page  Public Email  Twitter  Facebook  YouTube  Github   

Writing since ancient times, blogging, e-commercing, and site installing-designing-maintaining since 2001; WordPress theme and plugin configuring and developing since 2004 or so; a lifelong freelancer, not associated nor to be associated with any company, publication, party, university, church, or other institution. 

Posts in this series

Commenter Ignore Button by CK's Plug-Ins

Leave a Reply

Your email address will not be published. Required fields are marked *

*

WordPress Plug-In Notes

  1. Realizing the Commentariat (May 8, 2015)
  2. Child of Mog; Extraordinary Comments (May 25, 2015)
  3. Patronize 'Em: WordPress Draft Post Docket with Subscription and Donation Options (June 9, 2015)
  4. Realizing The Commentariat: Phase 2 (June 22, 2015)
  5. Pseudo-Redacting Spoilerer (July 25, 2015)
  6. Spoiling you some more (August 5, 2015)
  7. Testing Ajaxified Comments - Experiment Halted (August 11, 2015)
  8. New New Since Last Visit Comments Comments (August 16, 2015)
  9. WordPress Comment Nesting Unbound (August 22, 2015)
  10. The Snake Is Implemented (August 25, 2015)
  11. Comments Since Last Visit Reloaded, Reloaded, Testing Post (August 31, 2015)
  12. Comments Since Last Visit, Reloaded, Augmented, Installed, In Two Steps (September 13, 2015)
  13. Coming Soon (I Think!): Author Bios (September 25, 2015)
  14. How to Do Backlinking Footnotes (November 30, 2015)
  15. Who or What Is Using "Commenter Archive" and "commenter-thread"? (February 16, 2016)
  16. Enabling WordPress Press This for HostGator Sites (March 9, 2016)
  17. Linkback Your Xpost: A Simple WordPress Filter Function (March 14, 2016)
  18. Add Amazon Affiliate Tags to WordPress Posts <i>and</i> Comments Automatically (March 19, 2016)
  19. Finding Lost WordPress Widgets after Core Upgrade (March 21, 2016)
  20. Plug-In Away... and the Iron Law of Irony (April 16, 2016)
  21. To o-b or not to o-b (output-buffering in WordPress) - UPDATED (April 24, 2016)
  22. Output-Buffering and Extensible WordPress Plug-Ins (May 21, 2016)
  23. Getting Right with Image Rights: WP Replace Unlicensed and Broken Images Plug-In (June 17, 2016)
  24. Getting Right with Image Rights: Workflow and Major Minor Upgrade (June 27, 2016)
  25. Getting to Better WordPress Twitter oEmbed (June 28, 2016)
  26. An Alliance of Digital Artists (Art and Work in the Age of Instant Reproducibility) (July 8, 2016)
  27. Comparative Page Loads with and without Image Errors (July 14, 2016)
  28. jQuery-Filling an Input Box in WordPress Admin (July 15, 2016)
  29. Drilling a Hole in the Universe with WP_Query in a Shortcode (September 1, 2016)
  30. Troll-Stomping and Other Sensible Things: #WordPress Plug-In Beta Test/Preview (November 12, 2016)
  31. Commenter Ignore Button Preview Video (November 30, 2016)
  32. Is This Solution for Caches vs Cookies Going to Get Me in Trouble? (November 30, 2016)
  33. Commenter Ignore Button 0.99 (December 21, 2016)
  34. Adding wp.media Multiple Image Selection to WordPress Plug-Ins (January 5, 2017)
  35. Working around an Unexplained Failure of WordPress {$taxonomy} Hooks (January 10, 2017)In Progress: Subscribe!
  36. Better Twitter Embeds 2: Stripping the Convo for the Sake of the Convo (February 19, 2017)

Noted & Quoted

This is a Waterloo moment for Trump, the tea party and their alliance.  They have been stopped in their tracks not only by Democratic opposition but because of a mutiny within their own ranks. Although never particularly liked or respected, it is now clear that they are no longer feared. The bankruptcy of their ideas and their incompetence have been exposed. Their momentum has been dissipated. Their rejection of political norms has itself been scorned. Our long national nightmare may finally be coming to an end.

Comment →

One seasoned Democrat told me that among the reasons Trump won in 2016 was that a long year of Crooked Hillary talk, about emails and Goldman Sachs and the like, had steadily demoralised and demobilised the liberal base. If sustaining fury at Trump helps keep those same voters energised, so they eventually turn out to defeat him, it’ll be worth it, he says.

But it can’t just be in the form of world-weary, if witty, tweets. What’s needed is a coherent argument, one that explains why Trump’s repulsive behaviour matters. For Americans, that will surely centre on the state of their society. The civic realm is being degraded by Trump’s lies, vanities and insults. The national conversation is being coarsened. The basic democratic assumption, that disagreements can be resolved through discussion rather than coercion and violence, is being eroded from the very top. Note the language of Scaramucci’s outburst: “I want to fucking kill all the leakers.”

Comment →

[C]limate scientists have a strange kind of faith: We will find a way to forestall radical warming, they say, because we must.

It is not easy to know how much to be reassured by that bleak certainty, and how much to wonder whether it is another form of delusion; for global warming to work as parable, of course, someone needs to survive to tell the story. The scientists know that to even meet the Paris goals, by 2050, carbon emissions from energy and industry, which are still rising, will have to fall by half each decade; emissions from land use (deforestation, cow farts, etc.) will have to zero out; and we will need to have invented technologies to extract, annually, twice as much carbon from the atmosphere as the entire planet’s plants now do. Nevertheless, by and large, the scientists have an enormous confidence in the ingenuity of humans — a confidence perhaps bolstered by their appreciation for climate change, which is, after all, a human invention, too. They point to the Apollo project, the hole in the ozone we patched in the 1980s, the passing of the fear of mutually assured destruction. Now we’ve found a way to engineer our own doomsday, and surely we will find a way to engineer our way out of it, one way or another. The planet is not used to being provoked like this, and climate systems designed to give feedback over centuries or millennia prevent us — even those who may be watching closely — from fully imagining the damage done already to the planet. But when we do truly see the world we’ve made, they say, we will also find a way to make it livable. For them, the alternative is simply unimaginable.

Comment →
CK's WP Plugins

State of the Discussion

+ BTW, I recently upgraded some this and that on the back end of the blog, and it does seem to make comments post much faster [. . .]
Gutenberg: The Invention of the Printing Press, the Destruction of WordPress

For WordPress self-hosted people, there is already a "restore legacy editor" plugin, even though Gutenberg hasn't been installed yet as the default.

Gutenberg: The Invention of the Printing Press, the Destruction of WordPress
+ I thought you were on WordPress.com, not self-hosted WordPress. I can't find any info on WordPress.com and Gutenberg or Gutenbergerish editing, so I don't know [. . .]
Gutenberg: The Invention of the Printing Press, the Destruction of WordPress

Extraordinary Comments

CK's WP Plugins

Categories

Related