-1

I need to create a very basic function that calculates the cost when a user clicks the button.

Suppose there are three customers that want to travel; once they click on the button and select the number of people and a location then they should see their total cost for that location.

For example, if they choose the second destination, then three persons will be £450, £500, and then £550 each, so the total should be £1500.

  • 3
    Add the code you have tried. – anpsmn Apr 10 '15 at 05:09
  • You seem to be looking for code you can copy and paste without understanding it. This is not how it works. We are here to help you write code, not to write code for you. – Tomalak Apr 10 '15 at 05:35
  • I have created this table using Html but I havent add the code because it was easy, I was strugling with javascript and didnt had any idea where from to start. Like I said before I am completely novice to javascript but hopefully I will get better. Thanks for looking at my question and passing your valuable comments. – Jordan Westley Apr 11 '15 at 15:20
  • This is my webpage complete code, Javascript has been provided by below member Shrif ahmed, However it is not working for me. Click here to view my webpage. [link](https://jsfiddle.net/cq7aex00/) – Jordan Westley Apr 11 '15 at 16:24

3 Answers3

0

maybe something like this could help: you can see the running the example...

function calc(){
  var tmpText = "";
  var total = 0;
  $( ".price" ).each(function( index ) {
    //strip string into num
    tmpText = $( this ).text();
    tmpText = tmpText.substr(1);;
    //add number
    total+=Number(tmpText)
    console.log( index + ": " + $( this ).text() );
  });
  $("#result").text("$"+total);
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td class='price'>$50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td> 
    <td class='price'>$94</td>
  </tr>
</table>
<button onclick="calc()">calculate</button>
<p id="result"></p>

please be sure you are adding jquery to your fiddle enter image description here

David Rubin
  • 123
  • 7
  • I have tried but it doesnt seems to be working, However I am trying on something different, I got javascript from above member however it is not doing calculation on my webpage, I dont know why. Check my website here on [JSFIDDLE](https://jsfiddle.net/cq7aex00/) – Jordan Westley Apr 11 '15 at 16:32
  • ok, i tried the fiddle, the only thing you need to do is to add at the top left corner jquery load – David Rubin Apr 11 '15 at 16:47
  • Many thanks for your answer, it actually worked in fiddle however not in my webpage, this is how i am calling external javascript from html The script is same one but its not working do I have to add anything else? – Jordan Westley Apr 11 '15 at 17:20
  • yes, in order to include jQuery into your web page you can a. download the code to your hosting and load it from there b. load it directly from jquery with you have all the options here: https://jquery.com/download/ – David Rubin Apr 11 '15 at 18:28
  • I think your example is based on Jquery rather than javascript because I just realize that, I am sorry but I need it with a basic and original javascript, thats the requirement, thanks anyway for your help. – Jordan Westley Apr 11 '15 at 22:55
0

take a look at the example below

$(document).ready(function(){
$('#flights td').on('click', function(){
     var colIndex = $(this).prevAll().length;
     var rowIndex = $(this).parent('tr').prevAll().length + 1;

    var cost = 0;
    var sign = '';
    for (var i = 0; i < rowIndex; i++)
    {
        var value = $('#flights tbody tr:eq(' + i.toString() + ') td:eq(' + (colIndex-1) + ')').html();
        sign = value.substring(0,1);
        cost += Number(value.substring(1));
    }

    $('#cost').text(sign + cost);

});
});

<table id="flights">
<thead>
    <tr>
        <th>Destination</th>
        <th>First</th>
        <th>Second</th>
        <th>Third</th>
    </tr>
</thead>
<tbody>
    <tr>
        <th>One</th>
        <td>$400</td>
        <td>$450</td>
        <td>$500</td>
    </tr>
    <tr>
        <th>Two</th>
        <td>$450</td>
        <td>$500</td>
        <td>$550</td>
    </tr>
    <tr>
        <th>Three</th>
        <td>$500</td>
        <td>$550</td>
        <td>$600</td>
    </tr>
    <tr>
        <th>Four</th>
        <td>$550</td>
        <td>$600</td>
        <td>$650</td>
    </tr>
    <tr>
        <th>Five</th>
        <td>$600</td>
        <td>$650</td>
        <td>$700</td>
    </tr>
</tbody>
</table>

<label>Cost: </label> <label id="cost"></label>

Explanation:
1- $('#flights td') - This is a jquery selector to get all the td(s) inside a table called "#flights" ---- you can find more about jquery selector Here

2- .on('click', function(){}) - Here I'm attaching a event handler function to a specific event which is the click ---- you can find more about .on() Here

3- var colIndex = $(this).prevAll().length; - Here I'm getting the column index of the CLICKED td ---- you can find more about .prevAll() Here

4- var rowIndex = $(this).parent('tr').prevAll().length + 1; - Here I'm getting the row index of the CLICKED td ---- you can find more about .parent() Here

5- for (var i = 0; i < rowIndex; i++) - Here I started a loop starting from 0 until the ROW INDEX OF THE CLICKED td ---- you can find more about for loop Here

6- var value = $('#flights tbody tr:eq(' + i.toString() + ') td:eq(' + (colIndex-1) + ')').html(); - Here I'm getting the value inside the td based on the STATIC COLUMN INDEX OF THE CLICKED td and the ROW INDEX (which is i) inside the loop. ---- you can find more about .html() Here

7- value.substring(0,1); - I'm just getting the Sign which may vary ($, €) so that I can concatenate it in the cost label. ---- you can find more about .substring() Here

8- cost += Number(value.substring(1)); - Here I'm getting the value of each td and stripping out the sign and converting it to number and adding it to the total cost which will be populated in the cost label.

9- $('#cost').text(sign + cost); - Here just populating the total cost in the cost label and concatenating the Sign to it.

You can learn more about jquery from Here, it's a good start to learn.

Sherif Ahmed
  • 1,896
  • 1
  • 19
  • 37
  • I have tried but calculation is not working. Click here to view my webpage. [link](https://jsfiddle.net/cq7aex00/) – Jordan Westley Apr 11 '15 at 16:12
  • you must reference the jquery library ... the cdn url https://code.jquery.com/jquery-2.1.3.min.js – Sherif Ahmed Apr 11 '15 at 19:08
  • here is a jsfiddle link ... https://jsfiddle.net/cq7aex00/1/ ......... check the Frameworks & Extensions on the top left for the extensions used – Sherif Ahmed Apr 11 '15 at 19:09
  • Yes I have done that and its working properly but How I can implement jquery in same webpage. I have host my website yet, its not on server, It is in my pc and the calculation is not working. I dont know how I add jquery to my html document. I am lost. – Jordan Westley Apr 11 '15 at 20:05
  • in the head party of your html ... add this line if you local pc is connected to internet ... if your local pc is not connected .. download the script and attach it the same but specify the localtion if you put the file in "Scripts" folder on the root – Sherif Ahmed Apr 11 '15 at 20:57
  • check this if you have trouble in attaching jquery http://stackoverflow.com/q/5232968/2907017 – Sherif Ahmed Apr 11 '15 at 20:59
  • Ok Finally It worked. Would It be Possible to explain your java code to me. the table is straight forward but I would like to know about javascript that you provide me, because I havent use such functions in lesson. and I dont know how this all java code of yours work. I just want to understand so I can exaplain to totor what it does. – Jordan Westley Apr 11 '15 at 21:44
0

Ok, so here is the jQuery-free solution to this: (you can run it below)

function calc() {
  var elems = document.getElementsByClassName("someClass");
  var sum = 0;
  for (var i = 0; i < elems.length; i++) {
    var elem = elems[i];
    var num = elem.innerHTML;
    num = num.substr(1);
    sum += Number(num);
    elem.style.background = "red"
  }
  document.getElementById("cost").innerHTML = "£" + sum;
}
html {
  background: url(../images/background.jpg) no-repeat center center fixed;
  background-size: cover;
  /* Applying image to whole html document */
}
body {
  margin: 10px auto;
}
p {
  font-family: "times new roman";
  font-size: 20px;
  padding-left: 40px;
  padding-right: 30px;
}
a:hover {
  color: red;
}
a:link {
  text-decoration: none;
  /* These are link styles */
}
h1 {
  color: blue;
  text-align: center;
  font-family: courier;
  font-size: 20px;
  background-color: #C0C0C0;
}
table th,
table td {
  padding: 10px;
  border: 1px solid black;
}
td {
  text-align: center;
  cursor: pointer;
}
h2 {
  color: blue;
  font-family: courier;
  font-size: 20px;
  text-align: left;
  padding-left: 40px;
  padding-right: 25px;
}
article {
  font-family: "times new roman";
  background-color: #FFFFFF;
  font-size: 20px;
  margin: 10px;
  padding-left: 15px;
  padding-right: 15px;
  padding-bottom: 10px;
  margin-left: 22%;
  margin-right: 20%;
  /* This is article section */
}
img {
  display: block;
  margin: 0 auto;
  margin-bottom: 5px;
  /* This is image section */
}
#footer {
  width: 640px;
  margin: auto;
  clear: both;
  color: white;
  text-align: center;
  /* This is footer section */
}
/* Below is navigation bar section */

#cssmenu li #cssmenu a {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 14px;
  font-family: Helvetica;
  line-height: 1;
}
#cssmenu ul {
  background: #0033CC url(../images/pattern.png) top left repeat;
  list-style: none;
  margin-left: 26%;
  margin-right: 24%;
}
#cssmenu ul:before {
  content: '';
  display: block;
}
#cssmenu ul:after {
  content: '';
  display: table;
  clear: both;
}
#cssmenu a:link,
#cssmenu a:visited {
  padding: 20px 25px;
  display: block;
  text-decoration: none;
  color: #ffffff;
  text-shadow: 0 -1px 1px #586835;
  border-right: 1px solid #839b4e;
}
#cssmenu a:hover {
  color: #6600FF;
  text-shadow: 0 1px 1px #bdcd9c;
}
#cssmenu li {
  float: left;
}
<body>
  <a id="TOP" name="GoTop"></a>
  <div id="cssmenu">
    <ul>
      <li><a href="index.html">Home</a>
      </li>
      <li><a href="#">Detinations</a>
      </li>
    </ul>
  </div>
  <article>
    <h1> Three Different Cruise Tours </h1>
    <p>We are currently offering three different Cruise tours....</p>

    <h2> Paris & French Countryside Cruise tour </h2>
    <img src="images/french.jpg" alt="Paris and French" style="width:90%;height:400px">
    <p>You'll be dazzled by the city of romance with visits to the legendary Notre Dame Cathedral and the opulent Palace of Versailles....</p>
    <h2> Swiss Splendors Cruise tour </h2>
    <img src="images/swiss.jpg" alt="swiss splendors" style="width:90%;height:400px">
    <p>From the magnificent snow caps of the Bernese and Swiss Alps to the enchanting gardens surrounding Lake Como....</p>
    <h2>Europe's Imperial Treasures Cruise tour</h2>
    <img src="images/russia.jpg" alt="European" style="width:90%;height:400px">
    <p>You'll be immersed in the unique cultures of Budapest, Vienna and Prague ...</p>
    <h1> Price Guide </h1>
    <p>click on field to calculate the price.
      <p>

        <table id="flights">
          <thead>
            <tr>
              <th>Destination</th>
              <th>First</th>
              <th>Second</th>
              <th>Third</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <th>One</th>
              <td class="someClass">£400</td>
              <td>£450</td>
              <td>£500</td>
            </tr>
            <tr>
              <th>Two</th>
              <td class="someClass">£450</td>
              <td>£500</td>
              <td>£550</td>
            </tr>
            <tr>
              <th>Three</th>
              <td class="someClass">£500</td>
              <td>£550</td>
              <td>£600</td>
            </tr>
            <tr>
              <th>Four</th>
              <td class="someClass">£550</td>
              <td>£600</td>
              <td>£650</td>
            </tr>
            <tr>
              <th>Five</th>
              <td class="someClass">£600</td>
              <td>£650</td>
              <td>£700</td>
            </tr>
          </tbody>
        </table>

        <button onclick="calc()">calculate first col</button>
        <label>Cost:</label>
        <label id="cost"></label>

  </article>
  <div id="footer">
    <br>
    <p>&copy; 2014</p>
  </div>
  <a href="#TOP">Go To Top</a> 
</body>
David Rubin
  • 123
  • 7
  • Many thanks for your answer, However It is already been done by sherif ahmed and I may use his example, However I needed javascript not Jquery but appreciate the help. – Jordan Westley Apr 15 '15 at 07:04