Is there a way to add arithmetic operator inside a function in ejs?












0














I am creating a express app with a booking form using ejs and adding functionality inside it. it's used as a payment.



I have a select tag and stored it's selected text inside of a variable. Console logging it gives the value but using it in the actual code gives an error that says it's undefined.



What I need is to take the value of the selected input, for example 2 and multiply it to the tour.price amount, for example 34000 so the total would be 68000 and put inside the addCommas() Amount: $ <%= addCommas(34000 * 2) %> //the total should be 68000 then the function addCommas() which would make it 68,000.



I tried using Scriptlet' tag of ejs and put this code on top of the file



<%let selectedText = document.querySelector("#numOfPersons")%>
<%let valueOfSelected = selectedText.options[selectedText.selectedIndex].value %>
<form>
<div>
<label for="numOfPersons">Number of Persons</label>
<select id="numOfPersons">
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
</div>

Amount: $ <%= addCommas(tour.price * valueOfSelected) %> //addCommas() is a function that takes a number and adds comma every three numbers, ex: 100000 will become 100,000.
// tour.price is the total amount of the product. It's a Number. it's current value is 34000
</form>


It says that valueOfSelected is not defined.
my second attempt is adding
<%let selectedText = document.querySelector("#numOfPersons")%>
<%let valueOfSelected = selectedText.options[selectedText.selectedIndex].value %> below the form tag but it also says not defined.



Then I tried adding script tag below the file
<script>
let selectedText = document.querySelector("#numOfPersons");
let valueOfSelected =
selectedText.options[selectedText.selectedIndex].value;
</script>



and then for my final attempt, I do this.

let totalAmount = tour.price * Number(valueOfSelected);
document.querySelector("#total").innerHTML = "Amount: $ <%= addCommas(totalAmount) %>"



All come out as not defined



The expected result should output a total price of $68,000 when <%= addCommas(tour.price * valueOfSelected) %> is called



P.S. For some reason, I cannot create another code block using 4 spaces.










share|improve this question



























    0














    I am creating a express app with a booking form using ejs and adding functionality inside it. it's used as a payment.



    I have a select tag and stored it's selected text inside of a variable. Console logging it gives the value but using it in the actual code gives an error that says it's undefined.



    What I need is to take the value of the selected input, for example 2 and multiply it to the tour.price amount, for example 34000 so the total would be 68000 and put inside the addCommas() Amount: $ <%= addCommas(34000 * 2) %> //the total should be 68000 then the function addCommas() which would make it 68,000.



    I tried using Scriptlet' tag of ejs and put this code on top of the file



    <%let selectedText = document.querySelector("#numOfPersons")%>
    <%let valueOfSelected = selectedText.options[selectedText.selectedIndex].value %>
    <form>
    <div>
    <label for="numOfPersons">Number of Persons</label>
    <select id="numOfPersons">
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    </select>
    </div>

    Amount: $ <%= addCommas(tour.price * valueOfSelected) %> //addCommas() is a function that takes a number and adds comma every three numbers, ex: 100000 will become 100,000.
    // tour.price is the total amount of the product. It's a Number. it's current value is 34000
    </form>


    It says that valueOfSelected is not defined.
    my second attempt is adding
    <%let selectedText = document.querySelector("#numOfPersons")%>
    <%let valueOfSelected = selectedText.options[selectedText.selectedIndex].value %> below the form tag but it also says not defined.



    Then I tried adding script tag below the file
    <script>
    let selectedText = document.querySelector("#numOfPersons");
    let valueOfSelected =
    selectedText.options[selectedText.selectedIndex].value;
    </script>



    and then for my final attempt, I do this.

    let totalAmount = tour.price * Number(valueOfSelected);
    document.querySelector("#total").innerHTML = "Amount: $ <%= addCommas(totalAmount) %>"



    All come out as not defined



    The expected result should output a total price of $68,000 when <%= addCommas(tour.price * valueOfSelected) %> is called



    P.S. For some reason, I cannot create another code block using 4 spaces.










    share|improve this question

























      0












      0








      0







      I am creating a express app with a booking form using ejs and adding functionality inside it. it's used as a payment.



      I have a select tag and stored it's selected text inside of a variable. Console logging it gives the value but using it in the actual code gives an error that says it's undefined.



      What I need is to take the value of the selected input, for example 2 and multiply it to the tour.price amount, for example 34000 so the total would be 68000 and put inside the addCommas() Amount: $ <%= addCommas(34000 * 2) %> //the total should be 68000 then the function addCommas() which would make it 68,000.



      I tried using Scriptlet' tag of ejs and put this code on top of the file



      <%let selectedText = document.querySelector("#numOfPersons")%>
      <%let valueOfSelected = selectedText.options[selectedText.selectedIndex].value %>
      <form>
      <div>
      <label for="numOfPersons">Number of Persons</label>
      <select id="numOfPersons">
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
      </select>
      </div>

      Amount: $ <%= addCommas(tour.price * valueOfSelected) %> //addCommas() is a function that takes a number and adds comma every three numbers, ex: 100000 will become 100,000.
      // tour.price is the total amount of the product. It's a Number. it's current value is 34000
      </form>


      It says that valueOfSelected is not defined.
      my second attempt is adding
      <%let selectedText = document.querySelector("#numOfPersons")%>
      <%let valueOfSelected = selectedText.options[selectedText.selectedIndex].value %> below the form tag but it also says not defined.



      Then I tried adding script tag below the file
      <script>
      let selectedText = document.querySelector("#numOfPersons");
      let valueOfSelected =
      selectedText.options[selectedText.selectedIndex].value;
      </script>



      and then for my final attempt, I do this.

      let totalAmount = tour.price * Number(valueOfSelected);
      document.querySelector("#total").innerHTML = "Amount: $ <%= addCommas(totalAmount) %>"



      All come out as not defined



      The expected result should output a total price of $68,000 when <%= addCommas(tour.price * valueOfSelected) %> is called



      P.S. For some reason, I cannot create another code block using 4 spaces.










      share|improve this question













      I am creating a express app with a booking form using ejs and adding functionality inside it. it's used as a payment.



      I have a select tag and stored it's selected text inside of a variable. Console logging it gives the value but using it in the actual code gives an error that says it's undefined.



      What I need is to take the value of the selected input, for example 2 and multiply it to the tour.price amount, for example 34000 so the total would be 68000 and put inside the addCommas() Amount: $ <%= addCommas(34000 * 2) %> //the total should be 68000 then the function addCommas() which would make it 68,000.



      I tried using Scriptlet' tag of ejs and put this code on top of the file



      <%let selectedText = document.querySelector("#numOfPersons")%>
      <%let valueOfSelected = selectedText.options[selectedText.selectedIndex].value %>
      <form>
      <div>
      <label for="numOfPersons">Number of Persons</label>
      <select id="numOfPersons">
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
      </select>
      </div>

      Amount: $ <%= addCommas(tour.price * valueOfSelected) %> //addCommas() is a function that takes a number and adds comma every three numbers, ex: 100000 will become 100,000.
      // tour.price is the total amount of the product. It's a Number. it's current value is 34000
      </form>


      It says that valueOfSelected is not defined.
      my second attempt is adding
      <%let selectedText = document.querySelector("#numOfPersons")%>
      <%let valueOfSelected = selectedText.options[selectedText.selectedIndex].value %> below the form tag but it also says not defined.



      Then I tried adding script tag below the file
      <script>
      let selectedText = document.querySelector("#numOfPersons");
      let valueOfSelected =
      selectedText.options[selectedText.selectedIndex].value;
      </script>



      and then for my final attempt, I do this.

      let totalAmount = tour.price * Number(valueOfSelected);
      document.querySelector("#total").innerHTML = "Amount: $ <%= addCommas(totalAmount) %>"



      All come out as not defined



      The expected result should output a total price of $68,000 when <%= addCommas(tour.price * valueOfSelected) %> is called



      P.S. For some reason, I cannot create another code block using 4 spaces.







      javascript node.js express ejs






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 27 at 14:22









      bradrar

      857




      857
























          1 Answer
          1






          active

          oldest

          votes


















          1














          Whatever DOM operations like getting selected text cannot be written directly in ejs file. You have to do that inside the script tag(i.e. using js) as in your second approach.



          Inside the script try getting values after the document is loaded:



          <script>
          function addCommas() { // implement the function here }
          document.addEventListener("DOMContentLoaded", function(event) {
          // get values here like the `valueOfSelected`
          var tourPrice = "<%= tour.price %>";

          var valueWithCommasAdded = addCommas(tourPrice * valueOfSelected);
          var content = document.createTextNode("Amount: " + valueWithCommasAdded);

          // Finally append to the form
          document.forms[0].appendChild(content);

          });
          </script>


          You have to do this way because you have to wait for the document to load fully. The ejs will have loaded already before you can get value from the DOM. You have to do the calculation dynamically with javascript and place in the DOM.






          share|improve this answer










          New contributor




          Sankalpa Timilsina is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.


















          • Thank you for your answer. I tried your code and it works until ` var valueWithCommasAdded` by doing console.log(valueWithCommasAdded) but the appending part gives an error in the console. ` Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. at HTMLDocument.<anonymous>` where does document.forms[0] takes it? I also tried this instead yours by putting a <p> tag inside the form with id of #total, document.getElementById('#total').innerHTML(valueWithCommasAdded); . my attempt also failed
            – bradrar
            Dec 27 at 15:11








          • 1




            Please check the updated answer. Turns out you need to add a text node.
            – Sankalpa Timilsina
            Dec 27 at 15:22










          • Thank you for the answer. It is working now. But when I select another option inside the select tag, It's not updating. I will find a solution on my own on this one. Thank you again!
            – bradrar
            Dec 27 at 15:27






          • 1




            Glad I could help. And good luck!
            – Sankalpa Timilsina
            Dec 27 at 15:39











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53946550%2fis-there-a-way-to-add-arithmetic-operator-inside-a-function-in-ejs%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Whatever DOM operations like getting selected text cannot be written directly in ejs file. You have to do that inside the script tag(i.e. using js) as in your second approach.



          Inside the script try getting values after the document is loaded:



          <script>
          function addCommas() { // implement the function here }
          document.addEventListener("DOMContentLoaded", function(event) {
          // get values here like the `valueOfSelected`
          var tourPrice = "<%= tour.price %>";

          var valueWithCommasAdded = addCommas(tourPrice * valueOfSelected);
          var content = document.createTextNode("Amount: " + valueWithCommasAdded);

          // Finally append to the form
          document.forms[0].appendChild(content);

          });
          </script>


          You have to do this way because you have to wait for the document to load fully. The ejs will have loaded already before you can get value from the DOM. You have to do the calculation dynamically with javascript and place in the DOM.






          share|improve this answer










          New contributor




          Sankalpa Timilsina is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.


















          • Thank you for your answer. I tried your code and it works until ` var valueWithCommasAdded` by doing console.log(valueWithCommasAdded) but the appending part gives an error in the console. ` Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. at HTMLDocument.<anonymous>` where does document.forms[0] takes it? I also tried this instead yours by putting a <p> tag inside the form with id of #total, document.getElementById('#total').innerHTML(valueWithCommasAdded); . my attempt also failed
            – bradrar
            Dec 27 at 15:11








          • 1




            Please check the updated answer. Turns out you need to add a text node.
            – Sankalpa Timilsina
            Dec 27 at 15:22










          • Thank you for the answer. It is working now. But when I select another option inside the select tag, It's not updating. I will find a solution on my own on this one. Thank you again!
            – bradrar
            Dec 27 at 15:27






          • 1




            Glad I could help. And good luck!
            – Sankalpa Timilsina
            Dec 27 at 15:39
















          1














          Whatever DOM operations like getting selected text cannot be written directly in ejs file. You have to do that inside the script tag(i.e. using js) as in your second approach.



          Inside the script try getting values after the document is loaded:



          <script>
          function addCommas() { // implement the function here }
          document.addEventListener("DOMContentLoaded", function(event) {
          // get values here like the `valueOfSelected`
          var tourPrice = "<%= tour.price %>";

          var valueWithCommasAdded = addCommas(tourPrice * valueOfSelected);
          var content = document.createTextNode("Amount: " + valueWithCommasAdded);

          // Finally append to the form
          document.forms[0].appendChild(content);

          });
          </script>


          You have to do this way because you have to wait for the document to load fully. The ejs will have loaded already before you can get value from the DOM. You have to do the calculation dynamically with javascript and place in the DOM.






          share|improve this answer










          New contributor




          Sankalpa Timilsina is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.


















          • Thank you for your answer. I tried your code and it works until ` var valueWithCommasAdded` by doing console.log(valueWithCommasAdded) but the appending part gives an error in the console. ` Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. at HTMLDocument.<anonymous>` where does document.forms[0] takes it? I also tried this instead yours by putting a <p> tag inside the form with id of #total, document.getElementById('#total').innerHTML(valueWithCommasAdded); . my attempt also failed
            – bradrar
            Dec 27 at 15:11








          • 1




            Please check the updated answer. Turns out you need to add a text node.
            – Sankalpa Timilsina
            Dec 27 at 15:22










          • Thank you for the answer. It is working now. But when I select another option inside the select tag, It's not updating. I will find a solution on my own on this one. Thank you again!
            – bradrar
            Dec 27 at 15:27






          • 1




            Glad I could help. And good luck!
            – Sankalpa Timilsina
            Dec 27 at 15:39














          1












          1








          1






          Whatever DOM operations like getting selected text cannot be written directly in ejs file. You have to do that inside the script tag(i.e. using js) as in your second approach.



          Inside the script try getting values after the document is loaded:



          <script>
          function addCommas() { // implement the function here }
          document.addEventListener("DOMContentLoaded", function(event) {
          // get values here like the `valueOfSelected`
          var tourPrice = "<%= tour.price %>";

          var valueWithCommasAdded = addCommas(tourPrice * valueOfSelected);
          var content = document.createTextNode("Amount: " + valueWithCommasAdded);

          // Finally append to the form
          document.forms[0].appendChild(content);

          });
          </script>


          You have to do this way because you have to wait for the document to load fully. The ejs will have loaded already before you can get value from the DOM. You have to do the calculation dynamically with javascript and place in the DOM.






          share|improve this answer










          New contributor




          Sankalpa Timilsina is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          Whatever DOM operations like getting selected text cannot be written directly in ejs file. You have to do that inside the script tag(i.e. using js) as in your second approach.



          Inside the script try getting values after the document is loaded:



          <script>
          function addCommas() { // implement the function here }
          document.addEventListener("DOMContentLoaded", function(event) {
          // get values here like the `valueOfSelected`
          var tourPrice = "<%= tour.price %>";

          var valueWithCommasAdded = addCommas(tourPrice * valueOfSelected);
          var content = document.createTextNode("Amount: " + valueWithCommasAdded);

          // Finally append to the form
          document.forms[0].appendChild(content);

          });
          </script>


          You have to do this way because you have to wait for the document to load fully. The ejs will have loaded already before you can get value from the DOM. You have to do the calculation dynamically with javascript and place in the DOM.







          share|improve this answer










          New contributor




          Sankalpa Timilsina is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          share|improve this answer



          share|improve this answer








          edited Dec 27 at 15:21





















          New contributor




          Sankalpa Timilsina is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          answered Dec 27 at 14:46









          Sankalpa Timilsina

          1835




          1835




          New contributor




          Sankalpa Timilsina is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





          New contributor





          Sankalpa Timilsina is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          Sankalpa Timilsina is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.












          • Thank you for your answer. I tried your code and it works until ` var valueWithCommasAdded` by doing console.log(valueWithCommasAdded) but the appending part gives an error in the console. ` Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. at HTMLDocument.<anonymous>` where does document.forms[0] takes it? I also tried this instead yours by putting a <p> tag inside the form with id of #total, document.getElementById('#total').innerHTML(valueWithCommasAdded); . my attempt also failed
            – bradrar
            Dec 27 at 15:11








          • 1




            Please check the updated answer. Turns out you need to add a text node.
            – Sankalpa Timilsina
            Dec 27 at 15:22










          • Thank you for the answer. It is working now. But when I select another option inside the select tag, It's not updating. I will find a solution on my own on this one. Thank you again!
            – bradrar
            Dec 27 at 15:27






          • 1




            Glad I could help. And good luck!
            – Sankalpa Timilsina
            Dec 27 at 15:39


















          • Thank you for your answer. I tried your code and it works until ` var valueWithCommasAdded` by doing console.log(valueWithCommasAdded) but the appending part gives an error in the console. ` Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. at HTMLDocument.<anonymous>` where does document.forms[0] takes it? I also tried this instead yours by putting a <p> tag inside the form with id of #total, document.getElementById('#total').innerHTML(valueWithCommasAdded); . my attempt also failed
            – bradrar
            Dec 27 at 15:11








          • 1




            Please check the updated answer. Turns out you need to add a text node.
            – Sankalpa Timilsina
            Dec 27 at 15:22










          • Thank you for the answer. It is working now. But when I select another option inside the select tag, It's not updating. I will find a solution on my own on this one. Thank you again!
            – bradrar
            Dec 27 at 15:27






          • 1




            Glad I could help. And good luck!
            – Sankalpa Timilsina
            Dec 27 at 15:39
















          Thank you for your answer. I tried your code and it works until ` var valueWithCommasAdded` by doing console.log(valueWithCommasAdded) but the appending part gives an error in the console. ` Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. at HTMLDocument.<anonymous>` where does document.forms[0] takes it? I also tried this instead yours by putting a <p> tag inside the form with id of #total, document.getElementById('#total').innerHTML(valueWithCommasAdded); . my attempt also failed
          – bradrar
          Dec 27 at 15:11






          Thank you for your answer. I tried your code and it works until ` var valueWithCommasAdded` by doing console.log(valueWithCommasAdded) but the appending part gives an error in the console. ` Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. at HTMLDocument.<anonymous>` where does document.forms[0] takes it? I also tried this instead yours by putting a <p> tag inside the form with id of #total, document.getElementById('#total').innerHTML(valueWithCommasAdded); . my attempt also failed
          – bradrar
          Dec 27 at 15:11






          1




          1




          Please check the updated answer. Turns out you need to add a text node.
          – Sankalpa Timilsina
          Dec 27 at 15:22




          Please check the updated answer. Turns out you need to add a text node.
          – Sankalpa Timilsina
          Dec 27 at 15:22












          Thank you for the answer. It is working now. But when I select another option inside the select tag, It's not updating. I will find a solution on my own on this one. Thank you again!
          – bradrar
          Dec 27 at 15:27




          Thank you for the answer. It is working now. But when I select another option inside the select tag, It's not updating. I will find a solution on my own on this one. Thank you again!
          – bradrar
          Dec 27 at 15:27




          1




          1




          Glad I could help. And good luck!
          – Sankalpa Timilsina
          Dec 27 at 15:39




          Glad I could help. And good luck!
          – Sankalpa Timilsina
          Dec 27 at 15:39


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53946550%2fis-there-a-way-to-add-arithmetic-operator-inside-a-function-in-ejs%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Monofisismo

          Angular Downloading a file using contenturl with Basic Authentication

          Olmecas