Home > Blockchain >  How to navigation on buttons using arrow keys instead of tab
How to navigation on buttons using arrow keys instead of tab

Time:08-24

I have a bootstrpa modal that has a table on it. I want to navigate on the buttons using arrow keys instead of tabs...

I have tried it using autofocus but is not working.

enter image description here

Javascript Code

for (let i = 0; i < res.data.data.length; i  ) {
    table__body.innerHTML  = `<tr>
        <td id="english_name"> <p> ${res.data.data[i].english_name} </p></td>
        <td id="mrp_price"> <p> ${res.data.data[i].mrp_price} </p></td>
        <td id="sale_price"> <p> ${res.data.data[i].sale_price} </p></td>
        <td id="barcode"> <p> ${res.data.data[i].barcode} </p></td>
        <td id="tax_per" > <p> ${res.data.data[i].tax_per} </p></td>
        <td id="product_tax_id" > <p> ${res.data.data[i].product_tax_id} </p></td>
        <td id="product_unit_id" > <p> unit ${res.data.data[i].product_unit_id} </p></td>
        <td id="product_id"  <p>  ${res.data.data[i].product_id} </p></td>
        <td id="purchase_price"  <p>  ${res.data.data[i].purchase_price} </p></td>
        <td id="production_price"  <p>  ${res.data.data[i].production_price} </p></td>
        <td id="franchise_price"  <p>  ${res.data.data[i].franchise_price} </p></td>
        <input type="hidden" value="${res.data.data[i].point_value}" id="point_value" />
        <td><button type="button" onclick="productWithSameBarcode(this)"  id="focus_on_add_button${i   1}" >Add</button></td>
        </tr>`;
}

document.getElementById("call_modal").click();
let btn = document.getElementById("focus_on_add_button1")
console.log(btn.setAttribute('autofocus'))
console.log("focus set")

CodePudding user response:

document.onkeydown = (e) => {
    if (e.keyCode === 38) {
        console.log('up arrow pressed')
    } else if (e.keyCode === 40) {
        console.log('down arrow pressed')
    } else if (e.keyCode === 37) {
        console.log('left arrow pressed')
    } else if (e.keyCode === 39) {
        console.log('right arrow pressed')
    }
}

CodePudding user response:

let count = 0;
let buttons = document.getElementsByClassName("focus_on_add_button")
window.addEventListener('keydown', (e) => {
    const dec = () => {
        count == 0 ? count = 0 : count--
        buttons[count].focus()
    }
    const inc = () => {
        count  
        buttons[count].focus()
    }
    if (e.key == "ArrowUp") {
        dec()
    }
    else if (e.key == "ArrowDown") {
        inc()
    }
})
  • Related