The JQuery onchange event functions as expected multiple times within JSFiddle, but seems to only fire once in the

A jQuery (1.11.1) script has been implemented on a business catalyst site cart page to show or hide a message based on the dropdown option selected by the user. The script functions correctly multiple times in jsfiddle at http://jsfiddle.net/NathanHill/462tk/ but only works once in my browser. Currently, the JavaScript is placed directly after the dropdown in the HTML code.

Unfortunately, I do not have the ability to modify the HTML dropdown to add any functions for onchange events.

Here is the HTML code:

<select onchange="SomeBCfunction(a,b,c);" id="shippingCountry">
    <option value="AF">AFGHANISTAN</option>
    <option value="AX">ALAND ISLANDS</option>
    <option value="GB" selected="selected">UNITED KINGDOM</option>
</select>

<div id="zones">Show message</div>

And here is the JavaScript code:

<script type="text/javascript">
    $(document).ready(function(){
        $('#shippingCountry').on('change', function() {
            if ( this.value == 'GB')
            {
                $("#zones").show();
            }
            else
            {
                $("#zones").hide();
            }
        });
    });
</script>

Any assistance on this matter would be greatly appreciated.

I attempted to modify the existing BC function that is triggered by using the following code:

var SomeBCfunction = oldBCfunction 
Function SomeBCfunction (){ 
//my hide-display code 
oldBCfunction; 
} 

However, I did not make any progress with this approach...

Answer №1

Functioning smoothly on chrome version 35.0.1916.153 m.

Note: The onchange="SomeBCfunction(a,b,c);" has been removed to prevent the browser from encountering an error each time the selected item is changed, but even with the onchange it works multiple times. However, if not needed, it is recommended to remove it.

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<div class='required'>
    <select id="shippingCountry"> 
        <option value="AF">AFGHANISTAN</option>
        <option value="AX">ALAND ISLANDS</option>
        <option value="GB" selected="selected">UNITED KINGDOM</option>   
    </select>
    <div id="zones">Show message</div>
</div>
<script type='text/javascript'>
 $(document).ready(function(){ 
     $('#shippingCountry').on('change', function() {
      if ( this.value == 'GB')
      {
        $("#zones").show();
      }
      else
      {
        $("#zones").hide();
      }
    });
  });
</script>

Answer №2

Perhaps not the most ideal method, have you attempted this?

$('#shippingCountry').on('click', function() {

Also, have you verified if there are any other script blocks utilizing these events?

Answer №3

Have you attempted creating the function that BC inserts into the HTML?

 function CheckCountry() {
     if ($('#shippingCountry').val() == "GB") {
       $("#zones").show();
        }
        else
        {
            $("#zones").hide();
        }
      }

One approach could be to replace the existing function with a new one that includes the necessary action:

 var old_func = func;
     func = function() {
      old_func();
     newAction();
  }

Answer №4

With every update, BC is getting rid of everything inside #catCartDetails, including any event handlers you've added.

To prevent or customize this behavior, you can redefine the function window.UpdateShipping(), which is originally located in

/CatalystScripts/Java_OnlineShopping.js
.

For your specific situation, you can create a function that runs after ApplyDiscountCode() to display #zones based on the current selection in

jQuery('#shippingCountry').find(":selected").text()
.

window.UpdateShipping = function(e, t, n) {
  var r = document.getElementById("catCartDetails");
  if (r) {
    var i = CMS.OrderRetrievev2.ServerSideUpdateShipping(t, e, n);
    if (i.value[0]) {
      r.innerHTML = i.value[2];

      // Your custom logic goes here:
      checkShippingCountry();
    }
    if (i.value[1].length > 0) {
      if (/(iP[ao]d|iPhone).*?Safari/.test(navigator.userAgent)) {
        setTimeout(function() {
          alert(i.value[1])
        }, 0)
      } else {
        alert(i.value[1])
      }
    }
  }
};

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

Image staying in place when browser page is resized

Half page browser Full page browser Hello everyone, I could really use some assistance with my program. I'm trying to figure out how to keep my robot in the same position when switching from a half-page browser to a full-screen browser. Currently, w ...

Vuex action method completes without returning a value

I've come across a situation in my Vuex action where the console.log() is displaying an undefined output. Here's the method in my Vuex action: const actions = { async fetchByQuery({ commit, title }) { console.log(title); //other code ...

What are some ways to monitor the movement of elements and activate functions at precise locations?

I am working on a project that involves a #ball element which, when clicked, utilizes jQuery animate to move downwards by 210px. The code I currently have is as follows: $('#ball').click(function() { $(this).animate({ top: '+=2 ...

sequenced pauses within a sequence of interconnected methods in a class

scenario: There are two javascript classes stored in separate files, each utilizing a different external service and being called within an express.js router. Refer to the "problematic code" section below: route routes.post('/aws', upload.sing ...

Discovering child elements within an iframe using Angular and customizing their appearance

Is there a simple and effective way to locate child nodes within an iframe using Angular in order to access the HTML element? Currently, I have implemented the following method: I designated a reference variable within my iframe (#privacyPolicy) <ifra ...

FitText.js malfunctioning

I'm currently experimenting with using FitText.js to dynamically adjust the size of headlines to fit within the limits of the browser width. Interestingly, while this script successfully resizes the text in multiple sections of my website, it seems t ...

What is the best way to retrieve an HTML value using Impromptu?

I have integrated the impromptu jQuery plugin into my website to display modal prompts for users. I have included an input field of type "text" in the HTML section, but I am unsure of how to retrieve this value in order to send it via an AJAX request. va ...

Asynchronously load an AngularJS controller from AJAX without altering the route

I am looking to dynamically load an Angular controller after making an AJAX call that generates a new view in HTML. Here is the setup I currently have: Example of a View: HTML Snippet From AJAX <!-- CVS Pharmacy Extracare - Add View --> <d ...

The retrieval process is unable to receive a response from the server

Question: I am encountering an issue with the fetch API in the client-side code. Here is the snippet of the code: window.fetch('/signup', { method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlen ...

What is the best way to retrieve data from a jQuery AJAX call when it returns?

function isNewUsername(str){ var result; $.post('/api/isnewusername', {username:str}, function(data) { result = data.result; }, "json"); return result; } I am encounte ...

Flipping a combination of CSS 3 and JavaScript cards will cause them to flip all together in unison

Hello! I came across a really cool card flip code that is IE compatible. I made some modifications to it and got it working, but there's one problem - instead of flipping the selected card, it flips all the cards. I tried modifying the JavaScript code ...

Arranging two classes in close proximity

I need help aligning two classes that are stacked on top of each other to be displayed side by side. Below is a screenshot of the two classes: https://i.sstatic.net/V0tLL.png The right class is .testm_boxes1, and the left class is .testm_boxes2. Here is ...

Tips for sending a JavaScript variable within a div's ID in a Twig loop?

How can I insert a JavaScript variable into the ID of a div inside a Twig loop? Here is my unsuccessful attempt: <script type="text/javascript"> id = 0; </script> {% for element in parent.elements %} <div id="mydiv"> ...

Error message: "The variable 'bitmap' is not defined in jQuery/CreateJS $.ajax"

I recently acquired a product designer that uses CreateJS and jQuery. Within the code, there is a function called UrlLoader which wraps an $.ajax call. function UrlLoader(params) { $.ajax({ url: url, type: 'POST' ...

Shifting an item to a specific location using three.js

I'm attempting to fire bullets or projectiles utilizing three.js: let renderer, camera, scene, light, plane, cube, spheres; initialize(); animate(); function initialize() { renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); ...

"Implementing a button in a flask data table: A step-by-step guide

Hello, I am facing an issue with adding a button to a Bootstrap datatable in Flask (Python) using JavaScript. Any tips or solutions would be greatly appreciated. I am trying to achieve something like this: https://i.sstatic.net/NtaB3.png I have attempted ...

What is the best way to ensure these elements are neatly stacked one on top of the other?

Is there a way to center this text div while keeping it behind a fading image on the page? I've tried using margin-left: auto; and margin-right: auto; but it doesn't seem to work. Am I missing something? I'm testing everything in Chrome, ju ...

In reference to carrying out functions post partial page reload

For the web page I'm working on, I have set it up so that upon reloading, an ajax call is made to the server to retrieve and display data. Within my code, I have included: $(document).ready( function(){.... some work.... }); Now, I also have a refre ...

What is the process of permanently modifying an HTML document using JavaScript?

I'm interested in creating a basic comment section using JavaScript. Here is the structure of the form : <form> <textarea cols="50" rows="10" placeholder="Share your thoughts ..." id="theComment"></textarea><br/> < ...

Is there a native horizontal divider available in Bootstrap 4?

Is there a predefined horizontal divider in Bootstrap 4? I currently have this: <style type="text/css> .h-divider{ margin-top:5px; margin-bottom:5px; height:1px; width:100%; border-top:1px solid gray; } </style> However, I would prefer t ...