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:

    <!-- Textarea -->
    <div class="form-group">
    <label class="col-md-2 control-label" for="editor1">Insert your text here </label>
    <div class="col-md-10">                     
    <textarea class="form-control" id="editor1" name="editor1"><p>text example with ahöäåra</p></textarea>
    </div>
    </div>
    <!-- KW density result -->
    <div class="form-group">
    <label class="col-md-2 control-label" for="editor1">Suggested SEO keywords</label>
    <div class="col-md-10">                     
    <div id="KWdensity" ></div>
    </div>
    </div> 

Here is the javascript code:

<script type="text/javascript">
    $(document).ready(function() {
    CKEDITOR.replace('editor1');
    $(initKW);
    CKEDITOR.instances.editor1.on('contentDom', function() {
    CKEDITOR.instances.editor1.document.on('keyup', function(event) {
    $(initKW);
    });
    });
    function KeyDensityShow(srctext, MaxKeyOut, keylenMin) {
    var Output;
    var words = srctext.toLowerCase().split(/[^p{L}p{M}p{N}]+/u)
    var positions = new Array()
    var word_counts = new Array()
    try {
    for (var i = 0; i < words.length; i++) {
    var word = words[i]
    if (!word || word.length < keylenMin) {
    continue
    }
    if (!positions.hasOwnProperty(word)) {
    positions[word] = word_counts.length;
    word_counts.push([word, 1]);
    } else {
    word_counts[positions[word]][1]++;
    }}
    word_counts.sort(function(a, b) {
    return b[1] - a[1]
    })
    return word_counts.slice(0, MaxKeyOut)
    } catch (err) {
    return "";
    }}
    function removeStopWords(input) {
    var stopwords = ['test', ];
    var filtered = input.split(/b/).filter(function(v) {
    return stopwords.indexOf(v) == -1;
    });
    stopwords.forEach(function(item) {
    var reg = new RegExp('\W' + item + '\W', 'gmi');
    input = input.replace(reg, " ");
    });
    return input.toString();
    }
    function initKW() {
    $('#KWdensity').html('');
    var TextGrab = CKEDITOR.instances['editor1'].getData();
    TextGrab = $(TextGrab).text();
    TextGrab = removeStopWords(TextGrab);
    TextGrab = TextGrab.replace(/r?n|r/gm, " ").trim(); 
    TextGrab = TextGrab.replace(/ss+/g, " ").trim();
    if (TextGrab != "") {
    var keyCSV = KeyDensityShow(TextGrab, 11, 3);
    var KeysArr = keyCSV.toString().split(',');
    var item, items = '';
    for (var i = 0; i < KeysArr.length; i++) {
    item = '';
    item = item + '<b>' + KeysArr[i] + "</b></button>&nbsp;";
    i++;
    item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"><span class="badge">' + KeysArr[i] + "</span>&nbsp;" + item;
    items = items + item;
    }
    $('#KWdensity').html(items);
    }}});
</script>

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

The keywords box:
 <input type="text" id="thebox" value="" style="width:80%;height:30px;background:#000;color:#fff;"/>
    <br><input type="button" value="this one is working" onclick="document.getElementById('thebox').value='test button is working';">

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

keyword,

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

item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"><span class="badge">' + KeysArr[i] + "</span>&nbsp;" + item;

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

<button
  class="btn btn-default btn-xs"
  type="button"
  onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"
>

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

onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"
                                               ^--- problem here       ^--- and here

It should’ve been

onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"
                                               ^--- fixed here          ^--- and here

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:

onclick="document.getElementById("thebox").value="head of gwyneth paltrow";"
                                 ^---    ^--- fixed here

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:

item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById('thebox').value='' + key + '';"><span class="badge">' + KeysArr[i] + "</span>&nbsp;" + item;
                                                                                              ^--     ^--       ^^^^^^^^^^^^^^--- changed here (notice in the demo below I declare the key variable before using it here)

Updated fiddle here. Running demo below as well.

$(document).ready(function() {
  CKEDITOR.replace('editor1');
  $(initKW);
  CKEDITOR.instances.editor1.on('contentDom', function() {
    CKEDITOR.instances.editor1.document.on('keyup', function(event) {
      $(initKW);
    });
  });

  function KeyDensityShow(srctext, MaxKeyOut, keylenMin) {
    var Output;
    var words = srctext.toLowerCase().split(/[^p{L}p{M}p{N}]+/u)
    var positions = new Array()
    var word_counts = new Array()
    try {
      for (var i = 0; i < words.length; i++) {
        var word = words[i]
        if (!word || word.length < keylenMin) {
          continue
        }
        if (!positions.hasOwnProperty(word)) {
          positions[word] = word_counts.length;
          word_counts.push([word, 1]);
        } else {
          word_counts[positions[word]][1]++;
        }
      }
      word_counts.sort(function(a, b) {
        return b[1] - a[1]
      })
      return word_counts.slice(0, MaxKeyOut)
    } catch (err) {
      return "";
    }
  }

  function removeStopWords(input) {
    var stopwords = ['test', ];
    var filtered = input.split(/b/).filter(function(v) {
      return stopwords.indexOf(v) == -1;
    });
    stopwords.forEach(function(item) {
      var reg = new RegExp('\W' + item + '\W', 'gmi');
      input = input.replace(reg, " ");
    });
    return input.toString();
  }

  function initKW() {
    $('#KWdensity').html('');
    var TextGrab = CKEDITOR.instances['editor1'].getData();
    TextGrab = $(TextGrab).text();
    TextGrab = removeStopWords(TextGrab);
    TextGrab = TextGrab.replace(/r?n|r/gm, " ").trim();
    TextGrab = TextGrab.replace(/ss+/g, " ").trim();
    if (TextGrab != "") {
      var keyCSV = KeyDensityShow(TextGrab, 11, 3);
      var KeysArr = keyCSV.toString().split(',');
      var item, items = '';
      var previousKeys = [];
      for (var i = 0; i < KeysArr.length; i++) {
        item = '';
        var key = KeysArr[i];
        previousKeys.push(key);
        item = item + '<b>' + key + "</b></button>&nbsp;";
        i++;
        item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById('thebox').value='' + previousKeys.join(', ') + '';"><span class="badge">' + KeysArr[i] + "</span>&nbsp;" + item;
        items = items + item;
      }
      $('#KWdensity').html(items);
    }
  }
});
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="//cdn.ckeditor.com/4.6.1/standard/ckeditor.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- Textarea -->
<div class="form-group">
<label class="col-md-2 control-label" for="editor1">Insert your text here </label>
<div class="col-md-10">                     
<textarea class="form-control" id="editor1" name="editor1"><p>text example with ahöäåra</p></textarea>
</div>
</div>
<!-- KW density result -->
<div class="form-group">
<label class="col-md-2 control-label" for="editor1">Suggested SEO keywords</label>
<div class="col-md-10">                     
<div id="KWdensity" ></div>
</div>
</div> 



The keywords box: <input type="text" id="thebox" value="" style="width:80%;height:30px;background:#000;color:#fff;"/>
<br><input type="button" value="this one is working" onclick="document.getElementById('thebox').value='test button is working';">
2 People found this is helpful
Advertisement