0

This is my function and I've tried thousand ways but still getting 'undefined' when calling outside.

var abc;
var zxc;
$("#checktext").on('click', function(e) {
  var text = document.getElementById("checktext").value,
    element = $("#checktext")[0],
    arr1 = text.split(" "),
    length = 0,
    selectIndex = element.selectionStart;
  if (selectIndex == 0) {
    abc = arr1.indexOf(arr1[0]);
    console.log(arr1.indexOf(arr1[0]));
    return abc;
  } else {
    for (var i = 0; i < arr1.length; i++) {
      length = length + arr1[i].length + 1;
      if (length == selectIndex) {
        zxc = i + 1;
        console.log(i + 1);
        return zxc;
        break;
      }
    }
  }
});
document.write(abc);
document.write(zxc);

Getting undefined when calling in document.write().

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    You're calling `document.write()` when the page first loads. But the variables aren't set until the user clicks on `#checktext`. What are you expecting it to write? Do you think it can predict the future? – Barmar May 27 '22 at 15:54
  • Hi @Barmar Yes, you're right. But when I click on checktext id tag then still the undefined don't change with coming value. Is there any way to get the value and compare the coming values of abc, zxc on another function. – Jack Hickson May 27 '22 at 16:05
  • Put `console.log(abc, zxc)` inside the function to see the values after you've clicked. – Barmar May 27 '22 at 16:13
  • Yes, inside function by console.log or alert its showing result. I want to take that result and use over above the page. – Jack Hickson May 27 '22 at 16:24
  • You can use it elsewhere in the page. It just has to be in code that runs after the user clicks on the input field. For instance, you could use it in the click handler for a button, or the submit handler for a form, etc. – Barmar May 27 '22 at 16:25
  • But you can't use it in top-level code, because that all runs when the page first loads, it doesn't wait for the click. – Barmar May 27 '22 at 16:27
  • Yes, I totally get. But is there anyway. If after click and I use it outside below the code? Like Can I access it below outside the function after user click? – Jack Hickson May 27 '22 at 16:28
  • I already answered that. I also gave you a link to a question that explains the whole topic. – Barmar May 27 '22 at 16:33

0 Answers0