skip to Main Content

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


  1. 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:

    <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>
    
    Login or Signup to reply.
  2. 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:

    • Define constant values to reduce repeated selector processing.
    • Chain methods for simpler code.
    • Use a class or other abstract method to track state rather than text value. This is more robust as you can then change button text without breaking the script.
    • Button text really shouldn’t be used for feedback. It’s nonsensical to use a button, which implies that it’s available for an action, to report what’s already been done. Instead, consider removing the button and showing a simple message.
    $(document).ready(function() {
      const btnEl = $("#rec");
      const sixEl = $("#6")
    
      btnEl.click(function() {
        const btnText = btnEl.text().trim(); // remove leading and trailing whitespace
    
        if (btnText === 'RESERVADO') {
          btnEl.text("Reservar").css('color', 'blue');
          sixEl.appendTo($("#disponibles"));
        } else if (btnText === 'Reservar') {
          btnEl.text("RESERVADO").css('color', 'red');
          sixEl.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">
      <div class="p-6 bg-gray-50">
        <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>
    Login or Signup to reply.
  3. you can simly use a classList.toggle()

    and some CSS ( with ::before )

    $(document).ready(function()
      {
      $("#rec").click(function()
        {
        if (this.classList.toggle('RESERVADO') )
          $("#6").appendTo($("#reservados"));
        else
          $("#6").appendTo($("#disponibles"));
        });
      });
    #rec::before {
      color   : blue;
      content : 'Reservar';
      }
    #rec.RESERVADO::before {
      color   : red;
      content : 'RESERVADO';
      }
    <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"></button>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search