jQuery Conditional String Manipulation

I have set up a system where users can input values and make selections from a drop-down menu, which then get integrated into JavaScript code to generate customized sentences based on their inputs. Once the user clicks submit, the sentence is formed. It's a simple process overall, but I am struggling with incorporating multiple inputs from a single drop-down selection into the sentence.

For instance, if a user selects "navigation" and "usb ports" within the drop-down, the sentence should read as follows: "It has these options: navigation, aux." Similarly, if three options are chosen, the sentence should be formatted like this: "It has these options: navigation, aux, usb ports."

I am looking for guidance on how to modify the code so that when two options are selected, they are separated by an "and" in the sentence. For example, it should say: "It has these options: navigation and aux." In cases where three or more options are selected, an "and" should appear before the last option, like so: "It has these options: navigation, aux, and usb ports."

Answer №1

The input4 is an array provided by Chosen.

You simply need to iterate through the values in that array and customize them as desired, such as adding commas and including an "and" before the last value.

<!DOCTYPE html>
<html>

  <head>
<title>Greetings</title>;

  <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css">

<style type="text/css">
  table,td,th {margin-left: auto;margin-right: auto}
  .display {display: flex;align-items: center;justify-content: center;}
  p {text-align: center;}
  textarea {display: block;margin-left:auto;margin-right: auto;}
</style>

  <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>

<script type="text/javascript">

  $(function() {
    $(".chosen-select").chosen({
      disable_search_threshold: 4
    });
  })
  </script>

  <script type="text/javascript">

  function generateText() {
    document.getElementById("s1").value = "";// reset
    document.getElementById("s1").style.display = "block";
    document.getElementById("r1").style.display = "block";

    if (document.getElementById("z1").value == "") {
      alert("Please provide Year, Make, and Model");
      document.getElementById("z1").focus();
    }

  else if (document.getElementById("z2").value == "") {
      alert("Mileage is required");
    }

else if (document.getElementById("z3").value == "") {
      alert("Exterior color must be specified");
    }

    else {
      const input1 = document.getElementById("z1").value;
      const input2 = document.getElementById("z2").value;
      const input3 = document.getElementById("z3").value;
      var input4 = $('#z4').val();
      
      // =======================================
      console.log(input4);  // This represents an array.
      
      var formattedInput4 = "";
      if(input4.length==1){
        // Only one element...
        formattedInput4 = input4[0];
      }
      if(input4.length==2){
        // Two elements... Add "and"
        formattedInput4 = input4[0]+" and"+input4[1];
      }
      if(input4.length>2){
        // more than 2 elements...
        for(i=0;i<input4.length-1;i++){
          formattedInput4 += input4[i]+",";
        }
        formattedInput4 += " and"+input4[input4.length-1];
      }
      // =======================================
      
      document.getElementById("s1").value =
        "For sale is a " + input1 + " with " + input2 + " miles. It is finished in "
        + input3 + ". Options include: " +formattedInput4+ ".";

    }
  }

  function clearForm() {
    document.getElementById("s1").value = "";
  }


  function conceal() {
    document.getElementById("s1").style.display = "none";
    document.getElementById("r1").style.display = "none";
  }


</script>
  </head>

  <body onload="conceal()">
    <table>
      <tr>
        <td>
          <input type="text" id="z1" placeholder="Year, Make, Model" name="name" maxlength="100">
        </td>
        <td>
          <input type="text" id="z2" placeholder="Mileage" name="name" maxlength="100">
        </td>
        <td>
          <input type="text" id="z3" placeholder="Exterior Color" name="name" maxlength="100">
        </td>
        <td>
          <select data-placeholder="Options" name="options" id="z4"  multiple class="chosen-select">
            <option value=""></option>
            <option value=" navigation">Navigation</option>
            <option value=" aux">Aux</option>
            <option value=" usb ports">USB Ports</option>
            <option value=" heated seats">Heated Seats</option>
          </select>
        </td>
      </tr>
      <tr>
    </table>
    <br>
    <div class="display">
      <button onclick="generateText()"> Submit </button>
    </div>
    <hr>
    <br>
    <textarea rows="10" cols="100" id="s1"></textarea>
    <br>

    <div class="display">
      <button onclick="clearForm()" id="r1">Reset</button>
    </div>

  </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Alternative form for non-javascript browsers in the absence of script

I'm currently working on a landing page for an upcoming product, and I've run into a bit of a snag. <form novalidate method="POST" class="subscribe-form"> <noscript> </form> <form method="POST" action="/ ...

Tips for updating the color of a table row when it is chosen and a row is inserted using ajax

I have successfully added table rows dynamically through ajax in MVC C#. Now, I am looking to change the color of a selected row. This effect works well on the table with rows generated in the HTML view. <div class="col-lg-6 col-sm-12"> ...

Unable to modify variable to play audio

As I work on constructing my website, I am incorporating various sounds to enhance user experience when interacting with buttons and other elements. However, managing multiple audio files has proven challenging, as overlapping sounds often result in no aud ...

Transferring array data between two distinct click actions

Is there a way to transfer values between click events in jQuery? For example, on the first click event I want to add or remove values from an array based on whether a checkbox is checked. Then, on the second click I would like to iterate through all the ...

Created a custom JQuery Slider from scratch - Disappointed with the results

Despite having experience in J2ee/C/C++, I am new to Javascript and JQuery. I managed to create my own JQuery slider, complete with source code: <!DOCTYPE html> <html> <head> <title>Experimentation</title> <style ...

When using jQuery load and TinyMCE, I encountered an error stating "g.win.document is null" upon subsequent loads

New to stackoverflow and thrilled to make my first post! I'm working on a page where clicking a button triggers the function editIEPProgram(). This function counts how many specific divs exist, adds another div, loads it with content from '/cont ...

Using the jquery-ui-daterangepicker to fetch date values within an MVC controller

I have successfully implemented the jquery-ui-daterangepicker. How can I extract the start and end dates when submitting to my controller? Controller: [HttpPost] public ActionResult EmailReport(DateTime start, DateTime end) { int totalEma ...

JavaScript Date Validation: Ensuring Proper Dates

I am working with a date string that is in the format of "DD-MM-YYYY" and have successfully validated it using this code: var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ; if(!startDate.match(dateFormat)){ alert("'Start Dat ...

Bypass the save as dialogue box and initiate automatic file download without interruption

Working on an Angular 1 web application, I am utilizing the HTML download Attribute. Using the code snippet below: <a href="/images/myw3schoolsimage.jpg" download>, I am enabling users to download presented data as an Excel spreadsheet. My goal i ...

Extract content within Python pre tags

A Python code snippet is being used to extract content between PRE tags: s = br.open(base_url+str(string)) u = br.geturl() seq = br.open(u) blat = BeautifulSoup(seq) for res in blat.find('pre').findChildren(): seq = res.string ...

A table featuring two tbody sections positioned side by side within the table structure, with the thead located at the top

My goal is to design an HTML table layout resembling the following: Left part | Right part | Remove row? ------------------------------------------- 1 [input] [input] Y/N 2 [input] [input] Y/N 3 [input] [inpu ...

Using Django Template Variables in JavaScript Functions

Within one of my templates, there is a for loop that iterates over all the items. Whenever a user likes or dislikes an item, it should trigger a function in my code. I successfully set up the button's HTML like this: <button onclick='update_li ...

Refreshing a webpage to accurately display changes made in a CRUD application without the need for a hard reset

My to-do app is almost fully functional - I can create items, mark them as completed, and delete them using a delete button. However, there's one issue: when I delete an item, the page doesn't update in real-time. I have to manually refresh the p ...

Trouble with the JQuery event listener onchange()

On my webpage, I've set up a drop-down list and a text-box in the following HTML code: <table> <tr> <td>Group Name: </td> <td><%= Html.Dr ...

What is the best way to include a .AVI file in an HTML document?

I have come across some examples of .AVI in HTML on the internet. However, my page seems to be having issues. It displays fine in Chrome on my computer. But in Internet Explorer, there is a bar at the top and the videos appear blank afterwards. It ...

Tips for preventing recursion when utilizing scrollIntoView() in a scroll event handler

My goal is to break down my website into screen-sized sections that automatically scroll to the next section when a user begins scrolling. I attempted to accomplish this by using the following code: $(window).scroll(function() { getElementToScroll().s ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

What is the best way to ensure that text fields remain hidden upon page load until the appropriate drop down option is chosen?

Is it possible to initially hide text fields and only reveal them when a specific drop down option is selected? The current JavaScript code somewhat achieves this, but I would like the input fields to remain hidden by default. <script language=" ...

Working with the visibility of a button using JavaScript

My goal is to toggle the visibility of a button using JavaScript. Initially, on page load, the button should be hidden. function hideButton(){ var x = document.getElementById('myDIV'); x.style.display = 'none'; } The visibilit ...

What is the most effective approach to seamlessly conceal and reveal a button with the assistance

I have two buttons, one for play and one for pause. <td> <?php if($service['ue_status'] == "RUNNING"){ $hideMe = 'd-none'; } ?> <a href="#" class="btn btn-warning ...