2

I have a textbox and set of checkboxes that should link together. value in textbox is the equivalent hex value based on checkbox status.

in HTML side I have checkboxes with ID oc0 to oc19 which each one should control bit 0 to bit 19 of the hex value and vice versa.
what I did, I can get the bit weight based on checkbox ID number (0-19) and I can understand which checkbox should control which bit. But I donnow how to implement this in JS function . here is what I have so far.

this is checkboxes 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

and this is the textbox that I have:

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

and this is the JS function on event of checkbox change


// ---------------------------------------------------------------- 
    // 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

        });
    });

I want the value of text box and checkboxes relate to eachother so by changing textbox value, checkboxes' status change, or by changing each checkbox status the hex value gets updated.

checked = 1 unchecked = 0

majed
  • 467
  • 4
  • 7

1 Answers1

2

Here is an implementation for your use-case based on the Hex converter from this answer. See inner comments for guidelines:

//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>
majed
  • 467
  • 4
  • 7
Giddy Naya
  • 4,237
  • 2
  • 17
  • 30
  • 1
    Thanks a lot. it was a minor bug in your convert routine that was not connecting correct checkboxes to the right bit. I fixed that and edited your function . now works like a charm . Thanks a lot for your help. – majed Aug 21 '19 at 20:56
  • 1
    You welcome. And don't forget to `Mark reply as answered` if it answered your question. – Giddy Naya Aug 22 '19 at 00:45