Solving an issue with conflicting Javascript code

I'm experiencing an issue with JavaScript. I have implemented two scripts for a select element on my website. One script handles submitting it without a submit button, and the other script is responsible for custom styling the select. Here are the two scripts:

 <script type="text/javascript"><!--
                var dropdown = document.getElementById("stallions");
                function onStallion() {
                  if ( dropdown.options[dropdown.selectedIndex].value != null ) {
                    location.href = dropdown.options[dropdown.selectedIndex].value;
                  }
                }
                dropdown.onchange = onStallion;
            --></script>

  // Jquery plugin for styling selectboxes from DressCode.

$(document).ready(function(){
// first locate all of the select tags on the page and hide them
$("select#stallions").css('display','none');
//now, for each select box, run this function
$("select#stallions").each(function(){

    var curSel = $(this);
    // get the CSS width from the original select box
    var gddWidth = $(curSel).css('width');
    var gddWidthL = gddWidth.slice(0,-2);
    var gddWidth2 = gddWidthL - 28;
    var gddWidth3 = gddWidthL - 16;
    // build the new div structure
    var gddTop = '<div style="width:' + gddWidthL + 'px" class="selectME" tabindex="0"><div class="cornerstop"><div><div></div></div><div class="middle"><div><div><div>';
    //get the default selected option
    var whatSelected = $(curSel).children('option:selected').text();
    //write the default
    var gddFirst = '<div class="first"><span class="selectME gselected" style="width:'+ gddWidth2 +  'px;">'+ whatSelected +'</span><span id="arrowImg"></span><div class="clears"></div></div><ul class="selectME">';
    // create a new array of div options from the original's options
    var addItems = new Array();      
    $(curSel).children('option').each( function() {           
        var text = $(this).text();  
        var selVal = $(this).attr('value'); 
        var before =  '<li style="width:' + gddWidthL + 'px;"><a href="#" rel="' + selVal + '" tabindex="0"  style="width:' + gddWidth3 + 'px;">';
        var after = '</a></li>';           
        addItems.push(before + text + after);
    });
    //hide the default from the list of options 
    var removeFirst = addItems.shift();
    // create the end of the div selectbox and close everything off
    var gddBottom ='</ul></div></div></div></div><div class="cornersbottom"><div><div></div></div></div></div>'
    //write everything after each selectbox
    var GDD = gddTop + gddFirst + addItems.join('') + gddBottom;
    $(curSel).after(GDD);
    //this var selects the div select box directly after each of the origials
    var nGDD = $(curSel).next('div.selectME');

    $(nGDD).find('li:first').addClass("first");

    $(nGDD).find('li:last').addClass('last');
    //handle the on click functions - push results back to old text box
    $(nGDD).click( function(e) {
         var myTarA = $(e.target);
         var myTarT = $(e.target).text();
         var myTar = $(e.target);
         //if closed, then open
         if( $(nGDD).find('li').css('display') == 'none')
            {
                    //this next line closes any other selectboxes that might be open
                    $('div.selectME').find('li').css('display','none');
                    $(nGDD).find('li').css('display','block');

                    //if user clicks off of the div select box, then shut the whole thing down
                    $(document.window || 'body').click( function(f) {
                            var myTar2 = $(f.target);
                            if (myTar2 !== nGDD) {$(nGDD).find('li').css('display','none');}
                    });
                            return false;
            }
            else
            {      

                    if (myTarA == null){
                        $(nGDD).find('li').css('display','none');
                                return false;
                            }
                            else {
                                //set the value of the old select box
                                $(curSel).val(myTarA);
                                //set the text of the new one

                                 $(nGDD).find('span.gselected').text(myTarT);
                                 $(nGDD).find('li').css('display','none');
                                 return false;
                            }
            }
    //handle the tab index functions
     }).focus(function(e) {        

         $(nGDD).find('li:first').addClass('currentDD');
         $(nGDD).find('li:last').addClass('lastDD');
         function checkKey(e){
            //on keypress handle functions
            function moveDown() {
                var current = $(nGDD).find('.currentDD:first');
                var next = $(nGDD).find('.currentDD').next();
                if ($(current).is('.lastDD')){
                return false;
                } else {
                    $(next).addClass('currentDD');
                    $(current).removeClass('currentDD');
                }
            }
            function moveUp() {
                var current = $(nGDD).find('.currentDD:first');
                var prev = $(nGDD).find('.currentDD').prev();
                if ($(current).is('.first')){
                return false;
                } else {
                    $(prev).addClass('currentDD');
                    $(current).removeClass('currentDD');
                }
            }
            var curText = $(nGDD).find('.currentDD:first').text();
            var curVal = $(nGDD).find('.currentDD:first a').attr('rel');
           switch (e.keyCode) {
                case 40:
                    $(curSel).val(curVal);
                    $(nGDD).find('span.gselected').text(curText);
                    moveDown();
                    return false;
                    break;
                case 38:
                    $(curSel).val(curVal);
                    $(nGDD).find('span.gselected').text(curText);
                    moveUp();
                    return false;
                    break;
                case 13:
                    $(nGDD).find('li').css('display','none');
                    }     
        }
        $(document).keydown(checkKey);  
    }).blur( function() {
            $(document).unbind('keydown');
    });
});
});

The first script is embedded in the page's php file, while the second script is called from an external js file. After testing, I've identified a conflict between the two scripts. When using the second script, the functionality of the first script for submission stops working. However, if I remove the second script, everything works as expected.

Any assistance in resolving this error and understanding its cause would be much appreciated. Thank you for your help!

Answer №1

The problem lies in the way the DressDown code is interacting with the dropdown menu.

Specifically, at line 69 where you have this code snippet:

//assigning a value to the current select box
$(curSel).val(myTarA);

This line of code does not trigger the list's onchange event as intended. To resolve this issue, try adding location.href immediately after setting the value:

....
//assigning a value to the current select box
$(curSel).val(myTarA);
location.href = myTarA;
//updating text for the new selection
....

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

"Endless Cycle Dilemma" Enigma

Upon executing the function below, I encountered the following error: "Error: Possible infinite loop." The issue appears to stem from the use of "0" in the splice method, as changing it to any other number (1-9) eliminates the error. I'm uncertain ...

retrieving information via AJAX call using jQuery

I've been tasked with customizing a book website, and I'm trying to integrate reviews from the Goodreads API. However, my Ajax request isn't returning any data. Here is the code snippet: $.ajax({ 'type': 'GET', & ...

Is there a way to retrieve the Incoming Message object in Angular using HttpClient?

From my Angular file, I am sending this request to the server. Is there a way to access it from my typescript file using a HttpClient object? IncomingMessage { ... // Headers details omitted for brevity url: '/teradata/databases/view/djfg', ...

Exploring JS files for bugs using VS Code

Just starting out with learning javascript. Currently trying to troubleshoot this basic code: console.log("Hello World!\n"); // there's a breakpoint here let million = 1_000_000; console.log(million); However, upon hitting the play b ...

In Ext.net, learn how to effortlessly update the text of a textfield within the toolbar using dynamic

Currently, I am collaborating on a project involving the utilization of ext.net, where a paginator is located within the toolbar of an HtmlEditor. The markup is as follows: <ext:Hidden ID='HF_type' runat="server"/> <ext:HtmlEditor ...

Achieving successful content loading through AJAX using the .load function

Our website features a layout where product listings are displayed on the left side, with the selected product appearing on the right side (all on the same page). Initially, when the page loads, the first product is shown on the right. Upon clicking a new ...

Arrange the objects in the array in React based on their time and date of creation

As a newcomer to the world of React.js and Redux, I am faced with an array of objects structured like this: quizList = [ { createdDate : 1543314832505, id:5bfd1d90d4ed830001f589fc, name:'abc'}, { createdDate : 1543314152180, id:5bfd1ae8d4ed83000 ...

Dynamically enhance dropdownlist options in webforms using JavaScript

I am currently working on an asp.net webforms project where I have a page with 2 dropdown lists. Whenever a user selects an option from ddl1, I want to dynamically add that selected element to ddl2 using JavaScript. Initially, when the page loads, ddl1 h ...

Exploring the Integration of Material UI DatePicker with Firestore in ReactJS: Converting Firestore Timestamps to Date Format

The database is correctly recording the date, however, when displayed, the DatePicker does not recognize the date from the database as it is in timestamp format (seconds and nanoseconds). <DatePicker margin="normal" label="Data do pedido" ...

What method can we use to temporarily route traffic from one URL to another URL for a specific amount of time?

Is there a way to use javascript/jquery code that will redirect my website to a different domain, but only during specific hours? I'm looking to have the redirection occur between 2 a.m. and 4 a.m., so that it only works for two hours out of the day. ...

In JavaScript, how is the symbol "." referred to as?

While I am familiar with its purpose and the language terminology, could you please provide the official name for the period/dot used in Javascript/jQuery? Appreciate your help! ...

Utilizing the same uuid twice along with Vuex and the unique identifier generation tool uuidv4

Within my vuex store, there is a function to create a post. This function generates a json Object containing a unique uuid using uuidv4(). However, I have noticed that if I execute the function multiple times, the uuid remains the same each time (unless I ...

The @mouse-down event in Vue does not seem to be firing

I'm new to web development and I'm having some issues with Vue. I learned from a tutorial that I can use @click when a button is pressed, and it works fine. Now I want to create a simple mechanism to detect when the mouse is clicked and released ...

In ReactJS, changing one setState property triggers a cascade of changes in other properties

Within my React application, I am facing an issue where changing a state property in the parent component results in an unexpected change in another state property. The setup involves a table in the parent component and form fields in the child component. ...

Transforming the *.vue file into a *.js file for deployment on a content delivery network

Is there a way to compile Component.vue files into JavaScript files for use with the Vue CDN in HTML? For example, consider the following component Component.vue: <template> <div class="demo">{{ msg }}</div> </template& ...

Trail of crumbs leading to pages displayed in a div container

My website is designed with only one page where all other pages are loaded within a div. I am looking to implement breadcrumbs to keep track of the pages loaded inside the div. However, the solutions I have found online only work for pages loaded in the en ...

Utilizing Angular.js to nest directives seamlessly without cluttering the markup

Expressing my query might pose some difficulty, but I appreciate your patience. I comprehend that in the realm of Angular.js, directives play a crucial role in driving dynamic markup. What was once achieved through jQuery can now be accomplished using dir ...

When Bootstrap4 modals are positioned towards the bottom of the page, tapping on an input field inside the modal causes the page to scroll to the bottom on Chrome for Android

Can you please take a look at this issue? I have a simple one-page HTML code that reproduces it. There are two modals on the page - one at the top and one at the bottom. The problem occurs when tapping on an input field inside the bottom modal, causing the ...

Retrieving values with Jquery on a function's onClick event

Here is a small script that retrieves values from a select element <script> jQuery(document).ready(function() { var selectedValue = jQuery("#tr_val").val(); }); </script> When you click on this div and execute the open_win function, I need t ...

On mobile devices, the height of the absolutely positioned element is larger than its

I currently have an element with a background image that includes an absolutely positioned element at the bottom. As the screen width decreases, the height of the absolutely positioned element increases and surpasses the parent element. Since absolutely p ...