0

I want to change <a> color and <span> text every time when I press the button. I need to put something into data == '0'

<div class="submitset uncheck">
  <a class="btncolor--blue bt_register" href="<?php echo '/advertiser/campaign/' ?>">
    <span class="stop_offer">Start</span>
  </a>
</div>
jQuery(document).ready(function($) {
  //案件を登録する
  jQuery('.bt_register').click(function() {
    var link = jQuery(this);
    var params = link.attr('href').split('/');

    jQuery.get(link.attr('href'), function(data) {
      console.log($('#sidebar div:eq(14)').attr('class'));
      if (data == '0') {
        link.find('span').text('Start');
        link.attr('class', 'btncolor--red bt_register');
      } else {
        link.find('span').text('Stop');
        link.attr('class', 'btncolor--blue bt_register');
      }
    });
    return false;
  });
});
Andrew Evt
  • 3,613
  • 1
  • 19
  • 35

2 Answers2

2

If you haven't found solution yet, I show one of the many possible solutions:

jQuery(document).ready(function($) {
 let data = 1;
  jQuery('.bt_register').click(function() {
    let link = jQuery(this);
  
      if (data % 2 == 0) {
        link.find('span').text('Start');
        link.removeClass("btncolor--blue")
        link.addClass("btncolor--red");
        
      } else {
        link.find('span').text('Stop');
        link.removeClass("btncolor--red")
        link.addClass("btncolor--blue");
      }
      data++;
      return false;
  });
});
.bt_register {
  color: white;
  padding: 20px;
}
.btncolor--blue{
  background-color: blue;
}
.btncolor--red {
  background-color: red;

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="submitset uncheck">
  <a class="btncolor--blue bt_register" href="#">
    <span class="stop_offer">Start</span>
  </a>
</div>

Or shorter solution:

jQuery(document).ready(function($) {
  let data = 1;
  jQuery('.bt_register').click(function() {
    let link = jQuery(this);

    if (data % 2 == 0) {
      link.find('span').text('Start');
    }  else {
      link.find('span').text('Stop');
    }
    link.toggleClass("btncolor--red")
    data++;
    return false;
 });
});
Mat.Now
  • 1,715
  • 3
  • 16
  • 31
  • Thank you for your answer. Its a good solution. But a problem, that there lists with that button. Some of them is "Start" buttons, some of them "Stop". So i want to change color and text when i click it. I dont know how to recognize a class. Im am a back programmer, very bad in JS and CSS ... – Marzhan Bulkayeva Jan 27 '20 at 01:51
1

You can try this out:

document.onready(() => {
    const $ = jQuery;
    $(".bt_register")
      .click(() =>
        $.get($("href"))
            .then(data => {
               $("span").text( data === 0 ? "Start" : "Stop" )
               $("#sidebar").class("btncolor--" + ( data === 0 ? "red" : "blue" ) + " bt_register")
            })
      )
})
Felipe Malara
  • 1,796
  • 1
  • 7
  • 13