Can JS variables be recycled in any manner?

I'm currently working on building a simplified version of an online citation generator. This project involves creating over 20 input boxes, each requiring the user to enter an author's name. To streamline this process, I've divided the author’s name into two variables - lname and fname. My getElementById function will consist of these variables along with additional factors based on the specific requirements.

Within the JavaScript code, I have defined the variable 'lname' which corresponds to the first input box. However, when attempting to use the same variable for the second input box, it outputs the data from the initial box. While I could create a separate function for each input box, I believe there should be a way to reuse a variable from one function in another. Is this possible?

// JS function examples...

// CSS styling for grid layout... // HTML forms for entering citation details...

Answer №1

If you're facing the issue of not being able to reuse IDs, I suggest assigning classes to the inputs instead. Then within your BIB function, you can pass this and navigate through the parent element to access the child inputs.

function bib(el) {
  var _parent = el.parentNode.parentNode;
  var lname = _parent.querySelector(".lname").value;
  var fname = _parent.querySelector(".fname").value;
  var title = _parent.querySelector(".title").value;
  var city = _parent.querySelector(".city").value;
  var corp = _parent.querySelector(".comp").value;
  var pub = _parent.querySelector(".pub").value;
  _parent.querySelector(".cite").innerHTML = lname + ", " + fname + "." + title + "." + city + "." + corp + "." + pub + ".";
}
.grid{
  display: grid;
  flex-wrap: wrap;
  grid: 500px / auto auto auto auto;
  grid-gap: 10px;
  background-color: #2196F3;
  padding: 10px;
}

.grid > div {
  background-color: rgba(255, 255, 255, 0.8);
  text-align: left;
  padding: 10px 10px 10px 10px;
  font-size: 16px;
}

/*.float{
    float:left;
}*/

.output {
    height: 150px;
    width: 255px;
    flex-wrap: wrap;
  word-wrap: break-word;
}
@media only screen and (max-width: 768px) {
  /* For mobile phones: */
.grid {
    width: 100%;
  }
}
<h1> MLA Sourcing</h1>
<h2> Print Sourcing</h2>
<p> Enter the information in the appropriate box for your print source, click generate, copy to clipboard
  <br>and paste into your work boxes</p>
<!--single author-->
<!--single author-->

<div class="grid">
  <div>
        <h3> Bib a Book or Article -<br> Single Author </h3>
        <input class="float lname" placeholder="Author Last Name"></input><br>
        <input class="float fname" placeholder="Author First Name"></input><br>

        <input class="float title" placeholder="Book/ Article Title"></input><br>
        <input class="float city" placeholder="City of Publication"></input><br>
        <input class="float comp" placeholder="Press Company"></input><br>
        <input class="float pub" placeholder="(last) Year of Publication"></input><br>

      <p> <button onClick="bib(this)">Generate</button></p>


         <h3> Citation</h3>
        <p class="output cite"></p>
        <button>copy to clipboard</button>
  </div>
</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

Transitioning from utilizing Stripe Checkout to implementing Stripe Elements

After using Stripe Checkout for a while, I've decided to make the switch to Stripe Elements. You can find more information about Stripe Elements here. When sending the name and address fields as tokenData, I follow this format: let tokenData = { ...

The React sidebar expanded to cover the entire screen width

As I work on creating a dashboard page that will display a sidebar after the user logs in, I am facing an issue where the sidebar is taking up the full width of the page, causing my Dashboard component to drop to the bottom. You can view the image link of ...

Using ID attributes to compare JavaScript Objects and generate a distinct list within Angular/JS

I am working with the github API to retrieve an array of objects containing commit data. My goal is to extract a unique list of commitors and format it as shown below to create a graph: {"id":temp,"label":temp,"type": "number","p": {} } Here is the code ...

Ways to retrieve the controller scope from a dynamically generated directive

I am currently facing an issue where I need to access a controller scope property from a directive's controller function. I have tried using the $parent property, which works fine for static directives but not for dynamically created ones. You can ch ...

Tips for consistently obtaining the executed value of a getter in Mongoose?

In my mongoose schema, I have implemented a getter function for one of the properties as shown below: const User = new mongoose.Schema( { active: Boolean, email: {type: String, get: toLowerCase} } ) The toLowerCase function is def ...

Total of the Selected Rows

In my webpage, I have a table structured like this: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> ...

Repeating calls to the init() function within an AngularJS controller

Encountering an issue while developing an angularjs application. I have set up a controller and bound it in routeProvider with a function to initialize values like so: angular.module('app.Login', ['app.rpc','ngRoute']) ...

"The issue of the search form CSS class loading twice and causing placement issues following the completion of the AJAX

I implemented a search form that fetches data from the server and displays it in a div, which is working smoothly. However, when I added an ajaxComplete function to add a class for animating the results, it resulted in unexpected behavior. Upon entering t ...

Issues with the directory for Chrome

Currently, I am utilizing jQuery and running an HTML file on my local machine without a server. Interestingly, the code works perfectly fine on Firefox but encounters issues on Chrome: $('#result').load('test.html'); It appears that t ...

Guidelines for executing a Vue directive when the page is initially loaded

I am iterating through an array of objects containing map svg paths and locales, and I want to execute a function on load. The function needs to take the locale keys from the paths array as a parameter and perform some operation: <p v-for="(country ...

Caution in React: Utilizing functions with Object.assign() may not be a valid approach when dealing with React children

I have a setup using react for front-end and node for back-end. My goal is to retrieve data from the server to update the user entries on the front-end. I came across using Object.assign() as a potential solution to re-render user entries, but encountered ...

Unraveling AngularJS: Mastering the Art of Interpolating Interpol

Trying to interpolate a string retrieved from the database, such as "Users({{users_count || 0}})", poses a problem. Using {{}} or ng-bind for interpolation does not work properly. The HTML code written is {{data.usersCount}}, but instead of ren ...

A Vue button that toggles between three states depending on the value in an array

In my Vue project, I am working on loading an array when the page loads. I need to check the status of each line item in the array and display a specific button for each status using a 3-way toggle. Although I believe I understand the main concept, I am s ...

Retrieve the information of the currently logged-in user on Discord using next-auth

Can anyone help me with extracting the banner and ID of the currently logged in user? Feel free to reach out at next@12 [email protected] I have successfully logged the profile details at the backend, but I'm facing issues pulling this informatio ...

What is the best way for a function to pause until the variable 'rows' holds the outcome of a mysql query?

The client.mysqllocal function should be returning rows. Here's the code I'm currently using: https://pastebin.com/hgt2DwSY const mysql = require('mysql2'); let pool = mysql.createPool({ connectionLimit : 10, hos ...

Button that vanishes when clicked, using PHP and HTML

I am in the process of creating an online store and I am seeking to implement a button that directs users to a new page, but then disappears permanently from all pages within the store. Here is the code snippet I have developed so far: <input class="b ...

What is the best way to implement <li> in place of <div> to ensure the tool-tip code functions properly?

To see an example, please refer to this fiddle: http://jsfiddle.net/66nLy/12/ I am looking to achieve a similar functionality on a webpage, but using <li> instead of <div>. Here is the HTML code snippet: <table class="base-table selection- ...

Upward-Facing jQuery Dialog Box

jQuery( "#dialog" ).dialog({ width: 'auto', zIndex: 9999, height: 370, resizable: false, draggable: false, open :function(event, ui) { jQuery('body').addClass('black-overlay'); }, show: { effect: 'drop ...

Incorporate different courses tailored to the specific job role

https://i.stack.imgur.com/iGwxB.jpg I am interested in dynamically applying different classes to elements based on their position within a list. To elaborate: I have a list containing six elements, and the third element in this list is assigned the class ...

Is there a way to improve this code without the need for the variable `a`?

Assist in enhancing the performance of the functions below, without using the variable a getFieldsGroups(){ let list = []; if(this.activeTab.fieldsGroupName === ''){ this.activeTab = { groupIndex: 0, subgroupIndex: 0, f ...