getElementById when the id is a php query

0

Good morning I have a checkbox with the id defined by a result of an sql query in php

<input type="checkbox" id="<?php echo $row['identificacion']."1"; ?>" onchange="return habilitar()">

and I'm trying to put it in a getElementById for a function

function habilitar() {
chkb = document.getElementById("<?php echo $row['identificacion']."1"; ?>");
    //chkb = document.getElementById("chk2");
    if (chkb.checked) {

I do not know what I'm doing wrong but it does not work for me, if I use a function to see the id of the checkbox if it shows it without problem

thanks

    
asked by Nestor Bautista 05.01.2018 в 17:45
source

2 answers

1

What you are trying to do, it is not possible, although I understand your intention.

A file or JavaScript code does not interpret PHP code, since the php code can only be executed from the server . Yes it is true that if you include JS code in a PHP script, it is possible to concatenate PHP results with JS code, this is usually used when we want to generate JS code dynamically.

With the first response that Camilo Vasquez has given you, it can help you, as far as we can understand, what you want to do with that code. But if you want to continue that way because you want to get another kind of effect, you could do the following:

For this case you should have a hidden input with an already assigned and recognizable id (that is not dynamic like the one you are trying to pick up), then add the value of your row to it. query. Now you can pass to your getElemenById () the value of this hidden input.

You can see it in this example:

<input type="hidden" id="idCheckbox" value="<?php echo $row['identificacion']."1"; ?>"/>
<input type="checkbox" id="<?php echo $row['identificacion']."1"; ?>" onchange="return habilitar()">
function habilitar() {
    var idCheckbox = document.getElementById("idCheckbox").value;
    chkb = document.getElementById(idCheckbox);
    //chkb = document.getElementById("chk2");
    if (chkb.checked) {
    
answered by 05.01.2018 / 18:40
source
0

One solution may be to send the element ( this ) as a parameter to your function, so you should not use that getElementById

function habilitar(elemento) {
    if (elemento.checked) {
        console.log('chekeado');
    }else{
        console.log('no chekeado');
    }
}
<input type="checkbox" id="codigo_php" onchange="return habilitar(this)">

Now, if what you want is to use the selector at all costs then do it in the following way:

var selector = "<?php echo $row['identificacion']?>" + 1;
document.getElementById(selector);
    
answered by 05.01.2018 в 17:49