简体   繁体   中英

how to pass the value selected in an HTML table to a javascript function

I have three tables in my HTML form. Each table has different number of rows and upon double click of any row its value should be passed to a javascript function. These passed values should get appended to a text box present in the same form.

I have given Ids to all three tables and am passing this tableId to the function. Also, how to retrieve the value selected from the table into this javascript function.

What I have done so far is below. A small snippet of one table and the function. Am a newbie to HTML, so hoping for a few helpful answers. :)

    <table id="functionTable" >
            <tr>
               <td class="groupObjectTitle" nowrap>Functions</td>
            </tr>
            <td>
            <div class="easyui-panel">
                        <li>
                            <span>Mathematical</span>
                            <ul id="mathFunctions">
                                <li> <a href="javascript:" ondblclick="transferText('functionTable')">&nbsp; + </a></li>
                            ........
function transferText(table){
        var i;
        var k;
        var tabs= document.getElementById(table);
        alert("transferText called on double click");

        for (i=0;i<tabs.rows.length;i++){
            alert(tabs.rows[i].selected);    
            <!-- How to retrieve the value from the selected row. -->

        }
    }

Make sure your table ID's are NOT the SAME!


Solution 1

Use this and pass it as an argument to your function.

html

<a id="somevalue" href="javascript:" ondblclick="transferText('functionTable', this)">&nbsp; + </a>

javascript

    function transferText(table, element) {
        //element = clicked elment, so if you need the ID or some other data..   
        var elementId = element.id;
    }

Solution 2 (html5 req)

Use the html5 data attribute.

html

<a id="myid" data-mydata1="somedatavalue" data-mydata2="someothervalue" href="javascript:" ondblclick="transferText('functionTable', this)">&nbsp; + </a>

javascript

 function transferText(table, value) {
      var mydata = document.querySelector('#myid');
      var data1 = value.dataset.mydata1;
      var data2 = value.dataset.mydata2;
      //etc...
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM