简体   繁体   English

根据复选框\\单选按钮调整总成本\\标价

[英]Adjusting the Total Cost\List Price based on Checkboxes\Radio Buttons

Overview: 概述:

This is my first time using javascript. 这是我第一次使用javascript。 I'm trying to use a combination of Radio Buttons and Check Boxes to adjust the "Total Cost" & "Listed Price" of an Item under a number of different conditions. 我正在尝试使用单选按钮和复选框的组合来在多种不同条件下调整项目的“总成本”和“标价”。 The JS Fiddle reflects where I currently stand. JS小提琴反映了我目前的立场。 Any suggestions, examples, comments, or form of help would be greatly appreciated as I'm completely stuck. 当我完全陷入困境时,我们将不胜感激任何建议,示例,评论或帮助形式。

JS Fiddle (the code is below as well incase you don't want to open JS Fiddle): JS Fiddle(如果您不想打开JS Fiddle,下面的代码也是如此):

http://jsfiddle.net/y2u24x3r/4/ http://jsfiddle.net/y2u24x3r/4/

The Issues\\conditions that I'm completely stuck on: 我完全坚持的问题/条件:

[Radio 1] How many attendees? [广播1]有多少与会者? (1) (2) (1)(2)

  • (2) Should double the Total Cost (unless all Four Event Boxes are checked. See Below). (2)应将总费用加倍(除非选中了所有四个事件框。请参见下文)。

[Radio 2] Are you a Member? [电台2]您是会员吗? (No) (Yes) (否)(是)

  • (No) should make the cost $26.00 per Event as seen in the Jfiddle\\code below. (否)应使每个事件的费用为$ 26.00,如下面的Jfiddle \\ code中所示。
  • (Yes) change the displayed Price per Event to $18.00 and automatically adjust the Total Cost. (是)将显示的“每事件价格”更改为$ 18.00,并自动调整“总成本”。

[Four Event Check Boxes] [四个事件复选框]

  • If all Four Event Boxes are checked, Attendees = '1', and Are you a Member = 'Yes' then override all conditions above and set price to $68.00. 如果选中了所有四个事件框,则与会者='1',并且您是否是会员='是',则将覆盖上述所有条件并将价格设置为$ 68.00。

  • If all Four Event Boxes are checked, Attendees = '2', and Are you a Member = 'Yes' then override all conditions above and set price to $136.00. 如果选中了所有四个事件框,则与会者='2',并且您是否是会员='是',则将覆盖以上所有条件并将价格设置为$ 136.00。

HTML: HTML:

 <font color="orange">How many attendees?</font> <input type="radio" name="attendees" id="attendees" value="1" checked="checked" />1 <input type="radio" name="attendees" id="attendees" value="2"/>2<br/>
 <font color="orange">Are you a Member?</font> <input type="radio" name="member" id="member" value="0" checked="checked" />No <input type="radio" name="member" id="member" value="1"/>Yes <br/><br/>
 <form name="listForm"><font color="orange">Select the Concerts you want Tickets for:</font><br/>
 <input type="checkbox" name="event" value="1" onchange="checkTotal()"/><font color="#33FF33"> <div class="price"></div></font></input> Nov. 1, 2015 -- Concert 1<br/>
 <input type="checkbox" name="event" value="1" onchange="checkTotal()"/><font color="#33FF33"> <div class="price"></div></font></input> Dec. 1, 2015 -- Concert 2<br/>
 <input type="checkbox" name="event" value="1" onchange="checkTotal()"/><font color="#33FF33"> <div class="price"></div></font></input> Jan. 1, 2015 -- Concert 3<br/>
 <input type="checkbox" name="event" value="1" onchange="checkTotal()"/><font color="#33FF33"> <div class="price"></div></font></input> Feb. 1, 2015 -- Concert 4<br/><br/>
 <font color="#33FF33">Total Cost:</font> <input value="$0.00" readonly="readonly" type="text" id="total"/>
 </form>

Javascript: 使用Javascript:

 function checkTotal() {
   var attendees = document.getElementsByName("attendees");
   var member = document.getElementsByName("member");
   var total = 0;
   var event = 0;

    if (member == 0) {
         price = 26.00;
     }           
     else if (member == 1) {
         price = 18.00; 
     }

   for (var i = 0; i < event.length; i++) {
     if (event[i].checked) {
       total += parseFloat(member.value);
         total = total * attendees;

     }
   }

        if (member == 1 && event == 4 && attendees == 1) {
         total = 68.00;
        }

        if (member == 1 && event == 4 && attendees == 2) {
         total = 136.00;
        }

     document.getElementById("total").value = "$" + total.toFixed(2);
 }

Thank you for sharing your attempts, now i can help you correct your code. 感谢您分享您的尝试,现在我可以帮助您更正您的代码。 Lets go over the issues with the code one by one: 让我们一遍一遍地研究代码的问题:

1. Invalid left side assignment 1.左侧分配无效

unlike in languages like Visual Basic, here in JavaScript you must have a double == operator in order to check conditions. 与像Visual Basic这样的语言不同,在JavaScript中,您必须具有双==运算符才能检查条件。 therefore, in the next line: 因此,在下一行中:

if (member = 1 && event = 4 && attendees = 1)

what JavaScript actually understands is: JavaScript真正理解的是:

put 1 into member , put 1 into event , and put 1 into attendees . 将1个member放入,将1个member放入event ,然后将1个成员放入attendees

in order to ask JS to check if their values equal 1, you need to use a double equation operator: 为了让JS检查其值是否等于1,您需要使用双方程运算符:

if (member == 1 && event == 4 && attendees == 1)

2. Using of system-reserved keywords 2.使用系统保留的关键字

the reason why the previous was actually an issue, is because of the word event after all, JS could simply assign 1 to all of the keywords, but instead it dropped an error into the console saying that the assignment was invalid, so why is that? 之所以说前一个实际上是一个问题,是因为毕竟单词event ,JS可以简单地将1分配给所有关键字,但是却向控制台丢了一个错误,说分配是无效的,为什么呢? ? - that's because in JavaScript there is a reserved keyword named event which represents the event parameter in the function. -这是因为在JavaScript中有一个名为event的保留关键字,它表示函数中的event参数。 so when you assign 所以当你分配

onchange="checkTotal()"

once that function is called to handle the change event, the event data will be passed into the function in a built in event var. 一旦调用了该函数来处理更改事件,事件数据将被传递到内置event var中的函数中。 therefore, you should change the names of the input elements to something else, maybe "eventCheckBox" or something. 因此,您应该将输入元素的名称更改为其他名称,例如“ eventCheckBox”或其他名称。

3. Duplicate IDs 3.重复的ID

Ids are supposed to be unique. ID应该是唯一的。 when you search something by ID in JS, it will search from the top of the page and return the first one it finds, because it assumes that this ID is unique. 当您在JS中按ID搜索内容时,它将从页面顶部搜索并返回找到的第一个,因为它假定此ID是唯一的。 also, in JavaScript you can address the elements by their IDs without getting the elements first using getElementsByID() , so when you are using var names named the same as multiple ids on the page, well, you see the problem? 另外,在JavaScript中,您可以通过其ID来寻址元素,而无需先使用getElementsByID()来获取元素,因此,当您在页面上使用与多个ID相同名称的var名称时,您看到问题了吗? make unique ids per element. 使每个元素具有唯一的ID。 if you want a common identifier for your elements, use a common class. 如果您想要元素的通用标识符,请使用通用类。

4. Getting value of a radio button 4.获得单选按钮的价值

most likely, you have tried to name your radio buttons the same and thought that when you ask for the value, you will get the value of the checked one. 最有可能的是,您尝试将单选按钮命名为相同的名称,并认为当您要求输入该值时,您将获得选中按钮的值。 well, its good thinking but unfortunately it does not work this way in JavaScript. 好吧,它的思想很好,但不幸的是,它在JavaScript中无法以这种方式工作。 what you need to do, is find the checked one and get its value. 您需要做的就是找到已检查的项目并获得其价值。 it is rather simple, with 1 line of code: 这很简单,只需一行代码:

document.querySelector('input[name="member"]:checked').value;

*same applies for attendees. *与会人员相同。

5. Counting Checked Checkboxes 5.计数选中的复选框

while iterating through the checkboxes and altering the total value could work, it is much simpler to count how many of them are checked using the next line: 虽然可以遍历复选框并更改总值,但使用下一行计算检查了多少复选框要简单得多:

document.querySelectorAll('input[name="eventCheckBox"]:checked').length;

6. Optional 6.可选

if you want the total price to update when attendees and membership are changed, then you need to add the change event to them as well. 如果您希望在更改与会者和成员资格时更新总价格,则还需要向他们添加更改事件。

Here is your fixed code: 这是您的固定代码:

 function checkTotal() { //get values from the inputs var attendees = document.querySelector('input[name="attendees"]:checked').value; var member = document.querySelector('input[name="member"]:checked').value; var SelectedEvents = document.querySelectorAll('.EventCheckBox:checked').length; //init vars; var total = 0; var price = 26.00; if (member == 1) { price = 18.00; } //calculate cost total = SelectedEvents * attendees * price; if (member == 1 && SelectedEvents == 4 && attendees == 1) { total = 68.00; } if (member == 1 && SelectedEvents == 4 && attendees == 2) { total = 136.00; } document.getElementById("total").value = "$" + total.toFixed(2); } 
 <font color="orange">How many attendees?</font> <input type="radio" name="attendees" value="1" checked="checked" onchange="checkTotal()" />1 <input type="radio" name="attendees" value="2" onchange="checkTotal()" />2 <br/> <font color="orange">Are you a Member?</font> <input type="radio" name="member" value="0" checked="checked" onchange="checkTotal()" />No <input type="radio" name="member" value="1" onchange="checkTotal()" />Yes <br/> <br/> <form name="listForm"><font color="orange">Select the Concerts you want Tickets for:</font> <br/> <input type="checkbox" name="eventCB1" value="1" onchange="checkTotal()" class="EventCheckBox" /><font color="#33FF33"> <div class="price"></div></font> </input>Nov. 1, 2015 -- Concert 1 <br/> <input type="checkbox" name="eventCB2" value="1" onchange="checkTotal()" class="EventCheckBox" /><font color="#33FF33"> <div class="price"></div></font> </input>Dec. 1, 2015 -- Concert 2 <br/> <input type="checkbox" name="eventCB3" value="1" onchange="checkTotal()" class="EventCheckBox" /><font color="#33FF33"> <div class="price"></div></font> </input>Jan. 1, 2015 -- Concert 3 <br/> <input type="checkbox" name="eventCB4" value="1" onchange="checkTotal()" class="EventCheckBox" /><font color="#33FF33"> <div class="price"></div></font> </input>Feb. 1, 2015 -- Concert 4 <br/> <br/> <font color="#33FF33">Total Cost:</font> <input value="$0.00" readonly="readonly" type="text" id="total" /> </form> 

and a Fiddle 小提琴

UPDATE: 更新:

If having the same name on all of the check boxes causes issues of any sort, it is handled easily. 如果在所有复选框上使用相同的名称会引起各种问题,则可以轻松处理。

javascript/html/css have many different ways to achieve the same result, in time you will learn more tricks, for now here are two: javascript / html / css有多种方法可以达到相同的结果,随着时间的推移,您将学到更多的技巧,现在有两种:

a. 一种。 the ^= attribute selector: ^=属性选择器:

this selects all elements who's attribute begins with a certain string. 这将选择所有属性某个字符串开头的元素。
before, we have selected all the inputs using their exact name: 之前,我们已经使用它们的确切名称选择了所有输入:

document.querySelectorAll('input[name="eventCB"]:checked')

this selected all checked inputs who's name attribute equals "eventCB" . 这将选择所有具有name属性等于"eventCB"选中输入。 now our elements have now ID's appended to the name, but all still begin with the same string "eventCB" therefore we can alter our selector as follows: 现在,我们的元素已经在名称后附加了ID,但是所有元素仍以相同的字符串"eventCB"开头,因此我们可以按以下方式更改选择器:

document.querySelectorAll('input[name^="eventCB"]:checked')

b. common class 普通班

in my opinion, it is much easier to set a common class to the events, and select them using the class; 我认为,为事件设置一个通用类并使用该类选择它们要容易得多; let their class be "EventCheckBox" for the example: 对于示例,将其类设为"EventCheckBox"

document.querySelectorAll('.EventCheckBox:checked').length;

the dot at the beginning of the selector string means class select. 选择器字符串开头的点表示类选择。 without a dot it will select element by type, with a dot it selects class, and with a # it will select by ID. 没有点它将由类型选择元件,用它选择类的点,并用#它将由ID选择。

i have updated the snippet and fiddle above. 我已经更新了上面的代码片段和小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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