skip to Main Content

I have a DJANGO app and want to get the values of text in JAVASCRIPT when it gets selected but getting undefined instead.

my code:

<div class="askedDiv">
  {% for i in recentlyUsed %}
    <p onclick="myFunction()" id="myBtn">{{i}}</p>
  {% endfor %}
</div>

in js:

function myFunction() {
  const x = document.getElementById("myBtn").value;
  console.log(x)
}

but in console i’m getting undefined.

How can I get different text name, when it is selected from recentlyUsed list.

3

Answers


  1. If you want the text, then simply pass the desired value to the function as an argument, no need to use DOM methods to get it:

    <p onclick="myFunction('{{i}}')" >{{i}}</p>
    
    function myFunction(x) {
      console.log(x)
    }
    

    And if you still need the element, you can pass it too:

    <p onclick="myFunction('{{i}}', this)" >{{i}}</p>
    
    function myFunction(x, el) {
      console.log(x, el);
    }
    
    Login or Signup to reply.
  2. I haven’t tested this approach on my local. You can do the one below

    // option 1: pass the event object so function is reusable and can be applied to any element
    
    function getValue(e) {
      const value = e.target.innerText; // if you want to get the text value
      // const value = e.target.innerHTML; // if you want to get the markup value
      
      console.log(value);
    }
    
    // option 2: use your current code but fix to that paragraph only basd on id selector
    
    function getValue2() {
       const value = document.getElementById('my-btn').innerText;
       
       console.log(value);
    }
    
    
    // option 3: use the document
    
    // as an alternative, you can bind your click even to the document to dynamically get the value of any element in your document
    document.addEventListener('click', function(e) {
      const value = e.target?.value || e.target.innerText;
      
      console.log(e.target);
    });
    <div>
      <p onclick="getValue(event)">Option 1</p>
    </div>
    
    
    <div>
      <p onclick="getValue2()" id="my-btn">Option 2</p>
    </div>
    
    <div>
      <p>Option 3</p>
    </div>

    Additional Information:
    The reason why your code is not working is because the paragraph element doesn’t have a value property. Value property only works for inputs since their property exists to set/get the value.

    Login or Signup to reply.
  3. Try this:
    html

    <div class="askedDiv">
      {% for i in recentlyUsed %}
        <p onclick="funName(this)">{{i}}</p>
      {% endfor %}
    </div>
    
    

    Js

    function funName(e) {
      console.log($(e).text());
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search