Search code examples
javascriptjqueryjquery-ui-dialog

Trying to get html element value to a variable with Jquery


I have a confirm modal that will delete a user (from XML file), it shows the user name in the confirmation modal, but when i'm trying to get that value to a variable to pass it to php via AJAX, I can't get the value of the html element (span), so I can't pass it to php... when I alert it, its clear.

This is the Dialog HTML

<div id="myDialog">
        <h3>¿Está seguro de eliminar al usuario <b><span id="nombre_usuario_borrar"></span></b> ?</h3>
    </div>

This is the Dialog.js

$(function() {
     $("#myDialog").dialog({
         autoOpen: false,
         modal: true,
         title: "Eliminar",
         buttons: {
             'Eliminar': function() {
              var usuario_borrar = $('#nombre_usuario_borrar').val(); 
              alert(usuario_borrar);// It alerts nothing
                     $.ajax({
                         type: "POST",
                         url: 'eliminar2.php',
                         data: {
                             "usuario_borrar": usuario_borrar
                         }, 

                         error: function(result) {
                             alert("Error!!!");
                         }
                     });
                     $(this).dialog('close');
             },
             'Cancelar': function() {
                 $(this).dialog('close');
             }
         }
     });
 });
 function Editar(nombre_archivo) {
    alert(nombre_archivo);
}
function Eliminar(nombre_archivo) { // this works.
  $("#nombre_usuario_borrar").html(nombre_archivo);
    $("#myDialog").dialog("open");
}
function asignarUsuarioBorrar(nombre_archivo){

       var obj = $("#usuario_borrar");
       obj.attr("value",nombre_archivo);
    }

enter image description here

As you can see, it shows 'Benigno' (span) value right, but when I click 'Eliminar', it alerts nothing.


Solution

  • $('#nombre_usuario_borrar').val()
    

    This only works for HTML elements with a "value" option. The <span> tag does not have this option.

    Try this instead to get the text within the <span>:

    $('#nombre_usuario_borrar').text()