Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

javascript - How to assign different object values to different buttons while using the same function?

Good morning!

I am obviously pretty new to the whole programming thing, so I am working on a basic PoS application for a restaurant. I am trying to figure out how I can assign different values to the different buttons while using the same button click function. I know I could write out a new function for each button with the correct object properties pushed, but there has to be a better way. I currently just have it set for the top right port nachos button to push the information into the tab section (though right now I am drawing a blank as to why it is the only one to do this instead of all the foodbuttons pushing the pork nachos info). Any help would be greatly appreciated. Thanks again!

<body>
    <header>
        <h1>Point of Sale</h1>
    </header>
    <section id="foodOptionsSection">
        <h3>Food Options</h3>
        <button type="button" class= "foodButtons buttons" id="porkNachosFood">Pulled Pork Nachoes</button>
        <button type="button" class= "foodButtons buttons" id="wingsFood">6 Wings</button>
        <button type="button" class= "foodButtons buttons" id="totsFood">Tater Tots</button>
        <button type="button" class= "foodButtons buttons" id="hamburgerFood">Hamburger</button>
        <button type="button" class= "foodButtons buttons" id="cbqbbqFood">CBWBBQ</button>
        <button type="button" class= "foodButtons buttons" id="ppgcFood">PPGC</button>
        <button type="button" class= "foodButtons buttons" id="tacosFood">Tacos</button>
        <button type="button" class= "foodButtons buttons" id="friesFood">Fries</button>
        <button type="button" class= "foodButtons buttons" id="porkRindsFood">Pork Rinds</button>


    </section>
    <section id="tabList">
        <h3>Current Tab</h3>
        <div class="tabNameList tab">

        </div>
        <div class="tabAmountList tab">

        </div>

    </section>
    <script src="script.js"></script>
</body>
//Vars

const food = [
    {
        name: "Pulled Pork Nachos",
        price: 10.00
    },
    {
        name: "6 Wings",
        price: 5.00
    },
    {
        name: "Pork Rinds",
        price: 4.00
    }
];
const drinks = [
    {
        name: "Well Vodka",
        price: 5.00
    },
    {
        name: "Well Whiskey",
        price: 5.00
    }
];
const merch = [
    {
        name: "Well Vodka",
        price: 5.00
    },
    {
        name: "T Shirt",
        price: 20.00
    }
];

const tabNameSection = document.querySelector('.tabNameList');
const tabAmountSection = document.querySelector('.tabAmountList');
const btns = document.querySelector('.foodButtons');


// const wings = document.querySelector('#wingsFood');
// wings.assign('wings', 6.00)
// console.log(wings);

//Functions
function addTab(event) {
    
    //Name Div
    const tabNames = document.createElement('div');
    tabNames.classList.add('tabNameList');

    //Amt Div
    const tabAmt = document.createElement('div');
    tabAmt.classList.add('tabAmtList');

    //Create LI Tab Names
    const tabNameList = document.createElement('li');
    tabNameList.innerText = food[0].name;    
    tabNameList.classList.add('tabScreenNames');
    tabNames.appendChild(tabNameList);

    //Create LI Tab Amounts
    const tabAmountList = document.createElement('li');
    tabAmountList.innerText = food[0].price;
    tabAmountList.classList.add('tabScreenAmount');
    tabAmt.appendChild(tabAmountList);

     //Check trash button
    const trashButton = document.createElement("button")
    trashButton.innerHTML = '<i class="fas fa-trash"></i>';
    trashButton.classList.add("trash-btn");

    //append to LIs
    tabNameSection.appendChild(tabNames);
    tabAmountSection.appendChild(tabAmt);
    tabAmountSection.appendChild(trashButton);
};


//Events
btns.addEventListener('click', addTab);
question from:https://stackoverflow.com/questions/65641890/how-to-assign-different-object-values-to-different-buttons-while-using-the-same

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basically, I use the innerText of each html element as keys in the object

On a side note: only Pulled Pork Nachos, 6 Wings and Pork Rinds have any relation in the food variable so it will work better when you use your full variable and not JUST these 3 indexes(for an item that is non-existent in the food variable, an alert is shown)

NOW as to what I fully did:

FIRSTLY, I made 3 variables outside the function; blankElemState which is the tab element's innerHTML when holding NOTHING, amount as TOTAL tab amount and purchases for holding the object equivalent of each purchase(because of reference logic, one can search through the food, drink and merch arrays and when a value EQUALS a value in purchases, that's the exact item of purchase). For example of the reference logic, purchases[8] might EQUAL food[2]

SECONDLY, I made a variable i that holds the place in the food array of the requested item(for drinks you can change that part to drinks.forEach instead of food.forEach and so forth).

NEXT, if there is nothing in the array that refers to the requested item(by user), I warn that there is nothing available for the order(which naturally should not happen).

THEN, if tabAmountSection already has elements appended to it(not equal to blankElemState), I clear tabAmountSection(by making its innerHTML back to blankElemState) so that there aren't multiple "final" purchase values and remove buttons

//Vars
//also, only "Pulled Pork Nachos", "6 Wings" and "Pork Rinds" have any relation in the food variable so it will work better when you use your full variable and not JUST these 3 indexes
const food = [
    {
        name: "Pulled Pork Nachos",
        price: 10.00
    },
    {
        name: "6 Wings",
        price: 5.00
    },
    {
        name: "Pork Rinds",
        price: 4.00
    }
];
const drinks = [
    {
        name: "Well Vodka",
        price: 5.00
    },
    {
        name: "Well Whiskey",
        price: 5.00
    }
];
const merch = [
    {
        name: "Well Vodka",
        price: 5.00
    },
    {
        name: "T Shirt",
        price: 20.00
    }
];

const tabNameSection = document.querySelector('.tabNameList');
const tabAmountSection = document.querySelector('.tabAmountList');
const blankElemState=tabAmountSection.innerHTML;
const btns = document.querySelectorAll('.foodButtons');
let amount=0; let purchases=[];


// const wings = document.querySelector('#wingsFood');
// wings.assign('wings', 6.00)
// console.log(wings);

//Functions
function addTab(event) {
    //make index for getting data
    var i=-1; var elem=this;
    food.forEach(function (a,c){if(elem.innerText==a.name){i=c}});
    if(i==-1){return alert("There is nothing in the respective options array that links to the requested item.. if you are a client playing around, kindly cease it")}
    purchases.push(food[i]); //if not returned by now, the item is valid and now I'm taking record
    //all you have to do for drinks or merch is change which array you're doing this function to(like food, drink, or merch)
    //please note that document.querySelector ONLY selects ONE element, for your purpose, please use document.querySelectAll
    //you can easily just have it in one array for simplicity to add it to ALL buttons, but since you're not doing that, change which variable is being forEach-ed for the 3 different sections
    //btw i would console.warn when there's nothing in the array linked to the requested item(as for what you gave us, a lot of the items have no instance in the array)
    //finally, there was a logical error occuring when it first worked.. with each click, NEW elements of price and trashbuttons were created.. I understand the names adding up as one person can buy many things, but I made it that the price and trashbuttons dont make new ones each time
    
    //example of reference logic to see if an index of purchase is in an array
    function purchaseIsInArray(indexOfPurchase, arrayInQuestion){
      return arrayInQuestion.includes(purchases[indexOfPurchase])
    }
    
    //Name Div
    const tabNames = document.createElement('div');
    tabNames.classList.add('tabNameList');

    //Amt Div
    const tabAmt = document.createElement('div');
    tabAmt.classList.add('tabAmtList');

    //Create LI Tab Names
    const tabNameList = document.createElement('li');
    tabNameList.innerText = food[i].name;    
    tabNameList.classList.add('tabScreenNames');
    tabNames.appendChild(tabNameList);

    //Create LI Tab Amounts
    amount+=food[i].price;
    const tabAmountList = document.createElement('li');
    tabAmountList.innerText = amount;
    tabAmountList.classList.add('tabScreenAmount');
    tabAmt.appendChild(tabAmountList);

    //Check trash button
    function resetEverything(ev){
      tabAmountSection.innerHTML=blankElemState;
      tabNameSection.innerHTML=blankElemState;
      amount=0; purchases=[];
    } 
    const trashButton = document.createElement("button")
    trashButton.innerHTML = '<i class="fas fa-trash"></i>';
    trashButton.classList.add("trash-btn");
    trashButton.addEventListener('click', resetEverything);

    //append to LIs
    tabNameSection.appendChild(tabNames);
    if(tabAmountSection.innerHTML!=blankElemState){
      tabAmountSection.innerHTML=blankElemState;
    }
    tabAmountSection.appendChild(tabAmt);
    tabAmountSection.appendChild(trashButton);
};


//Events
btns.forEach(a=>a.addEventListener('click', addTab));
<body>
        <header>
            <h1>Point of Sale</h1>
        </header>
        <section id="foodOptionsSection">
            <h3>Food Options</h3>
            <button type="button" class= "foodButtons buttons" id="porkNachosFood">Pulled Pork Nachos</button>
            <button type="button" class= "foodButtons buttons" id="wingsFood">6 Wings</button>
            <button type="button" class= "foodButtons buttons" id="totsFood">Tater Tots</button>
            <button type="button" class= "foodButtons buttons" id="hamburgerFood">Hamburger</button>
            <button type="button" class= "foodButtons buttons" id="cbqbbqFood">CBWBBQ</button>
            <button type="button" class= "foodButtons buttons" id="ppgcFood">PPGC</button>
            <button type="button" class= "foodButtons buttons" id="tacosFood">Tacos</button>
            <button type="button" class= "foodButtons buttons" id="friesFood">Fries</button>
            <button type="button" class= "foodButtons buttons" id="porkRindsFood">Pork Rinds</button>
    
    
        </section>
        <section id="tabList">
            <h3>Current Tab</h3>
            <div class="tabNameList tab">
    
            </div>
            <div class="tabAmountList tab">
    
            </div>
    
        </section>
        <script src="script.js"></script>
    </body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...