Functions onclick on a href - PHP - Javascript

1

I have the following code in a form, it belongs to a column of a table with data collected from a MySQL database.

echo "<td width=\"08%\" id=\"estado".$row['ID_OBLIGATORIO']."\">" ?>
<!-- Columna ESTADO del usuario. -->
    <center>
    <?php
        $estado = 1;
        echo "<a href='#' onclick='return cambiar_estado(".$row['ID_OBLIGATORIO'].");'\">";
              echo "<img src=\"/imagenes/".$row['estado'].".gif\">";
        echo "</a>";
        ?>
    </center>
    <?php 
echo "</td>";   

Now I have the following function, in which clicking on each ID element of the state column of the table, I would put an image x.gif, or put a text "We have clicked on this image" as a series to test.

<script language="Javascript">
function cambiar_estado() {
    var img = "";
    var pregunta = confirm("¿Qué deseas elegir?");
    if (pregunta == true) {
        mg = "<center><img src='imagenes/0.gif'/></center>";
    } else {
        tmg = "<center><img src='imagenes/2.gif'/></center>";
    }
    document.getElementById("estado" +id).innerHTML = img;
}
</script>

What I want is that if all the rows start (all users) have the state = 1, I let me click to ask: Do you want to change the state = 0 or state = 2? And automatically call the image. I've already done that, but ... I edit the question: I have read that you can not change the alert or confirm () options - Cancel or Accept -, only if plugins or jQuery are used. Is it like that?

Why does not the function work with the following code? Of course, it does not give me failures in the console ... how weird you should not take the "id".

function cambiar_estado(id) {
    var imagen = "";
    //alert("El ID elegido es: "+id);
    var pregunta = confirm("¿Qué deseas elegir?");
    if (id == '1') {
        if (pregunta == true) {
            imagen = "<center><img src=\"/imagenes/0.gif\"></center>";
        } else {
            imagen = "<center><img src=\"/imagenes/2.gif\"></center>";
    } else if (id == '0') {
        if (pregunta == true) {
            imagen = "<center><img src=\"/imagenes/1.gif\"></center>";
        } else {
            imagen = "<center><img src=\"/imagenes/2.gif\"></center>";
    } else {
            imagen = "<center><img src=\"/imagenes/0.gif\"></center>";
        } else {
            imagen = "<center><img src=\"/imagenes/1.gif\"></center>";
    }
    document.getElementById("estado" +id).innerHTML = imagen;
}
    
asked by omaza1990 16.11.2016 в 12:57
source

4 answers

3

Try making these changes:

  • Passes the registration ID in the function cambiar_estado

    <?php
    echo "<td width=\"08%\" id=\"estado".$row['ID_OBLIGATORIO']."\">" ?>
    <!-- Columna ESTADO del usuario. -->
        <center>
        <?php
            $estado = 1;
            echo "<a href='#' onclick='return cambiar_estado(".$row['ID_OBLIGATORIO'].");'\">"; // Pasamos el ID
                  echo "<img src=\"/imagenes/".$row['estado'].".gif\">";
            echo "</a>";
        ?>
        </center>
    <?php 
    echo "</td>"; ?>
    
  • Modify the javascript function cambiar_estado , so that it accepts the ID per parameter.

    <script language="Javascript">
    // Recibe ID 
    function cambiar_estado(id) {
        var texto = "";
        var pregunta = confirm("¿Qué deseas elegir?");
        if (pregunta == true) {
            texto = "¡Has presionado OK!";
        } else {
            texto = "¡Has presionado Cancelar!";
        }
    
        // Buscamos el DOMElement con id="estado[ID]"
        document.getElementById("estado" + id).innerHTML = texto;
    }
    </script>
    
answered by 16.11.2016 в 13:17
1

What you have to do is click on the <td> to get the value of the attribute id .

<td onclick="cambiar_estado(this);" width=\"08%\" id=\"estado".$row['ID_OBLIGATORIO']."\">

And the function

<script language="Javascript">
function cambiar_estado(row) {
    var texto = "";
    var pregunta = confirm("¿Qué deseas elegir?");
    if (pregunta == true) {
        texto = "¡Has presionado OK!";
    } else {
        texto = "¡Has presionado Cancelar!";
    }
    row.innerHTML = texto;
}
</script>

And to get the id just enough with row.id

    
answered by 16.11.2016 в 13:16
0

You have put:

document.getElementById("id").innerHTML = texto;

When you really need to choose the id you want to affect:

document.getElementById("ID_AL_QUE_AFECTAR").innerHTML = texto;
    
answered by 16.11.2016 в 15:25
0

I'll give you an alternative in which you avoid putting JavaScript inline (directly in HTML tags), which is recommended because it's important to try to separate the interface from the functionality, and because if you have the inline events then you can not associate more than one.

The idea would then be to remove the onclick from the a tags and add the event handlers with addEventListener in the JavaScript. Another advantage of this method is that you no longer have to worry about passing IDs, you can use this that in that context will be the element that has been pressed (the a ).

The code would look like this:

// lees todos los enlaces que hay dentro de las celdas con id comenzando por "estado"
var enlaces = document.querySelectorAll("td[id^=estado] a");

// para cada uno de esos enlaces
for (let x = 0; x < enlaces.length; x++) {
  
  // añade un controlador del evento click
  enlaces[x].addEventListener("click", function() {
    
    // que realiza todo tu código
    var texto = "";
    var pregunta = confirm("¿Qué deseas elegir?");
    if (pregunta == true) {
      texto = "OK";
    } else {
      texto = "Cancelar";
    }
    
    // puedes usar this para hacer referencia al elemento pulsado
    this.innerHTML = texto;
  });
}
<table>
  <tr>
    <td width="08%" id="estado0">
      <center>
        <a href='#'>
          <img src="/imagenes/1.gif" />
        </a>
      </center>
    </td>
    <td width="08%" id="estado1">
      <center>
        <a href='#'>
          <img src="/imagenes/1.gif" />
        </a>
      </center>
    </td>
    <td width="08%" id="estado2">
      <center>
        <a href='#'>
          <img src="/imagenes/1.gif" />
        </a>
      </center>
    </td>
    <td width="08%" id="estado3">
      <center>
        <a href='#'>
          <img src="/imagenes/1.gif" />
        </a>
      </center>
    </td>
  </tr>
</table>
    
answered by 16.11.2016 в 15:30