简体   繁体   中英

How do I send a specific (generated) variable in PHP to a JavaScript?

I have a PHP page that generates different invoices in a search function and each invoice has a table that gets shown when the user clicks on a button (via JavaScript). The question is how to send a specific button id to the JavaScript. This is my code so far.

echo '<input type="submit" onclick="newDisplay()" style="padding: 5px;width: 90px;" value="Add Receipt">';

And

$idName = 'myForm' . $job['id'];
echo '<table style="display:none;width:100%;" id="' . $idName . '">';

Then the JavaScript is:

function newDisplay() {
        document.getElementById('<?php echo $idName; ?>').style.display = 'block';
    }

If a button is generated for each invoice, is there a way to send the element ID plus the invoice ID so that only the one specific table gets shown? I can concatenate the job id to the myForm, but how would I check that with the JavaScript?

EDIT: I tried the concatenation, but the JavaScript picks up the last one.

You can do something like this

 echo '<input type="submit" id="' . $id .'" data="" onclick="newDisplay(this.id)" style="padding: 5px;width: 90px;" value="Add Receipt">';

And in javascript

function newDisplay(id) {
//doanything with the id
        document.getElementById('myForm').style.display = 'block';
    }

You can also access any extra attribute you want to send in js like

function newDisplay(id) {
 let my_attr=$("#"+id).attr("data");
    //doanything with the id
            document.getElementById('myForm').style.display = 'block';
        }

If your id is numeric then you might need to append any alphabet or word before that like

echo '<input type="submit" id="my_' . $id .'" data="" onclick="newDisplay(this.id)" style="padding: 5px;width: 90px;" value="Add Receipt">';

And then in js you can access the id like

function newDisplay(id) {
var myid=id.split("_");
//doanything with the myid[1]
        document.getElementById('myForm').style.display = 'block';
    }

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