0

I am trying to add multiple values for the same output "Maths book". I think I am missing something basic on how to format values in brackets.

<script type="text/javascript">
  <!--
  var book = "maths";
  if (book == "history") {
    document.write("<b>History Book</b>");

    /*How to add more options below besides "maths" so the output will be "Maths
    Book". I want the output to be "Maths Book" also when user enters 
    mathemathics, mata, maths book...

    Do I need more else if lines or I can put additional values in in brackets*/


  } else if (book == "maths") {
    document.write("<b>Maths Book</b>");
  } else {
    document.write("<b>Unknown Book</b>");
  }
  //-->
</script>
<p>Set the variable to different value and then try...</p>

3
  • 1
    You’re looking for the logical OR operator, but you should also find a newer resource for learning JavaScript if your current one is old enough to recommend <!-- … //-->. Commented May 4, 2018 at 12:33
  • You mean something like if (book.toLowerCase().indexOf("math") !=-1) Commented May 4, 2018 at 12:33
  • I am using tutorialspoint.com PDF JS tutorial. What is wrong with <!-- … //--> Commented May 4, 2018 at 13:05

1 Answer 1

0

Try following script and JSFiddle: https://jsfiddle.net/19d7g8f0/2/ will help

function addBook(book){
   if( book == "history" || book=="archive"){
      document.write("<b>History Book</b>");
   }else if( -1 != ["maths","mathematics","arithmetics"].indexOf(book.toLowerCase()) ){
      document.write("<b>Maths Book</b>");
   }else{
      document.write("<b>Unknown Book</b>");
   }
}

addBook("Maths");
addBook("mathematics");
addBook("Arithmetics");
Sign up to request clarification or add additional context in comments.

6 Comments

I am trying to do something simpler: To add more options in else if ( book == "math", "matemathica") so every value outputs as Maths Book. So I don't have to add more lines. How to properly format that?
ah... try else if ( book == "math" || book == "matemathica")
Yup! That's it! Many thanks. I didn't know I need to put book== again every time. Is there any simpler way without book==?
You may try and .... else if( -1 != ["maths", "mathematics","arithmetics"].indexOf(book.toLowerCase()) ) to ignore case in comparison
I've changed my answer then to match :) Cheers!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.