Assist in troubleshooting and pinpointing the solution to this issue

function generateRandomString(length) {
  var result = "";
  var characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
  var charactersLength = characters.length;
  for (var i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

var input = document.getElementById("length");
console.log(generateRandomString(input));
<html>
  <body>
    <div>
      Enter the length of character:
      <input type="text" id="length" />
      <button onclick="generateRandomString(5)">Submit</button>
      <p id="result"></p>
    </div>
    <script type="text/javascript" src="app/index.js"></script>
  </body>
</html>

Please help me find the error. I cannot figure out why I'm not getting the output I expected. My goal is to display random text with a specific length based on the value entered in an HTML text field.

Answer №1

To address the issue of not displaying random text, I have made some updates to your code. Initially, I retrieve input data using

var num = +document.getElementById("num").value;
, where the plus sign is used for conversion into an integer. The reason why your code was not showing anything is because you had not included any code to display the result. To rectify this, you can use
document.getElementById("result").innerHTML = result
to show the output in a division element.

function stringGen(num) {
  var result = "";
  var alpha =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
  var alpha1 = alpha.length;
  for (var i = 0; i < num; i++) {
    result += alpha.charAt(Math.floor(Math.random() * alpha1));
  }
  return result;

}

function showResult(){
  var num = +document.getElementById("num").value;
  document.getElementById("result").innerHTML = stringGen(num);
 }
<div>
      Enter the length of character:
      <input type="text" id="num" />
      <button onclick="showResult()">submit</button>
      <p id="result"></p>
    </div>

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

Accessing PHP output within Jquery

Even though I know PHP is a server-side script and JavaScript is client-side, I encountered an issue. I struggled to bypass browser security when making an AJAX request to another domain. Feeling lost, I decided to turn to PHP for help. The challenge I f ...

Updating a .txt file using JavaScript

Is there a method on the client side to add text to a file called text.txt using JavaScript? In Python: f = open("text.txt","w") f.write("Hello World") f.close() The code snippet above would input "Hello World" into the text file. I am looking for a sim ...

I am experimenting with an express middleware that can either return next() or next("route")

After developing a middleware function that returns next() if a route's parameters are defined by queryItems, I came across a useful tool called node-mocks-http. However, it does not fake the next object. This led me to explore how this can be achieve ...

Is it possible to show an image without altering the Box dimensions?

Hi there, I am currently working on designing a footer and I have encountered an issue. I want to add an image in a specific position, but when I do so, it affects the size of the box. I was wondering if there is a way to set the image as a background or b ...

Updating the default value of a MUI TextField: Step-by-step guide

I am in the final stages of completing my form, but I have encountered an issue when trying to display the current user's name in the defaultValue variable of the TextField from MUI. If the value starts as ""/null, or essentially empty, the ...

Is there a way to convert the existing JavaScript code for a hyperlink so that it can be triggered by clicking a button instead?

I have a JavaScript code that works well when the hyperlink below is clicked: <a href="delete_event.php?event_id=110" onClick="return ConfirmDelete()" class="list-group-item">Delete Event</a> <script> function ConfirmDelete() { var ans ...

Is there a way to automatically close a created div by clicking anywhere outside of it?

I'm facing an issue with a dynamically created div that I want to close by clicking outside of it. However, when I try to achieve this functionality, the div closes immediately as soon as it is opened. closediv(); } function closediv() { d ...

What is the best way to dynamically pass JSON object values to PHP?

Greetings, I am new to JSON and Ajax. Although my question may seem trivial, I believe that even the simplest inquiries are crucial in the learning process. My dilemma involves passing two parameters (giorno and periodo) via Ajax: For example: 'gior ...

Order the variables in the dropdown menu based on the PHP variables

I currently have a select list that allows me to choose between two options: Popularity and Recently Ordered. My goal is to filter the objects on the page based on these attributes, connecting each option to its respective function in my dataloader.php fi ...

Ways to forward a webpage once validation has been completed

I have a login form that is being validated using jQuery/Ajax to receive a JSON response. The form calls a PHP page called add-data.php. Upon successful validation, I want to redirect to another page after displaying the message Successfully logged!: if ...

vue-dropzone fails to create thumbnails when a file is added

I am facing an issue where I want to upload files that are already stored on my server to the Dropzone. Despite searching extensively through both vue-dropzone and regular dropzone documentation, as well as various GitHub issues for solutions, I have not b ...

Choosing from a variety of tr elements

I'm working with a table in HTML that has about 100 rows. I would like to apply different colors to specific groups of rows, such as making rows 1-10 red and rows 20-40 blue. Using nth-child seems like an option, but it can get quite verbose if I nee ...

Refresh tab controllers in Angular JS on every click event

Is there a way to refresh the tab controller every time a tab is clicked? Here's the current code: $scope.tabs = [ { id: 'tab1', title: 'tab1', icon: 'comments', templateUrl: 'tab1/tab1.tpl.html&ap ...

Encountering a ReferenceError stating that the window object is not defined while building a React Leaflet application

In my upcoming nextjs project, I've incorporated react-leaflet. It behaves flawlessly in dev mode. However, upon attempting to build the project, it throws a ReferenceError: window is not defined. Despite setting ssr to false in dynamic, the error per ...

The custom directive in Vue utilizes the refreshed DOM element (also known as $el)

I am looking to create a custom directive that will replace all occurrences of 'cx' with <strong>cx</strong> in the Dom Tree. Here is my current approach: Vue.config.productionTip = false function removeKeywords(el, keyword){ i ...

Hidden content from Vue router view

My goal is to have the navigation pane overlaying the content of the page, but instead, it is being appended to the bottom where the end of the navigation drawer would be. I've experimented with different variations to display data using navigation dr ...

What is the best way to hide the input field when there are multiple parent classes present?

I am currently implementing dynamic fields with jQuery and everything is functioning correctly. The problem arises when I attempt to remove these fields. After searching on Google and browsing past questions on StackOverflow, I noticed that everyone seems ...

Issue with passing props to screen not displaying on initial load

Greetings, I'm a newcomer to the world of react native and currently facing an issue: const Tab = createMaterialTopTabNavigator(); export const CurriculumMenu = ({navigation, item}) => { const data = item.Title; console.log(data) return ( ...

Populate a PHP array with designated file types from a designated folder, to later be loaded into a JavaScript array

My goal is to populate a JavaScript array with files of type .dae from different directories: "/collada/basement", "/collada/ground", "/collada/first", and "/collada/roof". I'm thinking of creating separate arrays for each directory. I understand that ...

Update the class information using jQuery after performing an action and serialize the button's ID for AJAX requests

I'm facing an issue with two buttons on my page: <td> <button id="1" class="green-button">Publish</button> <button id="1" class="yellow-button">Delete</button> </td> The green-button and red-button have different ...