How to use javascript/html to differentiate between male and female names?

I've developed a random name generator code that is powered by both CSS and JavaScript. Currently, the code allows me to input any name - regardless of gender - press the generate button, and receive a randomly generated first and last name. However, I now wish to have distinct buttons for male, female, and unisex names.

In my attempts to achieve this, I created separate div IDs for male and female names, duplicated the JavaScript section, and modified the code segments to 'femalename' and 'malename'. Unfortunately, this approach compromised the formatting and caused both divs to generate a name whenever any of the generate buttons were clicked.

<!DOCTYPE HTML>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>Random Name Generator</title>
<meta charset='utf-8' />

<style type='text/css'>

    #name {
    color : #444;
font : bold 51px times, Times New Roman, times-roman, georgia, serif;
letter-spacing : -2px;
line-height : 44px;
text-align : center;
text-transform: uppercase;
}

#refresh {
font : normal 11px Gill Sans, Verdana;
letter-spacing : 2px;
line-height : 14px;
text-align : center;
text-transform : uppercase;
}

a {
    color : #666;
}

a:hover {
    color : #999;
}

</style>
</head>

<body>
<script type='text/javascript'>
first = ['abbie ', 'abby ', 'abu ', 'alec ', 'alek ', 'aleksander ', 'alex ', 'alexander ', 'aaron ', 'adam ', 'andrew ', 'anthony ', 'archer ', 'arthur ', 'austin '];
last = ['williamson', 'davidson', 'edwards', 'ingram', 'olsen'];

name = "";
length = Math.floor(Math.random()) + 1; 
for (i = 0; i < length; i++)
name += (first[Math.floor(Math.random()*first.length)]
 + last[Math.floor(Math.random()*last.length)]);
name = name.charAt(0) + name.slice(1);
document.write("<p id='name'>" + name + "</p>"); 
</script>
<p id="refresh">
<a href='#' onclick='window.location.reload()'>Generate a New One</a>
</p>
</body>
</html>

Answer №1

Do you approve of this?

const
  // Identifies HTML elements
  buttons = document.getElementsByClassName("btns"),
  display = document.getElementById("display"),

  // Identifies arrays of names
  girls = ['abbie', 'abby'],
  boys = ['abu', 'alec', 'arthur'],
  whatevs = ['alex', 'archer',  'austin'],
  lastNames = ['williamson', 'davidson', 'edwards', 'ingram', 'olsen'];

// Runs the makeName function when a button is clicked
document.addEventListener("click", makeName);

// Defines the makeName function (`event` is the triggering click event)
function makeName(event){
  
  // Remembers what was clicked
  const clickedThing = event.target;
  
  // Declares a variable to hold the appropriate array
  let chosenList;
  
  // Makes sure the click was on a button before proceeding
  if(clickedThing.classList.contains("btns")){
  
    // Sets the appropriate list depending on which button was clicked
    if(clickedThing.value == "girl"){ chosenList = girls; }
    else if(clickedThing.value == "boy"){ chosenList = boys; }
    else { chosenList = whatevs; }

    // Identifies names (retrieved using the `randFrom` function)
    const
      first = randFrom(chosenList), // Chooses a name from the specified list
      last = randFrom(lastNames), // Chooses a lastName
      fullName = `${first} ${last}`; // Puts them together

    // Shows the result on the page
    display.innerHTML = fullName;
  }
}

// Gets a random element from an array
function randFrom(array){
  const index = Math.floor(Math.random() * array.length);
  return array[index];
}
#display {
  color: #444;
  font: bold 51px times, Times New Roman, times-roman, georgia, serif;
  letter-spacing: -2px;
  line-height: 44px;
  text-align: center;
  text-transform: uppercase;
}
<button class="btns" value="girl">girl</button>
<button class="btns" value="boy">boy</button>
<button class="btns" value="whatevs">whatevs</button>

<p id="display"></p>

Answer №2

To enhance the function, I would modify it to include a gender parameter within the HTML and ensure that the function runs upon loading.

Additionally, here is an illustration featuring an "any gender" choice: https://codepen.io/kboedges/pen/qeXmqK?editors=1111

const maleFirst = ["abu", "alec", "alek"];
const femaleFirst = ["abbie", "abby", "katie", "leah"];
const last = ["williamson", "davidson", "edwards", "ingram", "olsen"];

// Function
function generateName(gender) {
  const randomLast = last[Math.floor(Math.random() * last.length)];
  const randomMaleName = `${maleFirst[Math.floor(Math.random() * maleFirst.length)]} ${randomLast}`;
  const randomFemaleName = `${femaleFirst[Math.floor(Math.random() * femaleFirst.length)]} ${randomLast}`;
  
  // Insert into HTML
  const p = document.getElementById('name');
  p.innerHTML = gender === 'female' ? randomFemaleName : randomMaleName;
}

// On first run
generateName('male');
#name {
  color: #444;
  font: bold 51px times, Times New Roman, times-roman, georgia, serif;
  letter-spacing: -2px;
  line-height: 44px;
  text-align: center;
  text-transform: uppercase;
}

#refresh {
  font: normal 11px Gill Sans, Verdana;
  letter-spacing: 2px;
  line-height: 14px;
  text-align: center;
  text-transform: uppercase;
}

a {
  color: #666;
}

a:hover {
  color: #999;
}
<p id='name'></p>
<p id="refresh">Generate a...
  <a href='#' onclick="generateName('female')">female name</a>
  <a href='#' onclick="generateName('male')">male name</a>
</p>

Answer №3

It seems like you need two steps to create and show names in different containers.

<!DOCTYPE HTML>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <title>Unique Name Generator</title>
    <meta charset='utf-8' />

    <style type='text/css'>

        .name {
        color : #444;
    font : bold 51px times, Times New Roman, times-roman, georgia, serif;
    letter-spacing : -2px;
    line-height : 44px;
    text-align : center;
    text-transform: uppercase;
    }
    
    .refresh {
    font : normal 11px Gill Sans, Verdana;
    letter-spacing : 2px;
    line-height : 14px;
    text-align : center;
    text-transform : uppercase;
    }
    
    a {
        color : #666;
    }
    
    a:hover {
        color : #999;
    }
    
    </style>
</head>

<body>
<p id="firstName" class="name"></p>
    <p class="refresh">
<a href='#' onclick='generateName("firstName")'>create a first name</a>
</p>
    <p id="secondName" class="name"></p>
    <p class="refresh">
        <a href='#' onclick='generateName("secondName")'>create a second name</a>
    </p>
    <script type='text/javascript'>
        function generateName(containerId) {
            first = ['abbie ', 'abby ', 'abu ', 'alec ', 'alek ', 'aleksander ', 'alex ', 'alexander ', 'aaron ', 'adam ', 'andrew ', 'anthony ', 'archer ', 'arthur ', 'austin '];
            last = ['williamson', 'davidson', 'edwards', 'ingram', 'olsen'];

            name = "";
            length = Math.floor(Math.random()) + 1; 
            for (i = 0; i < length; i++)
                name += (first[Math.floor(Math.random()*first.length)] + last[Math.floor(Math.random()*last.length)]);
            name = name.charAt(0) + name.slice(1);
            document.getElementById(containerId).innerHTML = name;
            
        }        
    </script>

</body>
</html>

Answer №4

Presented here is a solution that utilizes a single array for the first names, structured as an array of objects.

I made extensive use of ES6 'fat-arrow' functions and aimed to create functions that are highly reusable. It turned out to be quite an enjoyable experience! ;)

const resultsPane = document.querySelector('.random-name-results ul'),
  generateBtn = document.querySelector('.refresh-random-name');

const filterByGender = gender => name => gender.includes(name.gender);

const getRandom = arr => arr[Math.floor(Math.random() * arr.length)];

const findName = (gender) => {
  const firstNames = [
    {
      name: 'abigail',
      gender: 'female',
      variations: ['abigail', 'abbie', 'abby']
    },
    {
      name: 'abu',
      gender: 'neutral',
      variations: ['abu']
    }, 
    // Additional names removed for brevity
  ];
  const last = ['williamson', 'davidson', 'edwards', 'ingram', 'olsen'];

  const findGender = filterByGender(gender),
    filteredList = firstNames.filter(findGender),
    firstName = getRandom(getRandom(filteredList).variations),
    lastName = getRandom(last);
  return `${firstName} ${lastName}`
}

generateBtn.addEventListener("click", function(){
  const gender = document.querySelector("input[name='gender']:checked").value;
  let name = findName(gender),
      nameEl = document.createElement('li');
  nameEl.innerText = name;
  resultsPane.innerText = "";
  resultsPane.appendChild(nameEl);
})
.random-name-container {
  width: 96vw;
  height: 95vh;
  border: 2px solid palevioletred;
  border-radius: 2vmin;
  padding: .5vmin;
  display: grid;
  grid-template-areas: 'head head'
                       'actions results'
                       'actions foot';
  grid-template-rows: 8vh 1fr 30px;
  grid-template-columns: 30vw 1fr;
  overflow: scroll;
  }

.random-name-container header {
  grid-area: head;
  background-color: bisque;
}

header h1 {
  margin: auto auto 0 auto;
}
header p {
  margin: 0;
}

.random-name-container footer {
  grid-area: foot;
  background-color: bisque;
}

.random-name-results {
  grid-area: results;
  background-color: gainsboro;
  width: 100%;
  height: 100%;

}
  .random-name-actions {
    display: flex;
    grid-area: actions;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .random-name-actions > * {
    width: 95%;
  }

  .random-name-actions fieldset > * {
    display: block;
  }
  <article class='random-name-container'>
    <header>
      <h1>Random Name Generator</h1>
      <p>Choose your preferred gender, and give it a spin!</p>
    </header>
    <section class='random-name-results'>
      <ul></ul>
    </section>
    <section class='random-name-actions'>
      <fieldset>
        <label><input type='radio' name='gender' value='female neutral' checked />Female</label>
        <label><input type='radio' name='gender' value='male neutral' />Male</label>
        <label><input type='radio' name='gender' value='neutral' />Gender-neutral</label>
      </fieldset>

<input type='button' class='refresh-random-name btn' value='Generate another!'>
    </section>
    <footer>The name game</footer>
  </article>

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

Stop the body from scrolling when dialog is open on a mobile screen

I am encountering an issue on a mobile screen where I am displaying a dialog that is longer than the screen size, causing it to scroll. The problem arises when scrolling past the bottom of the dialog (I am utilizing Bootstrap 3) as instead of stopping, it ...

Executing an HTTP POST request without properly encoding a specific parameter

I am attempting to communicate with an unauthorized third-party API using Node and the request module. Below is the code that generates the request: request.post( { url: url, headers: MY_HEADERS_HERE, followAllR ...

Finding the Modular Reciprocal with JavaScript

I am attempting to find the value of d by solving the equation ed ≡ 1 mod((p-1)(q-1)), similar to the RSA algorithm. Given e = 5 and (p-1)*(q-1) = 249996 I have experimented with various Javascript code snippets, such as: function calculateModInverse( ...

Personalize the md-tab component in Angular 2

I'm encountering an issue with styling the md-tab component in Angular 2. While I understand that Angular 2 Materials is currently under development, I am wondering if there is a way to customize it, such as removing the bottom-radius. Below is an exa ...

A guide to selecting the bookmark with a URL that is on a currently opened page

To gain a clearer understanding of my goal, follow these steps: Open the Chrome Browser and go to a URL, such as https://www.google.com. Once the page loads, locate and click on the bookmark labeled "ABC", which contains the URL ({window.open('/ ...

Issue with Angular Script not functioning upon reopening the page

I recently completed my first website, which can be found at Despite my efforts, I've encountered an issue that has me stumped. When you navigate to the certificate page, you should be able to input your name onto the certificate. However, if you sw ...

Guide on altering the background color of a table row depending on the data in its cells with the help of AngularJS

I am looking to dynamically change the background color of a row based on specific cell data. If the first four characters in a table cell match a certain value, I want the entire row to change its color to red. Currently, my code changes the row color ba ...

Change the price directly without having to click on the text field

Our Magento marketplace site is currently utilizing the code below for updating prices. However, we are looking to make the price field editable without requiring a click on the textfield. This means that users should be able to edit the price directly wi ...

HTML Data Service for WCF

Is there a way for users to easily display a list of their publications on their websites? I'm considering pulling data from a SSRS database and using a WCF Data Service. However, the WCF Data Service only outputs ATOM or JSON data. Is this the right ...

Unpack an array with entries and an iterator

I am working with an array of objects, each containing the same properties. My goal is to create a function that will return an array of arrays, where each inner array holds values based on the property names of the objects. Here is an example input: inp ...

How to troubleshoot syntax errors when using the delete function in Three.js within Eclipse

When using the Javascript Library Three.js, it is important to note that the delete keyword can be used as an object property. While this is valid under ECMAScript 5 standards, Eclipse currently only supports ECMA 3. As stated in the Mozilla reference, re ...

Generate a structured table display using the JSON information

How can I convert the following JSON data into a tabular view? {"data_report":[{"data":[1,2,0,3],"label":"Test1","backgroundColor":"blue"}, {"data":[3,4,2,5],"label":"test2","backgroundColor":"#a3eaae"}, {"data":[2,3,1,4],"label":" ...

There was a problem with the ajax request

Attempting to make an ajax request in my SpringMVC project has been challenging. $.ajax({ contentType : 'application/json; charset=utf-8', type : 'get', url : 'order/get/'+i, dataType : 'json', ...

AngularJS: ng-show causing flickering issue upon page refresh

Recently, I encountered an issue with my code snippet: <body> <ng-view></ng-view> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script> <script src="http://ajax.googleapis.com/ajax/ ...

The checkbox linked to a Vector layer in Openlayers 3 seems to have no effect on its visibility

Help me debug my code where I am attempting to connect a checkbox to a vector layer's 'visible' property. I can't seem to figure out what's wrong, can you spot the error? Interestingly, this code successfully works for ol.layer.Ti ...

Exploring the process of performing an AJAX JQuery HTTP request using JavaScript and PHP on the server side - any tips?

Greetings! I have developed a web application using HTML, CSS, and JavaScript. To enhance functionality, I have integrated Bootstrap and jQuery into the project. The application comprises both client-side and server-side components. Let's take a look ...

Utilizing Tailwind's layer component directives on a Remix React component

I've been experimenting with creating Tailwind directives in my Remix project. However, when I define CSS classes under the components layer of tailwind.css and apply them to my React components' className(s), the styles don't seem to be tak ...

Menu with hover functionality in JQuery that functions as a standard menu even when JavaScript is disabled in the browser

Is it possible to modify this code so that the hover point links' images do not appear if the browser has JavaScript disabled? And can the links function like a regular hover point even when JavaScript is disabled? <script type="text/javascript" s ...

Top and bottom fieldset legends in Bootstrap 4

Looking for suggestions on how to include legend text on the bottom border in bootstrap 4. I attempted to use position and margin, but it didn't work. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.mi ...

Leveraging the power of react routes for efficient navigation within a react-based application

I am currently facing an issue with setting up routes for a basic react application using react-router. The given routes don't seem to match and the switch defaults to displaying the 404 page. Below is the code for the routes: import { BrowserRout ...