简体   繁体   中英

Next and previous buttons javascript

I want to get alert when the user clicked next or previous button and its already at the first or last element of the array

function myFunction() {
    document.getElementById("f").value = person[arr].fname;
    document.getElementById("l").value = person[arr].lname;
    document.getElementById("a").value = person[arr].age;
    document.getElementById("s").value = person[arr].salary;
}

document.getElementById("prevbtn").addEventListener("click", myFunctionPrev);
document.getElementById("nxtbtn").addEventListener("click", myFunctionNext);


function myFunctionPrev() {
    if (arr > 0) {
        arr -= 1;
    }

    myFunction();
}



function myFunctionNext() {
    if (arr < 3) {
        arr += 1;
    }

    myFunction();
}

by "get alert" I don't know exactly your expectation but a nice way to alert the user that can't cross the limits it is disabling the button.

Here an example.

 var person = [{ fname: "1", lname: "1", age: "1", salary: "1" }, { fname: "2", lname: "2", age: "2", salary: "2" }, { fname: "3", lname: "3", age: "3", salary: "3" }]; var index = 0; document.getElementById("prevbtn").addEventListener("click", myFunctionPrev); document.getElementById("nxtbtn").addEventListener("click", myFunctionNext); myFunction(); function myFunction() { document.getElementById("f").innerHTML = person[index].fname; document.getElementById("l").innerHTML = person[index].lname; document.getElementById("a").innerHTML = person[index].age; document.getElementById("s").innerHTML = person[index].salary; checkButtonStatus(); } function checkButtonStatus() { document.getElementById("prevbtn").disabled = index <= 0; document.getElementById("nxtbtn").disabled = index >= person.length - 1; } function myFunctionPrev() { if (index > 0) { index -= 1; } myFunction(); } function myFunctionNext() { if (index < person.length) { index += 1; } myFunction(); }
 <div> <div> <div id="f"></div> <div id="l"></div> <div id="a"></div> <div id="s"></div> </div> <div> <button id="prevbtn">Prev</button> <button id="nxtbtn">Next</button> </div> </div>

If you wish you can replace the enable/disable function with the alert that you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM