Home > OS >  Unable to change button text on click toggle JQUERY
Unable to change button text on click toggle JQUERY

Time:11-07

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" >
  <img src="https://via.placeholder.com/50" >
  <div >
    <h2 >Recursividad y contingencia</h2>

    <p >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" >
        Reservar
    </button>
  </div>
</div>

CodePudding user response:

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" >Reservar</button>

CodePudding user response:

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" >
  <div >
    <button id="rec" >
        Reservar
    </button>
  </div>
</div>

CodePudding user response:

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" >
  <img src="https://via.placeholder.com/50" >
  <div >
    <h2 >Recursividad y contingencia</h2>

    <p >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" ></button>
  </div>
</div>

  • Related