I am having trouble getting two similar Javascript codes to function simultaneously

Using a common JavaScript code, I am able to display a div when a certain value is selected.

http://jsfiddle.net/FvMYz/

 $(function() {
    $('#craft').change(function(){
        $('.colors').hide();
        $('#' + $(this).val()).show();
    });
});

However, I encountered an issue when trying to make the same JavaScript code work for two select options and divs. Adding another script with different names did not yield the desired results. When selecting an option from the second dropdown list, the contents of the first div show up.

$(function() {
    $('#craft2').change(function(){
        $('.colors2').hide();
        $('#' + $(this).val()).show();
    });
});

Here is my complete code:

First set of options and divs:

{!! Form::select('id', $upgradeable_items, null, array('id' => 'craft')) !!}

@foreach($reals as $real)
    <div id="{{$real->id}}" class="colors" style=";width: 250px; display:none">
        +{{$real->type}}  <img style="margin-left: 20px" class="marketpics" src="{{$real->picturePath}}">
    </div>
@endforeach

Second set of options and div:

{!! Form::select('id', $charms, null, array('id' => 'craft2')) !!}

@foreach($chars as $char)
    <div id="{{$char->item_id}}" class="colors2" style="float: right;width: 250px; display:none">
        <img style="margin-left: 20px" class="marketpics" src="{{$char->picturePath}}">
    </div>
@endforeach

I am facing an issue where the content overlaps when choosing options in the second dropdown list, it appears in the first div and repeatedly overlaps. However, there is no problem when selecting an option from the first dropdown list, as it correctly displays the content in the first div.

Answer №1

It is important to ensure unique IDs in your HTML when using document queries, as they will only return the first instance of an ID. To achieve this, make sure to add something unique to each selector and its corresponding query like so:

$(function() {
    $('#craft2').change(function(){
        $('.colors2').hide();
        $('#' + $(this).val() + '2').show();
    });
});

{!! Form::select('id', $charms, null, array('id' => 'craft2')) !!}

 @foreach($chars as $char)
<div id="{{$char->item_id}}2" class="colors2" style="float: right;width: 250px; display:none"><img style="margin-left: 20px" class="marketpics" src="{{$char->picturePath}}"></div> @endforeach

View working fiddle: http://jsfiddle.net/FvMYz/4508/

Answer №2

Consider using classes instead of IDs for color selection to account for potential duplicates.

To simplify your code, group each select box and its elements within a single div with a unique class for easy manipulation.

Avoid repeating JavaScript for each select box by utilizing classes and the following markup structure:

Stack Snippet

$(function() {
  $('.craft').change(function() {
    $(this).closest('.wrap').find('.colors').hide();
    $(this).closest('.wrap').find('.' + $(this).val()).show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
  <select class="craft" id="colorselector">
    <option value="red">Red</option>
    <option value="yellow">Yellow</option>
    <option value="blue">Blue</option>
  </select>
  <div class="red colors" style="display:none"> red... </div>
  <div class="yellow colors" style="display:none"> yellow.. </div>
  <div class="blue colors" style="display:none"> blue.. </div>
</div>
<div class="wrap">
  <select class="craft" id="colorselector">
    <option value="red">Red</option>
    <option value="yellow">Yellow</option>
    <option value="blue">Blue</option>
  </select>
  <div class="red colors" style="display:none"> red... </div>
  <div class="yellow colors" style="display:none"> yellow.. </div>
  <div class="blue colors" style="display:none"> blue.. </div>
</div>

Answer №3

It is essential to assign unique IDs to the div elements, as each ID can only exist once within a document. If multiple instances of an ID are present and a query is made for that specific ID, it will always refer to the first instance found.

In order to differentiate between the divs, the first one should have ID = "red", and the second one should have ID = "red2".

Additionally, your JavaScript code needs to target the corresponding IDs, illustrated below.

$(function() {
     $('#craft2').change(function(){
           $('.colors2').hide();
           $('#' + $(this).val() + '2').show();
     });
});

UPDATE: To make sure each ID is unique, append "2" at the end of every ID like this:

<div id="{{$char->item_id}}2" class="colors2" style="float: right;width: 250px; display:none">
    <img style="margin-left: 20px" class="marketpics" src="{{$char->picturePath}}">
</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

I am experiencing an issue where my REST call is being triggered twice while using AngularJS

Why is my REST call triggering twice when I make the call from the UI? I am using Java v8 and AngularJS v1.6, here is the service: import com.project123.temp.component.ImportFileComponent; @Component @Path("project123/ImportFileService") @JsonIgnorePrope ...

Is it possible to call a REST API in Javascript by passing the username and password as

I have been attempting to use Javascript to call the AwaazDe REST API with a specific username and password, but I'm encountering issues. Below is my code: function authenticateUser(user, password) { var token = user + ":" + password; ...

Tips for fixing a type error in javascript/cypress

While learning cypress and javascript, I encountered this type error: TypeError: _testElements.default.selectionRow is not a function I have thoroughly reviewed the documentation for cypress but cannot seem to find any errors in my code. I'm hoping ...

What is the best way to adjust the spacing in my bootstrap Navbar? I am struggling to make it stretch to the entire width of the screen

I am currently working on a website project where I want to have a navigation bar that spans the full width of the screen with a black background. I also need the links to be centered and evenly distributed within the navbar. My main issue right now is re ...

Creating multiple rectangles and filling them with a color chosen by the user in Angular can be achieved by following these steps

Looking for advice on angular coding. I'm working on a project that requires creating multiple rectangles and filling them based on selected values. Can anyone suggest a module that would offer this functionality? ...

looping through an ajax function with addEventListener

Apologies in advance for any errors in my English. My task involves creating a simple webpage with just 2 links. When one of these links is clicked, it should load the content of a specific .html file on the same page. For example: clicking on link 1 (wi ...

Creating regex to detect the presence of Donorbox EmbedForm in a web page

I am working on creating a Regex rule to validate if a value matches a Donorbox Embed Form. This validation is important to confirm that the user input codes are indeed from Donorbox. Here is an example of a Donorbox EmbedForm: <script src="https: ...

When I try to share a link to my website on Google Plus, the thumbnail does not appear

Previously, I encountered a similar issue on Facebook, but by utilizing the following tag, I was able to resolve it: <meta property="og:image" content="link to image" /> The dimensions of the image in the "link to image" are 200px x 200px, which me ...

What is the best way to display a mongodb _id in HTML using AJAX?

Using an ajax function to fetch employees using the code provided below, I am attempting to incorporate the mongodb _id field into the checkbox id attribute. However, after rendering in the browser, the output appears as follows: <input id="[object Obj ...

Stylishly Select with Bootstrap 4

Currently, I am utilizing Angular 2 with bootstrap 4 and have implemented the following select element: <div class="form-group"> <label class="col-md-4 control-label" for="OptionExample">Choose an option:</label> <div class="c ...

Angular/JS encountered a premature end of program unexpectedly

I am taking my first steps in the world of web development with Angular (and JavaScript in general). I have been trying to rewrite some basic and common examples using Angular. One thing I attempted was to display a simple message using data binding. This ...

Techniques for Grouping an Array of Objects by a Specific Value Key in Angular

I have the following array that needs to be grouped by section_name in HTML. Additionally, I need to first check if the length of the array values for section_name is greater than zero before displaying the results grouped by section_name. I hope my expl ...

Update the table contents smoothly using the html helper PagedListPager without having to reload the entire

I am struggling with a specific line of code that utilizes the html helper's PagedListPager: @Html.PagedListPager(Model.kyc_paged_list, page => Url.Action("ClientDetails", new { id = ViewBag.ID, kyc_page = page, transaction_page = Model. ...

Proper syntax for jQuery's insertAfter() method when using selectors

I am working with a div <div id="imgDIV"><h4>My Debug DIV</h4></div> and I am trying to add a debug message at the top of the div, right after the first h4. This way, my most recent messages will be displayed at the top. $(' ...

Click on the button to send the input field

Below you'll find an input field and a button: <input id="pac-input" class="controls" type="text" placeholder="Search! e.g. Pizza, Pharmacy, Post office"> <button id="new" class="btn btn-success">Submit</button> Currently, when te ...

Using jQuery to save PHP form output into an Excel spreadsheet

I have a PHP-enabled form on my website for collecting Address details. Currently, the output is sent to my email inbox. However, I would like the output data to be saved in an external Excel file named "address.xls" using jQuery/JSON. The input fields of ...

Issue with Vue2: DIV does not adjust height when using v-for loop

I have a div set up like: <div class="pt-4"> <h5>Genres:</h5> <div class="inline-block float-left" v-for="(genre, index) in moreData.genres" :key="index"> <span v-if="index < ...

Display fixed or absolute elements within a scrollable container

I want to create a unique design with overlapping divs that can be selectively displayed through scrolling. While this effect is possible with images using background-attachment: fixed, I am seeking a solution that can work for any child element. Here is ...

What is the method for defining CSS styles for child elements using the parent element's style attribute?

Here is an example: <div style="SET IMAGE ATTRIBUTES HERE!"> <img src="http://somesite.com/someimg.jpg"><br /> <img src="http://someothersite.com/someotherimg.jpg"><br /> ... </div> With my dynamic ASP.NET ...

Obtain the final array within an array composed of multiple arrays

My dilemma involves working with a dynamically generated array, where I need to extract only the values from the last array for aggregation purposes, discarding all others. Imagine a structure similar to this: let target = [] let data = [ [ { name: &apo ...