Is it possible to get the value of a element using onclick?

前端 未结 6 1598
[愿得一人]
[愿得一人] 2020-12-22 07:51

I currently have a table that has a list of email template names being echoed using php. Below is part of the php code. I\'m trying to grab the table value and pass it to

相关标签:
6条回答
  • 2020-12-22 08:28

    its work.

    function clickValue(elem) {
      var x = document.getElementById(elem).innerHTML;
      alert(x);
    }
    <table>
      <th>Coba</th>
      <tr>
        <td id="1" onclick="clickValue('1')">value</td>
      </tr>
      <tr>
        <td id="2" onclick="clickValue('2')">value yg ke 2</td>
      </tr>
    </table>

    Change id="*anyvalue*" and clickValue('*anyvalue*')

    0 讨论(0)
  • 2020-12-22 08:29

    You can do it either by

    function moveValue()
    {
      var x = document.getElementById('test');
      var y = x.innerHTML;
      alert(y);
    }
    

    or by:

    function moveValue(element) {
      var y = element.innerHTML;
      alert(y);
    }
    //with the following html code:
    <td onclick="moveValue(this)">'.$email['email_name'].'</td>
    
    0 讨论(0)
  • 2020-12-22 08:32

    You id attribute would be the same for every td inside the loop. So JS would not know which element you want.

    You could try passing this into the onclick method

    HTML

    <td onclick="moveValue(this);">
    

    JS

    function moveValue( elem )
    {
        alert(elem.innerHtml);
    }
    

    I would take a look at jQuery if I were you. It makes all this stuff much easier to achieve.

    0 讨论(0)
  • 2020-12-22 08:40

    With javascript:

    To get raw text without any elements or:

    somevar=document.getElementById ( "test" ).innerText;
    

    To get full html code of tag. Contents will be stored in 'somevar' variable.

    somevar=document.getElementById ( "test" ).innerHTML;
    
    0 讨论(0)
  • 2020-12-22 08:42

    Javascript:

    var y = document.getElementById("test").innerText;
    

    jQuery:

    $("#test").text();
    

    To get the HTML:

    var html = document.getElementById("test" ).innerHTML;
    

    jQuery:

    $("#test").html();
    
    0 讨论(0)
  • I don't want to get into all the problems with your code as there are rather a lot. However, getting the value of a <td> element by clicking is trivial to achieve.

    You first need to assign a click handler to each cell in your table. The easiest way to do this is to loop through each cell and assign the handler like so:-

    var cells = document.getElementsByTagName('td');
    for(var i = 0; i <= cells.length; i++){
        cells[i].addEventListener('click', clickHandler);
    }
    
    function clickHandler()
    {
        alert(this.textContent);
    }
    

    Then every time you click on a cell the clickHandler() will be called and you can run whatever code you wish.

    You can see it working in this fiddle

    Lots of information here https://developer.mozilla.org/en-US/docs/Web/API

    0 讨论(0)
提交回复
热议问题