I have a text input box and some links on a webpage. When I click on one of the links, I want to set the text of the search box to whatever the link text is. How do I do this? I have jQuery as well. I can't change the way the function executes though. I have to keep it as "href=javascript:".
function setText(this) {
$("#searchBox").val(this);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="searchBox">
<a class="link" href="javascript:setText(this)">Example 1</a>
<a class="link" href="javascript:setText(this)">Example 2</a>
<a class="link" href="javascript:setText(this)">Example 3</a>
<a class="link" href="javascript:setText(this)">Example 4</a>
First, the
href
in your links should just be set to the URL where you want to navigate to. Usingjavascript:...
inline with your HTML is a 25+ year old technique that isn't used in modern coding.Your event handlers should be set up in JavaScript, not inline with your HTML and while I'll show you how to accomplish the main effect with JQuery, this is hardly a reason to use JQuery, as this is a quite trivial thing to do without it.
And, if you are not actually navigating anywhere when the links are clicked, then you shouldn't be using hyperlinks in the first place - they are only for navigation and if you don't use them for that, it can cause accessibility problems. If this is the case, just replace them with an inline element like
span
(the rest of the code will still work as it is).