Using Jquery to transfer text from a form to a DIV and ensuring the final character is verified

Users can input their name on my HTML form, which will then be displayed in a DIV as part of a book title.

The book title includes apostrophes (e.g. Amy's Holiday Album).

However, if the user's name ends with an S, I do not want the apostrophe s to be included (e.g. Chris' Holiday Album instead of Chris's Holiday Album).

This should only happen if the form has a class of apostrophe. Otherwise, the name should be copied without any apostrophes or 's' added.

I attempted to use slice() along with an if statement to achieve this, but it did not work as expected.

Here is my JSFiddle link

Below is the HTML code:

<div><b class="title"></b> Holiday Album</div>

And here is the Jquery code (1.8.3):

$(document).ready(function() {

$('.name').keyup(function() {


    var finalname = text($(this).val());

    var lastChar = finalname.slice(-1);

    var finaltitle;


    if ($(".apostrophe")[0]) {


        if (lastChar == 's') {
            finaltitle = finalname + "'";
        }


        else {
            finaltitle = finalname + "'s";
        }


        $('.title').text(finaltitle);
    }

    else {
        $('.title').text(finalname);

    }

}); 

});

Answer №1

A text method is unnecessary for

let finalname = $(this).val();

View the example here

Answer №2

Opt for

let finalname = $(this).val();

over

let finalname = text($(this).val());

Answer №3

Simple Version

$(document).ready(function() {

    //Function triggers when user begins typing:
    $('.name.apostrophe').keyup(function() {
        if (this.value.indexOf("'s") != -1 )  {
            $('.title').text(this.value.replace(/'s/g, "'"));
        } else {
             $('.title').text(this.value)
        }
    }); /* Capture Personalized Message */

});

This script will replace every instance of 's with just '.

I hope this explanation is helpful!.

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

php - assign image to picture through file location

My webpage features an img element with the following code: <img id=".."class=".." src="setPhoto/second_photo.php"> In the source attribute, I have linked to a .php file: <?php $id = $_SESSION['u_id']; $sql = "SELECT * FROM users WHER ...

Limiting the number of lines in a TextArea using PHP Validation

I came across an incredible code snippet on this thread However, I have concerns about its vulnerability if someone manipulates the form using firebug or disables JavaScript. I'm seeking advice on how to implement server-side validation for this func ...

Is it possible to create a THREE.js form using a sequence of outlines?

Consider the scenario where three two-dimensional shapes are present. To keep things simple, let's envision them all as circles: Is there a method in THREE.js that allows for these shapes to be 'stacked' on top of each other vertically, res ...

Storing Tags with jQuery Tag-it: A guide to saving user inputted tags in an object

Recently stumbled upon a fantastic plugin called tagit, and now I'm looking for a way to extract tag values from it and convert them into an object. Any assistance on this matter would be greatly welcomed! ...

Transferring information from various HTML forms using JQuery's ajax functionality

Hello there! I have recently started learning how to use jQuery AJAX for file uploads. Currently, I am working with a simple HTML form and including JavaScript/jQuery code within it to make an AJAX request. <!DOCTYPE HTML> <html> <head> ...

Incorporate a personalized style into the wysihtml5 text editor

Is there a way for me to insert a button that applies a custom class of my choice? I haven't been able to find this feature in the documentation, even though it's a commonly requested one. Here's an example of what I'm looking for: If ...

Unusual actions observed with that particular button

Currently, I am working on creating a pomodoro clock using Codepen. While I acknowledge that my code isn't flawless yet, I have encountered a peculiar behavior with the Start button. When I click on it once, the timer starts as expected. However, if I ...

Retrieve the value of the chosen option from a dropdown menu that adjusts dynamically within

I have a query that involves dynamically adding rows to a table for data insertion. A particular <td> element houses a dropdown menu, and I need to extract the selected value from this dropdown in order to make an AJAX call back to a PHP script that ...

Enhancing JavaScript Asynchronous Programming with EventLoop and async/await

Exploring the intricacies of how JavaScript processes asynchronous methods led me to dive into async/await. In an effort to gain a complete understanding, I crafted the following example: async function first() { console.log(9); await Promise.resolv ...

What steps can I take to prompt this function to modify the value of my input?

After recently delving into the world of JavaScript, I decided to create a background color generator that randomly changes when a button is clicked. This simple project involves two input fields (color1 & color2) which receive random values upon clicking ...

What is the best way to retrieve calendar events using Microsoft Graph and NodeJS based on the calendar name?

Is there a way to condense these two API calls into one? Currently, this code uses microsoft-graph-client to first retrieve the ID of a specific calendar and then fetch the events from that calendar. I am looking for a method to combine these into a single ...

Leveraging jQuery for Custom Form Styling

.I prefer to utilize personalized form elements in my forms. <fieldset> <legend id="Cities">Urban Areas</legend> <div class="legend-underline"></div> <div class="filters" id="Cities-filters"> <div> < ...

Tips on avoiding the repetition of jQuery functions in AJAX responses and ensuring the effectiveness of jQuery features

My HTML form initially contains only one <div>. I am using an AJAX function to append more <div> elements dynamically. However, the JavaScript functionality that works on the static content upon page load does not work for the dynamically added ...

invoke a JavaScript function within the $(document).ready(function() {}) event handler

I am trying to execute an ajax function both on page load and when there is a change, here is the code snippet I am using: function fetchData(ID) { alert('function called'); $.ajax( { type: 'POST', url: &a ...

CSS for a Div with a Subtle Curve at the Bottom

Is there a way to achieve this specific shape using CSS? I attempted to use the following resources, but they didn't provide me with the desired outcome. Curved border with stroke in pure CSS? http://jsfiddle.net/ECHWb/ .banner-img{ height: 661p ...

6 Steps to Extract Data from a POST Request Using JavaScript

I have a form that includes a text field and a select field. When the form is submitted, I am posting it. Can someone guide me on how to extract the form data on the server using JavaScript? <form id="createGameForm" action="/createGame" method="post" ...

Python scripts are unable to perform file uploads through an HTTP form, unlike PHP scripts which are compatible

Currently, I am working on a Python project where I need to upload a text file through HTTP to my server. Initially, I used an HTTP form for convenience and the upload process was successful. However, now I want to automate the file selection process by ha ...

Learn the process of creating various themes with Tailwind CSS

When exploring Tailwind CSS, it appears that specific colors need to be specified in classes like this: <div class="bg-yellow-200 dark:bg-gray-800"></div> However, I am interested in offering 10 different themes for users to choose f ...

Ways to retrieve the data within the tinymce text editor for seamless submission through a form

I am a beginner with TinyMCE and I am working on integrating the editor into my Laravel project. So far, I have managed to get it up and running, but I am struggling with retrieving the content from the editor and passing it to the controller for database ...

Most Effective Method for Switching CSS Style Height from "0" to "auto"

After coming across a question with no answer that suited my needs, I decided to share the solution I created. In my case, I had a hidden generated list on a page which was initially set with a CSS height of "0" and then expanded upon clicking by transit ...