Change <span> text with jQuery+variable

Asked

Viewed 1,061 times

1

I’m trying to change the text displayed by a span within a modal:

<div class="modal-body">Deseja realmente excluir?<span id="nomecliente"></span></div>

I’m using onclick to pass the value to use in jQuery.

<td style="text-align:center" onclick="Excluir(@item.nome)"><button class="btn btn-danger btn-circle btn-sm" data-toggle="modal" data-target="#excluirmodal"></button></td>

And my JS/jQuery function is this:

function Excluir(nome) {
    $(document).ready(function () {
        $('#nomecliente').html(nome);
    })
}

I’ve tried to change the .html for .text and it didn’t work, and the weird thing is if I try to pass a number it works, displays in modal normally, but string I’m not getting.

1 answer

2


You need to delimit the string in the onclick with single quotes, in this case:

onclick="Excluir('@item.nome')"

Otherwise it will fail, because it would be a string without delimiter, like:

onclick="Excluir(fulano de tal)"

Without the delimiter, the string will be interpreted as a variable or code to be interpreted that does not exist.

In the case of the number works because number does not necessarily need a delimiter:

Could be onclick="Excluir(123)" or onclick="Excluir('123')".

Something else:

The $(document).ready... used within the function has no effect or meaning. The correct would be only:

function Excluir(nome) {
    $('#nomecliente').html(nome);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.