javascript - jQuery remove highlight only if already selected -


this should basic fix. im wanting remove selected class when clicking on highlighted button. 1 button highlighted @ given time.

http://jsfiddle.net/7wy7sjm5/1/

the reason have remove class of them execute first because when 1 clicked, 1 highlighted, , not have previous clicked ones still highlighted. , when clicking on same button highlighted, remove highlight. hope makes sense.

$(".details-btn").on("click", function(){ var $this = $(this); //add/remove selected button $(".details-btn").removeclass("selected"); $this.toggleclass("selected");}); 

possibly using .each() cycle through each instance of button , if has class remove? ive tried different approaches , none working way want.

in case can make use of .not().

basically, remove .selected .details-btn except current 1 not(this). then, use toggle()

$(".details-btn").on("click", function() {   var $this = $(this);   $(".details-btn").not(this).removeclass("selected");   $this.toggleclass("selected"); }); 

$(".details-btn").on("click", function() {    var $this = $(this);    $(".details-btn").not(this).removeclass("selected");    $this.toggleclass("selected");  });
* {    margin: 0;    padding: 0;    font-size: 1.1em;  }  table {    border: 1px solid;    text-align: center;  }  thead {    background-color: #ddd;  }  th {    border-bottom: 1px solid;  }  td {    width: 140px;  }  .details-btn {    background-color: #dad1ea;    width: 50px;    margin: 4px auto;    border: 1px solid #4b3575;    border-radius: 5px;    cursor: pointer;  }  .selected {    color: #fff;    background-color: #4b3575;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>  <table>    <thead>      <tr>        <th scope="col">data</th>        <th scope="col">view</th>      </tr>    </thead>    <tbody>      <tr>        <td>1</td>        <td>          <p class="details-btn">+</p>        </td>      </tr>      <tr>        <td>2</td>        <td>          <p class="details-btn">+</p>        </td>      </tr>      <tr>        <td>3</td>        <td>          <p class="details-btn">+</p>        </td>      </tr>      <tr>        <td>4</td>        <td>          <p class="details-btn">+</p>        </td>      </tr>      <tr>        <td>5</td>        <td>          <p class="details-btn">+</p>        </td>      </tr>      <tr>        <td>6</td>        <td>          <p class="details-btn">+</p>        </td>      </tr>    </tbody>  </table>


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -