I’m new to JQUERY and I want to change the button text when user clicks on it from "Reservar" to "RESERVADO" and from "RESERVADO" to "Reservar" again, and so on (toggle).
But I can only change the button text once, and then it doesn’t change anymore. Any help is appreciated
$(document).ready(function() {
$("#rec").click(function() {
if ($("#rec").text() === 'RESERVADO') {
$("#rec").html("Reservar")
$("#rec").css('color', 'blue');
$("#6").appendTo($("#disponibles"));
} else if ($("#rec").text() === 'Reservar') {
$("#rec").html("RESERVADO")
$("#rec").css('color', 'red');
$("#6").appendTo($("#reservados"));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="6" class="m-2 bg-white rounded-lg shadow-xl lg:flex lg:max-w-lg">
<img src="https://via.placeholder.com/50" class="w-1/1 lg:w-1/2 rounded-l-2xl">
<div class="p-6 bg-gray-50">
<h2 class="mb-2 text-2xl font-bold text-gray-900">Recursividad y contingencia</h2>
<p class="text-gray-600">Yuk Hui se aboca a esa tarea mediante una reconstrucción histórico-crítica del concepto de lo orgánico en filosofía, que aparece en la Crítica de la facultad de juzgar de Kant y plantea una ruptura respecto a la visión mecanicista del mundo para fundar
un nuevo umbral del pensamiento.</p>
<button id="rec" class="bg-transparent mt-5 hover:bg-blue-500 text-blue-700 font-semibold hover:text-white py-2 px-4 border border-blue-500 hover:border-transparent rounded">
Reservar
</button>
</div>
</div>
3
Answers
The problem is the way you wrote your buttons tags there are spaces character before and after "Reservar" so just edit your button as following:
The structure of your button markup results in whitespace in its text value, which causes the comparison to fail. Trim that away and your script works.
Other tips:
you can simly use a classList.toggle()
and some CSS ( with
::before
)