kurumkan
kurumkan

Reputation: 2725

How to use switch with special characters

Suppose I have button like this:

<button>&divide;</button>

I want to use switch operator with string variable.

<!DOCTYPE html> 
<html lang="en">
<head>      
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>     
    <script type="text/javascript">

$(document).ready(function()
{  
  $("button").click(function(){
      var value=$(this).text();
      console.log(value);
    switch(value){

      case "÷":
         alert("OK");
         break;
      case "&divide;":
         alert("OK");
         break;
    }
  });   

}
);

    </script>   
</head>
<body>
<button>&divide;</button>
</body>
</html>

But none of those alerts appear on button click.console.log() shows:

"÷"

My browser - firefox 39.0.

Upvotes: 1

Views: 872

Answers (1)

Hitmands
Hitmands

Reputation: 14189

Consider that Html Node Text isn't always a safe source of truth... A good choise could be putting some attribute that gives you the information that you need and use views only for data presentation...

function CheckBtnTextCtrl($) {
  let 
    $btns = $('button')
  ;
  
  function smartTextSanitization(text) {
    let decoder = document.createElement('textarea');
    decoder.innerHTML = text;
    
    return decoder.value;
  }
  
  function onBtnClick(event) {
    let 
      $btn = $(this),
      $btnText = $btn.text(),
      text = smartTextSanitization($btnText)
    ;
    
    switch(text) {
      case "÷":      
        console.log('it is division');
        break;
    }
  }
  
  $btns.click(onBtnClick);
}

jQuery(document).ready(CheckBtnTextCtrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>&divide;</button>


Good way (in my opinion):

function CheckBtnCtrl($) {
  const ACTION_TYPES = {
    "SUM": 1,
    "DIVIDE": 2
  };
  
  let $btns = $('button');
  
  function onBtnClick(event) {
    let 
      $btn = $(this),
      action = $btn.data('actiontype')
    ;
    
    switch(action) {
      case ACTION_TYPES.SUM:
        console.log('ok, we need to sum values');
        break;
        
      case ACTION_TYPES.DIVIDE:
        console.log('ok, we need to divide values');
        break;
    }
  }
  
  $btns.click(onBtnClick);
}
jQuery(document).ready(CheckBtnCtrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-actiontype="2">&divide;</button>

Upvotes: 1

Related Questions