javascript - 根据复选框的状态更新十六进制字中的位值,反之亦然

标签 javascript

我有一个文本框和一组应链接在一起的复选框。文本框中的值是基于复选框状态的等效十六进制值。

在 HTML 端,我有 ID 为 oc0 到 oc19 的复选框,每个复选框都应控制十六进制值的位 0 到位 19,反之亦然。
我所做的,我可以根据复选框 ID 号(0-19)获取位权重,并且我可以了解哪个复选框应该控制哪个位。但我不知道如何在 JS 函数中实现这个功能。这是我到目前为止所拥有的。

这是复选框 block

<span style="float:left;text-align:left;min-width:70px" for="checkboxSbiCK-oc0">
    <input type="checkbox" id="checkboxSbiCK-oc0" data-weight="oc0" class="mdl-checkbox__input checkboxSbiCK">
    <label>CK_0</label>
</span>
<span style="float:left;text-align:left;min-width:70px" for="checkboxSbiCK-oc1">
    <input type="checkbox" id="checkboxSbiCK-oc1" data-weight="oc1" class="mdl-checkbox__input checkboxSbiCK">
    <label>CK_1</label>
</span>
<span style="float:left;text-align:left;min-width:70px" for="checkboxSbiCK-oc2">
    <input type="checkbox" id="checkboxSbiCK-oc2" data-weight="oc2" class="mdl-checkbox__input checkboxSbiCK">
    <label>CK_2</label>
</span>

..........and same structure till oc19

这是我的文本框:

<label>SBI 20 bit OE Word:</label>
<input type="text" value="0x00000" id="textboxSbiCK" class="guiTextBox" style="width:75px;margin-left: 10px">

这是复选框更改事件的 JS 函数


// ---------------------------------------------------------------- 
    // checkbox change event    
    // ----------------------------------------------------------------
    document.querySelectorAll(".checkboxSbiCK").forEach(function(checkboxSbiCK)
    {   
        checkboxSbiCK.addEventListener("change", function(e)            
        {

            var textboxSbiCK = document.getElementById("textboxSbiCK").value;
            var checkbox = document.getElementById(this.id);
            var outputId = checkbox.id.match((/(checkboxSbiCK-)(.*)$/))[2];
            var outputBitNum = outputId.substring(2);//remove oc from the name and just get the output number
            var outputBitWeight= 2**outputBitNum; // calculate the weight of the bit based on output number. 
            //...... to be completed

        });
    });

我希望文本框和复选框的值彼此相关,因此通过更改文本框值、复选框的状态更改或通过更改每个复选框状态,十六进制值都会更新。

已检查 = 1 未选中= 0

最佳答案

这里是一个基于十六进制转换器的用例的实现 answer 。请参阅内部评论以获取指南:

//hex prefix
var hex_prefix = "0x";

//add initial checkboxes
var checkbox_count = 19;
var checkboxes = "";
for (var count = 0; count < checkbox_count; count++)
{
 checkboxes += '<span class="col-3" for="checkboxSbiCK-oc'+count+'"> <input type="checkbox" id="checkboxSbiCK-oc'+count+'" data-weight="oc'+count+'" class="mdl-checkbox__input checkboxSbiCK" onchange="convertBitToHex()"> <label>CK_'+count+'</label></span>';
} 
 //append to parent
   document.getElementById("checkboxes").innerHTML += checkboxes;
//alert(checkboxes);

function convertBitToHex(){
var bit_value = "";

//retrieve all checkboxes and loop through states
var checkboxes = document.querySelectorAll('.checkboxSbiCK');
for (var checkbox = checkboxes.length-1; checkbox >= 0; checkbox--)
{
//concat checkbox states to form bits
  bit_value +=  (checkboxes[checkbox].checked - 0); //returns 1 or 0 instead of true/false
}
var hex = tools.convertBinaryToHexadecimal(bit_value);
//set value to textbox
document.getElementById("textboxSbiCK").value = hex_prefix + hex;
//alert(tools.convertBinaryToHexadecimal(hex_prefix + hex));
//alert(bit_value);
dummyBlink();
}

function convertHexToBit(){
var hex = document.getElementById("textboxSbiCK").value;

//validate hex input
if(!hex.length > 2)return;
if(hex.substring(0,2) != hex_prefix)return;

//get converted hex
var bits = tools.convertHexadecimalToBinary(hex); 

//validate bits
if(!bits)return;

//remove padding and badformats from bits
bits = bits.replace("00000NaN","");


//retrieve all checkboxes and apply new states
var checkboxes = document.querySelectorAll('.checkboxSbiCK');
for (var index = checkboxes.length-1; index >= 0; index--)
{
//set checkbox states from bits
  checkboxes[index].checked = bits[checkboxes.length-index-1] - 0; //converts to int 
}
//alert(bits);
dummyBlink();
}


function dummyBlink(){
//A UI method that changes background color to indicate an action was triggered
document.getElementById("checkboxes").style.backgroundColor = "#eeeeff";

setTimeout(function(){
document.getElementById("checkboxes").style.backgroundColor = "#ffffff";
}, 500);
}

//Helper Object by user2503552
//From: https://stackoverflow.com/questions/17204912/javascript-need-functions-to-convert-a-string-containing-binary-to-hex-then-co
var tools = {
    /**
     * Converts binary code to hexadecimal string
     * @param {string} binaryString A string containing binary numbers e.g. '01001101'
     * @return {string} A string containing the hexadecimal numbers
     */
    convertBinaryToHexadecimal: function(binaryString)
    {
        var output = '';

        // For every 4 bits in the binary string
        for (var i=0; i < binaryString.length; i+=4)
        {
            // Grab a chunk of 4 bits
            var bytes = binaryString.substr(i, 4);

            // Convert to decimal then hexadecimal
            var decimal = parseInt(bytes, 2);
            var hex = decimal.toString(16);

            // Uppercase all the letters and append to output
            output += hex.toUpperCase();
        }

        return output;      
    },

    /**
     * Converts hexadecimal code to binary code
     * @param {string} A string containing single digit hexadecimal numbers
     * @return {string} A string containing binary numbers
     */
    convertHexadecimalToBinary: function(hexString)
    {
        var output = '';

        // For each hexadecimal character
        for (var i=0; i < hexString.length; i++)
        {
            // Convert to decimal
            var decimal = parseInt(hexString.charAt(i), 16);

            // Convert to binary and add 0s onto the left as necessary to make up to 4 bits
            var binary = this.leftPadding(decimal.toString(2), '0', 4);

            // Append to string         
            output += binary;
        }

        return output;
    },

    /**
     * Left pad a string with a certain character to a total number of characters
     * @param {string} inputString The string to be padded
     * @param {string} padCharacter The character that the string should be padded with
     * @param {string} totalCharacters The length of string that's required
     * @returns {string} A string with characters appended to the front of it
     */
    leftPadding: function(inputString, padCharacter, totalCharacters)
    {
        // If the string is already the right length, just return it
        if (!inputString || !padCharacter || inputString.length >= totalCharacters)
        {
            return inputString;
        }

        // Work out how many extra characters we need to add to the string
        var charsToAdd = (totalCharacters - inputString.length)/padCharacter.length;

        // Add padding onto the string
        for (var i = 0; i < charsToAdd; i++)
        {
            inputString = padCharacter + inputString;
        }

        return inputString;
    }
};
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class='row' id='checkboxes'> </div>

<label>SBI 20 bit OE Word:</label>
<input type="text" value="0x00000" id="textboxSbiCK" class="guiTextBox" onblur="convertHexToBit()" style="width:75px;margin-left: 10px"/> <button onclick="">Validate Input</button>

关于javascript - 根据复选框的状态更新十六进制字中的位值,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57577622/

相关文章:

javascript - 为什么 .attr() 对 $(this) 起作用,但对 every() 的参数不起作用?

javascript Blob 对象未定义

javascript - 从组件内的表单中删除值

javascript - 在javascript中使用map为内部数组添加值

javascript - ES6 + BabelJS + Webpack 导出类

javascript - 未捕获的类型错误 : object is not a function (calling onchange function)

javascript - 如何在页面加载后使用 JS 执行繁重的 PHP 函数以加快速度?

javascript - 日期时间选择器上的更改功能无法正常工作

javascript - 类型错误 : Cannot read property 'insertData' of undefined

javascript - 使用 JavaScript 物理库与 A 型框架对象发生碰撞