Skip to content
Advertisement

Button generated inside javascript code to onclick insert value in input type text in form

I have a very nice SEO-keyword suggestion tool working with CKeditor, it displays the most used word in the text while writing. The problem is that I want to make these generated keywords clickable one by one. So when you click on a keyword, it auto-fills an input-type text.

Here is the HTML code:

JavaScript

Here is the javascript code:

JavaScript

And here is some extra HTML for the input that needs to be auto-filled.

JavaScript
JavaScript

So if you write something, it will generate keywords buttons. When you click on one of these buttons, the keyword must be entered in the input text like this

JavaScript

Here is a Fiddle DEMO.

Any idea how to fix that? I added a document.getElementById('thebox'). but it does not return anything

Advertisement

Answer

Your code in

JavaScript

Will add to the DOM (in other words, to the HTML of the page), the following bit:

JavaScript

Now, the resulting onclick above has some problems. First, notice that the quotes it uses in the string after .value= are actually closing the onclick declaration because they are not escaped. I mean, instead of

JavaScript

It should’ve been

JavaScript

Secondly, the argument to .getElementById(thebox) is thebox. Notice here that the way it is now, thebox is actually a variable, not a string. So instead of the above, what you want is:

JavaScript

These fixes should be enough to make the clicks on the words set the "head of gwyneth paltrow" value in the textbox.

I believe, though, you want to actually set the key when the button is clicked. To do that, instead of having "head of gwyneth paltrow" after the .value, you should have the text of the key. All in all, here’s how that line could be:

JavaScript

Updated fiddle here. Running demo below as well.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement