Reputation: 2725
Suppose I have button like this:
<button>÷</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 "÷":
alert("OK");
break;
}
});
}
);
</script>
</head>
<body>
<button>÷</button>
</body>
</html>
But none of those alerts appear on button click.console.log() shows:
"÷"
My browser - firefox 39.0.
Upvotes: 1
Views: 872
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>÷</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">÷</button>
Upvotes: 1