Function is raising an error with the wrong value or text

I am currently testing a form that I am in the process of developing. My goal is to have different values returned each time I click on a different item from the dropdown menu. If this explanation isn't clear, please take a quick look at my pen for clarification here

var val1 = $("#box1 p:first-child").text()
var val2 = $("#box2 p:first-child").text()

$("#box1").click(function(){
    $("#dropdown2").removeClass('appear')
    $("#dropdown1").toggleClass('appear')  
})

$("#dropdown1 ul li a").click(function(){
    $("#box1 p:first-child").text($(this).text());
    $("#box1 p:first-child").val($(this).text());
    alert(val1)
})

Every time I click on Placeholder 1, 2, or 3, they all just display "Placeholder" instead of their full text. For instance, clicking on "Placeholder 1" should show "Placeholder 1" and not just "Placeholder."

I would greatly appreciate any assistance as I am completely stuck.

Answer №1

When the page loads, you're defining val1 as $("#box1 p:first-child").text(), then changing the contents of #box1 p:first-child. If you want to alert with the new contents of $("#box1 p:first-child").text(), you need to re-define that variable.

I've relocated val1 into your click handler, after changing its contents with $.text(), since that was the only place where that variable was referenced.

$(document).ready(function() {
  var val2 = $("#box2 p:first-child").text();

  $("#box1").click(function() {
    $("#dropdown2").removeClass("appear");
    $("#dropdown1").toggleClass("appear");
  });

  $("#dropdown1 ul li a").click(function() {
    $("#box1 p:first-child").text($(this).text());
    $("#box1 p:first-child").val($(this).text());

    var val1 = $("#box1 p:first-child").text();

    alert(val1);

    // switch (val1) {
    //   case "Placeholder 1":
    //     alert("test");
    //   case "Placeholder 2":
    //   alert("test2");
    //     break;
    //   default:
    //     alert("test3");
    //   }
  });

  $("#box2").click(function() {
    $("#dropdown1").removeClass("appear");
    $("#dropdown2").toggleClass("appear");
  });

  $("#dropdown2 ul li a").click(function() {
    $("#box2 p:first-child").text($(this).text());
    $("#box2 p:first-child").val($(this).text());
  });
});
* {
  margin: 0;
  padding: 0;
}

/* containers */

#wrapper {

  height: 560px;
  width: 1000px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

#container {

  width: 100%;
  height: 100%;
  position: relative;
}

/* rows */

#row1, #row2, #row3 {
  background: #000;
  width: 100%;
  height: 80px;
  position: absolute;
  top: 80px;
}

#row2 {
  top: 240px;
  z-index: -1;
}

#row3 {
  top: 400px;
}



/* box containers */

.box-wrapper {
  background: blue;
  width: 80%;
  height: 100%;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}




/* boxes */

#box1, #box2 {
  background: #333;
  width: 45%;
  height: 100%;
  position: absolute;
  text-align: left;
  cursor: pointer;
}

#box2 {
  right: 0;
}

#box3, #box4, #box5 {
  background: #333;
  width: 30%;
  height: 100%;
  position: absolute;
}

#box4 {
  left: 50%;
  transform: translateX(-50%);
}

#box5 {
  right: 0;
}

#box6, #box7 {
  background: #333;
  width: 45%;
  height: 100%;
  position: absolute;
  text-align: left;
  cursor: pointer;
}

#box7 {
  right: 0;
}



/* box text */

#box1 p, #box2 p, #box3 p, #box4 p, #box5 p, #box6 p, #box7 p {
  font-size: 40px;
  line-height: 80px;
  padding-left: 10px;
}



/* dropdown */

#dropdown1, #dropdown2 {
  background: #000;
  height: 150px;
  width: 100%;
  position: absolute;
  top: 80px;
  z-index: 2;
  display: none;
}

#dropdown1 ul, #dropdown2 ul {
  background: yellow;
  height: 100%;
}

#dropdown1 ul li, #dropdown2 ul li {
  list-style: none;
}

#dropdown1 ul li a, #dropdown2 ul li a {
  padding-left: 10px;
  font-size: 30px;
  text-decoration: none;
  color: #000;
}



/* show dropdown */

.appear {
  display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <div id="container">
    
    <div id="row1">
      <div class="box-wrapper">
        <div id="box1">
          <p>Placeholder</p>
          <div id="dropdown1" class="dropdown">
            <ul>
              <li><a href="#">Placeholder 1</a></li>
              <li><a href="#">Placeholder 2</a></li>
              <li><a href="#">Placeholder 3</a></li>
            </ul>
          </div>
        </div>

        <div id="box2">
          <p>Placeholder</p>
          <div id="dropdown2" class="dropdown">
            <ul>
              <li><a href="#">Placeholder 1</a></li>
              <li><a href="#">Placeholder 2</a></li>
              <li><a href="#">Placeholder 3</a></li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    
    <div id="row2">
      <div class="box-wrapper">
        <div id="box3">
          <p>Placeholder</p>
        </div>

        <div id="box4">
          <p>Placeholder</p>
        </div>
        
        <div id="box5">
          <p>Placeholder</p>
        </div>
      </div>
    </div>
    
    <div id="row3">
      <div class="box-wrapper">
        <div id="box6">
          <p>Placeholder</p>
        </div>

        <div id="box7">
          <p>Placeholder</p>
      </div>
    </div>
    </div>
  </div>
</div>

Answer №2

Ensure val1 is reset after the text value has been changed, and remember to conclude your lines with a semicolon for consistency.

$("#dropdown1 ul li a").click(function(){
    $("#box1 p:first-child").text($(this).text());
    $("#box1 p:first-child").val($(this).text());

    val1 = $("#box1 p:first-child").text();

    alert(val1);
});

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

Angular input for date is showing wrong value due to timezone problem

My database stores dates in UTC format: this.eventItem.date: "2023-06-21T00:00:00.000Z" The input form field value is showing '2023-06-20' (incorrect day number), which seems to be a timezone issue. I am located in a region with a +3 o ...

Vue does not consistently update HTML when the reference value changes

I am trying to showcase the readyState of a WebSocket connection by utilizing a Ref<number> property within an object and displaying the Ref in a template. The value of the Ref is modified during WebSocket open and close events. However, I am encount ...

Issues with validation preventing PHP contact form from functioning correctly

Issue encountered as nothing I attempted seemed to be effective. Tried my own script, experimented with various solutions found on Google, but alas, nothing worked. The closest success I achieved was receiving empty emails from the latest version. Any insi ...

Disabling past dates in a React JS application with a React date picker

Can someone help me figure out how to prevent selecting past times in React JS? Here is the code snippet: import DatePicker from "react-datepicker"; import setHours from "date-fns/setHours"; import setMinutes from "date-fns/setMi ...

What exactly is the purpose of utilizing node js and can someone explain to me what constitutes a

After mastering HTML and CSS, I've started diving into JavaScript. However, I'm curious about Node.js. What exactly is it, why do I need it, and can you explain what a framework is in general? Sorry if these questions sound silly! ...

implementing HtmlSpanner with an appended css stylesheet

Using HtmlSpanner with CSS for TextView I recently discovered a library called HtmlSpanner that claims to assist in adding an HTML string with CSS to a TextView. However, I am struggling to locate any detailed documentation on how to achieve this, except ...

Picking an element that has a dynamic data attribute, but also considering those with a hyphen

Currently, I am developing a function that will select a span element when clicked based on its data attribute and value. Here is the code snippet: function moveFilterElements(event) { if ($(event).hasClass('active')) { var dataAtt ...

Tips on setting the ajax parameter contentType to "html"

I'm encountering an issue where the variable "myvariable" is passing as null. Can anyone provide guidance on what I might be doing incorrectly? $.ajax({ type: "POST", url: "/MyController/MyAction", data: JSON.stringify({ items: my ...

Formatting text over an image

The challenge I am facing involves having an image and text on it in two separate divs with a background color. The length of the text in one div is long while the text in the second div is short, but I want to ensure that the width of both divs are equal. ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

Ways to implement a 'Delete' feature in a PHP audio tag player

"I successfully retrieved the name of the uploaded file and am able to play it in my browser. How can I incorporate a delete function for each user-uploaded song?" echo "<hr />"; echo "<h4>" . $name . "<br /><a href='#' titl ...

Utilize CSS exclusively on the "Theme Options" page within a Wordpress website

Everything is running smoothly with my current PHP code, which controls the design of my "Theme Options" page under the WP API Appearance menu. However... The issue is that the CSS stylesheet is affecting all other menus in the WP dashboard as well, like ...

Unable to access npm run build on localhost

I have developed a web application using react and node.js, and now I want to test it with a production build. After running npm run build in the app directory, I successfully created a build folder. However, when trying to run the application using local ...

Adjust the alignment of text on both ends of the HTML5 canvas

Is there an easier way to align text on both sides of a canvas element besides using CSS? The link below might provide some insight: https://github.com/nnnick/Chart.js/issues/114#issuecomment-18564527 I'm considering incorporating the text into the d ...

What steps should I take to address this 'key' alert?

My browser console is displaying the following error message: Warning: Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information. ExpenseList@http://localhost:3000/main.cfec1fef7369377b9a ...

What is the process for extracting data from latitude and longitude in order to generate a marker on Google Maps using a script

I have an HTML input text and want to pass coordinates to create a marker on Google maps. Check out the code here: jsfiddle.net/#&togetherjs=r3M9Kp7ff7 What is the best way to transfer this data from HTML to JavaScript? <label for="latitude">L ...

JavaScript: The functionality of calling functions through buttons ceases to function once the page is updated without reloading

I am trying to create a program that consists of one HTML page, where I can dynamically update and populate it with different elements using JavaScript. The main feature of the program is a button that remains constant in every version and displays a mod ...

Navigating through Next.js for slug URLs such as site.com/username

Can someone help me figure out how to create a profile page for each username, like site.com/jack or site.com/jill? I'll be pulling the username info from an API that also contains the user ID and email. I'm new to Next.js and would really appre ...

What is the method for submitting a POST request with a JSON body that consists of only a string, without any key-value pairs included?

There was a developer who, not knowing the correct JSON format for key-value pairs, created a JSON body that looks like this: { "dog" } Instead of { "dog": "dog" } I must send the request from a JavaScript file, and the body needs to be in JSON f ...

What is the best way to display JSON file results when clicking a button using Vue?

Once again, it's me! Check out my latest project here I am looking to retrieve data from a json file by inputting the necessary details and clicking on the button. For instance, let's say we want to find job listings for developers in Istanbul ...