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

What is causing the Access-Control-Allow-Origin error when using axios?

I have a simple axios code snippet: axios.get(GEO_IP) .then(res => res) .catch(err => err); In addition, I have configured some default settings for axios: axios.defaults.headers["content-type"] = "application/json"; axios.defaults.headers.common. ...

Exploring the concept of union return types in TypeScript

Hello, I am facing an issue while trying to incorporate TypeScript in a way that may not be its intended use. I have created a custom hook called useGet in React which can return one of the following types: type Response<T> = [T, false, false] | [nul ...

Is there a way to import TypeScript modules from node_modules using browserify?

After successfully running tsc, I am facing difficulty understanding how to import TypeScript modules from node modules. The crucial section of my gulp file is as follows: gulp.task('compile-ts', ['clean'], function(){ var sourceTsF ...

Modifying arrays in ReactJS

Having trouble editing my array list, need some help. I can update a single input value successfully, but struggling with updating the entire array. Any suggestions on why the method isn't working and how to edit the array? When I try to store data ...

A guide on seamlessly transitioning from a mobile website to the corresponding native app

I am currently working on a mobile website project. This website is built using basic HTML and is accessed through a URL on a web browser, not as a native app or through PhoneGap. The client has requested links to their Facebook, Pinterest, YouTube, Twitt ...

Begin the div at a width of 0 pixels and expand it towards the right

My current project involves opening a row of blocks with an animation. The desired outcome is to transition from 2 blocks to 3 blocks by clicking a button. Specifically, the block that needs to be added should appear in the middle and fade in from left to ...

Instead of using a hardcoded value, opt for event.target.name when updating the state in a nested array

When working with a dynamically added nested array in my state, I encounter the challenge of not knowing the key/name of the array. This lack of knowledge makes it difficult to add, update, iterate, or remove items within the array. The problem lies in fun ...

Sending an AJAX request and then fetching a file for further processing

Recently I've been diving into PHP and I'm working on a piece of code that involves sending data to PHP, running some operations using exec(), and then retrieving the processed output to use (for example, displaying it on a webpage). $.ajax({ ...

What is the best way to send data into functions?

I'm trying to avoid using global variables and I'm facing some difficulties in figuring out how to pass the database variable into the addTrain function. Do I necessarily need to use global variables for the database? $(document).ready(function( ...

What is the appropriate way to utilize `render_template` from Flask within Angular?

I'm facing an issue where I need to implement different routes for various Angular Material tabs. I have attempted to directly call Flask from the template, as demonstrated below, but unfortunately, I am unable to invoke render_template from Angular. ...

Responding with a 404 Error in Node.js and Express with Callbacks

Apologies for the lackluster title, I couldn't come up with anything better. Let's delve into the following code snippet: app.use(function(request, response){ request.addListener('end', function() { parseUrl(request.url, fu ...

Dealing with a variety of AJAX requests

After implementing AJAX to retrieve JSON data from multiple URLs and store them in separate arrays, I encountered an unexpected issue. Take a look at the code snippet below: var var1 = $.ajax({ url: FEED1, dataType: 'jsonp', crossDom ...

Send a basic variable from jQuery using Ajax to Ruby

I'm a beginner in the world of Ruby, jQ, and Ajax. I always make sure to do some reading before reaching out for help. My issue is with sending a basic jQuery variable to a Ruby controller using Ajax for a seamless transition. Is it possible to pass ...

What is the best way to retrieve the data from this date object?

How can I access the date and time in the code below? I've attempted using functions within the Text block without success. It's unclear to me what mistake I'm making or how to correctly access this object, or transform it into an object th ...

CSS exhibiting variations on similar pages

Although the pages look identical, they are actually pulled from the same template file in Drupal but have different URLs. nyc.thedelimagazine.com/snacks In my document head, I've included a style rule that overrides a stylesheet further up the casc ...

Package for running scripts in Node Package Manager

Currently, I am working on developing an npm package that will automatically insert a specific npm script into any package.json file that it is being used. Unfortunately, after going through the npm package.json/script documentation, I haven't been ab ...

Developing a JSON structure from a series of lists

var data = [ [ "default_PROJECT", "Allow", "Connect", "Allow", "AddComment", "Allow", "Write", "Allow", "ViewComments", "Allow", "ExportData", "Allow", ...

Discover the best practices for integrating media queries using Radium within Material UI components

Having trouble applying a breakpoint to the Material UI component, Raised button. I have managed to make it work for regular divs, but not for the Material UI component. I attempted wrapping the button inside Radium import RaisedButton from 'materia ...

Is it possible to utilize an XML format for translation files instead of JSON in React Native?

I'm in the process of creating a react native application using the react i18next library. For translations, I've utilized XML format in android for native development. In react native, is it possible to use XML format for translation files inste ...

"Implementing a click event on a dynamically generated element is triggering the event for all of its parent elements

I have a task to generate a dynamic table with data retrieved from the server. Each row in the table contains a tag that I am trying to link to a click event. The code snippet below demonstrates how the dynamic table is created: function ProcessResponse ...