Creating a pros and cons form for users using jQuery involves dynamically checking and updating the input values to ensure that no

When a new value is entered into the input box in this code, it will add and replace it for all P's tag. The desired change is to create a div with .pros-print class after each other, where the content of the P tags is equal to the new input value when a new value is added to the input and the add button is clicked.

  $(document).ready(function () {
      var prosinput = $("#pros-input").val();
      $("#basic-addon1").click(function () { 
        $(".right-side-pros").append('<div class="pros-print d-flex align-items-center"><i class="fa-light fa-plus-large c-green me-2"></i><p></p><i class="fa-thin fa-trash-can ms-auto c-red me-2"></i></div>');
        $(".pros-print").children("p").text($("#pros-input").val());
      });
      
    });
.pros-cons-inputs-wrapper{
margin-top: 100px; 
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a2825253e393e382b3a0a7f647b6479">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<div class="pros-cons-inputs-wrapper input-group mb-3 d-flex justify-content-around">

 <input 
 type="text" 
 name="user-pros" 
 id="pros-input"
 class="form-control"
 placeholder="pros" 
 aria-label="Username"
 aria-describedby="basic-addon1">
 
 <button 
 class="input-group-text me-3"
 id="basic-addon1">add
 </button>
 </div>
 
 <div class="d-flex">
  <div class="right-side-pros">
     <div class="pros-print d-flex align-items-center ">
        <p class="pros-txt"> a </p>
     </div>
  </div>
</div>
              
              
              
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
 
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b4944445f585f594a5b6b1e051a0518">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

Answer №1

$(document).ready(function() {
  var inputPros = $("#pros-input").val();
  $("#basic-addon1").click(function() {
    inputPros = $("#pros-input").val();
    var alreadyExists = $(".pros-print p:contains('" + inputPros + "')").length > 0;
    if (alreadyExists) return false;
    $(".right-side-pros").append('<div class="pros-print d-flex align-items-center"><i class="fa-light fa-plus-large c-green me-2"></i><p>' + inputPros + '</p><i class="fa-thin fa-trash-can ms-auto c-red me-2"></i></div>');
  });

});

Answer №2

Adjust your approach slightly

$(document).ready(function () {
      var prosinput = $("#pros-input").val();
      $("#basic-addon1").click(function () { 
        $(".right-side-pros").append('<div class="pros-print d-flex align-items-center"><i class="fa-light fa-plus-large c-green me-2"></i><p>'+$("#pros-input").val()+'</p><i class="fa-thin fa-trash-can ms-auto c-red me-2"></i></div>');
      });
});

To prevent duplicate entries

var prosarr = [];
    
$(document).ready(function () {
     var prosinput = $("#pros-input").val();
     $("#basic-addon1").click(function () { 
          let prosVal = $("#pros-input").val();
          if(prosarr.includes(prosVal)){
          return;
          }
          prosarr.push(prosVal);
          $(".right-side-pros").append('<div class="pros-print d-flex align-items-center"><i class="fa-light fa-plus-large c-green me-2"></i><p>'+prosVal+'</p><i class="fa-thin fa-trash-can ms-auto c-red me-2"></i></div>');
     });
});

Trigger button click event on keydown and clear input after successful addition

var prosarr = [];
    
$(document).ready(function () {

    $("#pros-input").keydown(function(event){
        let keycode = (event.keyCode ? event.keyCode : event.which);
        if(keycode == '13') {
            $( "#basic-addon1" ).trigger( "click" );
        }
    });

     var prosinput = $("#pros-input").val();
     $("#basic-addon1").click(function () { 
          let prosVal = $("#pros-input").val();
          if(prosarr.includes(prosVal)){
          return;
          }
          prosarr.push(prosVal);
          $(".right-side-pros").append('<div class="pros-print d-flex align-items-center"><i class="fa-light fa-plus-large c-green me-2"></i><p>'+prosVal+'</p><i class="fa-thin fa-trash-can ms-auto c-red me-2"></i></div>');
         $("#pros-input").val("");
    });
});

Delete div and value from array on .fa-trash-can click

var prosarr = [];

$(document).ready(function () {
         
     $(".right-side-pros").on("click", ".fa-trash-can", function (event) {
        let parentVal = $(this).siblings('p').first().html();
        prosarr = prosarr.filter(function(item) {
                return item !== parentVal
                });
        $(this).parent().remove();
    });

    $("#pros-input").keydown(function(event){
        let keycode = (event.keyCode ? event.keyCode : event.which);
        if(keycode == '13') {
            $( "#basic-addon1" ).trigger( "click" );
        }
    });

     var prosinput = $("#pros-input").val();
     $("#basic-addon1").click(function () { 
          let prosVal = $("#pros-input").val();
          if(prosarr.includes(prosVal)){
          return;
          }
          prosarr.push(prosVal);
          $(".right-side-pros").append('<div class="pros-print d-flex align-items-center"><i class="fa-light fa-plus-large c-green me-2"></i><p>'+prosVal+'</p><i class="fa-thin fa-trash-can ms-auto c-red me-2"></i></div>');
         $("#pros-input").val("");
    });
});

Alternative method if you prefer not to use array (suggested by @Silvia Tacher )

$(document).ready(function () {
         
     $(".right-side-pros").on("click", ".fa-trash-can", function (event) {
        $(this).parent().remove();
    });

    $("#pros-input").keydown(function(event){
        let keycode = (event.keyCode ? event.keyCode : event.which);
        if(keycode == '13') {
            $( "#basic-addon1" ).trigger( "click" );
        }
    });

     var prosinput = $("#pros-input").val();
     $("#basic-addon1").click(function () { 

          let prosVal = $("#pros-input").val();
          let exists_already = $(".pros-print p:contains('" + prosVal + "')").length > 0;
          if (exists_already) return false;

          $(".right-side-pros").append('<div class="pros-print d-flex align-items-center"><i class="fa-light fa-plus-large c-green me-2"></i><p>'+prosVal+'</p><i class="fa-thin fa-trash-can ms-auto c-red me-2"></i></div>');
         $("#pros-input").val("");
    });
});

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

`A mistake occurred while building in the package.json file`

While attempting to run all build processes by using the command npm run build:css, I encountered an error indicated below. Even after running npm cache clean --force, the issue remains unresolved. https://i.sstatic.net/4edDo.png npm ERR! code ELIFECYCLE ...

Safari's problem with auto-filling forms

I am in the process of designing a payment form. I need to have the fields for credit card number and its expiry date set to autofill. The Chrome browser is functioning correctly, but Safari is not recognizing the expiry_date field for autofill. Below are ...

Tips for managing a date picker with JavaScript using the Selenium WebDriver

I have been attempting to scrape a travel website using Selenium Webdriver and Python. While I have successfully set the destination (destino) and place of origin (origem), I am encountering difficulties when trying to select a date. I understand that Ja ...

Dividers afloat - expanding current script with multiple additions

I am currently utilizing this website as a hub for showcasing my various web projects. The jsfiddle code provided in response to this particular inquiry is exactly what I need, however, I am unsure of how to have multiple divs moving simultaneously acros ...

What are the best practices for utilizing ESM only npm packages alongside traditional npm packages within a single JavaScript file?

Hey there, I'm fairly new to web development and I encountered a problem when trying to require two packages, franc and langs, in my index.js file. It turns out that franc is now an ESM only package, requiring me to import it and mention type:module i ...

Struggling with sending intricate model to controller via ajax request

I've encountered an issue where my model is not updating properly when I click a button. Despite logging the data in the razor file and confirming that it's correct, the controller method receives an empty model. Below is the onclick method bein ...

What is the best way to handle a RadioButton's change event using jQuery within a SharePoint WebPart?

After much exploration on a desolate promontory and sending out filaments from within myself, I reached this point. Following the steps outlined here, I added the following code to the end of the WebPage's *.ascx file: <script> $(document).read ...

Tips for preventing circular dependencies in JavaScript/TypeScript

How can one effectively avoid circular dependencies? This issue has been encountered in JavaScript, but it can also arise in other programming languages. For instance, there is a module called translationService.ts where upon changing the locale, settings ...

Exploring the interaction between Bootstrap and AngularJS in creating unique menu functionality

UPDATE: added JSFiddle link I am currently working on creating a dynamic menu or set of options that will be populated based on server requests. The data structure I am dealing with is as follows (some unnecessary data has been omitted): { "name" : ...

Issue with Tailwind classes not applying correctly upon refreshing the page in production settings

Challenge Description: Encountering an issue with my nextjs project that utilizes tailwindcss. The login page initially loads with the required classes for the UI, but upon refreshing the page, the classes disappear from the DOM, causing a broken UI. Her ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

prompting the JavaScript hangman game to identify the letters in the "selected word"

Currently, I am on a mission to teach myself Javascript and have taken on the challenge of creating a simple hangman game. This type of project is commonly used in interviews or tests, so it seemed like a great opportunity for practice. My approach involve ...

When I toggle the password visibility and then click the submit button, it functions correctly

I am currently working on an application that combines Vue with Laravel. One of the Vue components I created is called UsersCreate. This component is responsible for gathering user data and sending it to a Laravel controller using axios. However, I have en ...

Scrolling is disabled when using a full-screen background

My current issue involves a full screen background that is functioning properly when the window is resized, but it has caused a problem where scrolling is disabled when the page is longer than the window size. The content just gets cut off. Is there a way ...

Customize the default getstream component styles in a NextJS Component

Is there a way to customize the CSS of getStream.io components using custom CSS? I have created a component as shown below and now I want to override the styles for various classes of its components. Following the instructions in this README file, I impor ...

Disrupting a Program Operation

We are utilizing the gauge Google Chart applet to visually track the failure rates of message transfers on a SOAP interface via AJAX. My goal is to make the page's background flash red and white when the failure rate reaches 50% or higher, and remain ...

Utilize a Dropdown Menu to Retrieve Information from a Database and Display the Results on Either the Current Page or a Separate Page

My PHP page includes a code snippet that generates an HTML table: <table> <thead> <tr> <th class="wheniwant">Date</th> <th class="wheniwant">Income Amount</th> <t ...

Unable to display values in Fusion Charts zoomline chart using the showValues chart property

I'm struggling to figure out how to display the data plot values with showValues: '1' in a zoomline chart using Fusion Charts. You can see and test it on this fiddle: http://jsfiddle.net/60oeahc1/4/ Is there a way to make this feature work ...

Transferring information back and forth between jQuery and Servlet

Looking for a solution to extract data from an HTML form and send it to a servlet? Here's a sample HTML form along with the script: <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script> <s ...

"Trouble in Transmitting: Node.js Fails to

As a beginner in programming, I am currently following a tutorial to enhance my skills. I've encountered a roadblock and I can't seem to successfully post new entries using the code. I'm struggling to identify what I might be missing here. ...