Using Javascript to assign a hidden form value when the drop down selection changes - having trouble populating options from an array in Javascript

When using my JavaScript code to create 2 arrays for Product Category and Product selection, I encountered an issue. The user must first choose the type of Campaign they want to run before selecting the Product Category or Product. The 'Campaign' selection triggers a drop-down menu to choose the Product Category, followed by the Product options.

The problem arose when the Product Category did not populate correctly. Although the options were invisible, selecting one would then display the appropriate Product options. This confusion led me to seek help...

Here is the JavaScript code snippet:

<script type="text/javascript">

var info = new Array(
 "Select One*Select One|Select One",
 "Mortgage*1yr NegAm|3yr ARM|5yr ARM|7yr ARM|15yr FRM|30yr FRM",
 "Home Equity*HELoan|HELOC|Convertible",
 "Credit Card*Standard|Premium|Charge|Limited|Secured|Pre-Paid|Business",
 "Student Loan*Subsidized|Unsubsidized|Undergrad|Graduate|Refi",
 "Auto Loan*Purchase|Lease|Used|Dealer"
);

function stringSplit ( string, delimiter ) { 
    if ( string == null || string == "" ) { 
        return null; 
    } else if ( string.split != null ) { 
        return string.split ( delimiter ); 
    } 
} 

var menu1 = new Array();
var menu2 = new Array();

function createMenus() {

    for ( var i=0; i < info.length; i++ ) {
      menu1[i] = stringSplit ( info[i], '*' );
        menu2[i] = stringSplit ( menu1[i][1], '|' );
    }

    var b = document.selector.dropnum.options[document.selector.dropnum.options.selectedIndex].value;

    var myFormx = myForm + b;

    var prodcat = document.myFormx.main;
    var product = document.myFormx.title;

    prodcat.length = menu1.length;
    product.length = menu2[0].length;  

    for ( var i=0; i < menu1.length; i++ ) {
         prodcat.options[i].value  = menu1[i][0];
         prodcat.options[i].text   = menu1[i][0];
    }
    document.myFormx.main.selected = 0;

    for (var x=0; x < menu2[0].length; x++) {
         product.options[x].text = menu2[0][x];
         product.options[x].value = menu2[0][x];
    }
    document.myFormx.title.selected = 0;
}

function updateMenus ( what ) {
    var sel = what.selectedIndex;

    if ( sel >= 0 && sel < menu1.length ) 
        var temp = menu2[sel];
    else
        var temp = new Array ();

    what.form.title.length = temp.length;

    for ( var i = 0; i < temp.length; i++ ) {
       what.form.title.options[i].text  = temp[i];
        what.form.title.options[i].value = temp[i];
    }
    what.form.title.selected=0;
}
</script>

I also have code from my .php file that defines the form elements:

<html>
<body onLoad="createMenus()">

<br>
<br>

<form name="selector" action="#" method="post">
Select the Campaign methodology to model:

<select id='campnum' name='dropnum' class='css_button_example' onChange="javascript: ShowMenu(document.getElementById('campnum').value, 'camp', 5);">
        <option value='0'>Select Campaign
        <option value='1'>Retention Campaign
        <option value='2'>Acquisition Campaign
        <option value='3'>Cross-Sell Campaign
        <option value='4'>Up-Sell Campaign
</select>
</form>

<div name="newboxes" id="camp0" style="display: none;" href="javascript:showonlyone('camp0');">
</div>

<!-- Retention Campaign Section -->
<div name="newboxes1" id="camp1" style="display: none;" href="javascript:showonlyone('camp1');">
   <form name="myForm1">
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Product Category:&nbsp;
      <select name="main" size=1 onChange="updateMenus(this)">
          <option>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      </select>
  
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Product:&nbsp;
      <select name="title" size=1>
           <option>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
       </select>
     </form>
</div>

</body>
</html>

Best regards,

Vijay

Answer №1

The use of the "href" attribute within a div element is not recommended:

<div href="javascript:showonlyone

Additionally, it is incorrect to include "javascript:" in the onChange event handler. The onchange should only contain JavaScript code without any prefix.

Can you provide information on where ShowMenu is defined?

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

Can you explain the purpose of $winstonLoggerConfig<T>() and $winstonLogger<T>() in winston v3?

I'm currently using the winston logger and I want to implement flow typing for it. However, I am unsure of what exactly I should pass to it in order to achieve this. Below is my current logger setup: const logger = createLogger({ ... }); Missing typ ...

How can you use JavaScript to create a JSON object using values from an HTML form textarea and then send

I need to create an HTML form that will send specific information in the Http-request body. { “info” : { “id” : “123” “text1” : <data from html text-box> } Therefore, my goal is to convert the provided data into a JavaScri ...

Personalized date range filter

I've been attempting to narrow down the data based on two specific dates, but I seem to be having trouble getting it to work correctly. Is there anyone out there who can lend a hand? Here is my HTML: <input type="date" ng-model="from_date"> &l ...

Click the button in Javascript to add new content

I am currently experimenting with JavaScript to dynamically add new content upon clicking a button. Although I have successfully implemented the JavaScript code to work when the button is clicked once, I would like it to produce a new 'hello world&ap ...

Implementing image rendering functionality in Vue.js

So here's what's going on: I developed a horror movie bucket list app for my bootcamp final project. The minimum viable product received positive feedback, and I obtained my certification. However, now that I've graduated, I want to enhance ...

What is the general consensus on combining SWR with Redux - is it considered a best practice?

I am currently incorporating both SWR and Redux into my code. Here is how I'm using them together: const vehiclesStates = useSelector(({ vehiclesStates: state }) => state); // REDUX const response = useFetch("/vehicles/states") // SWR con ...

Place a check mark in the corner of the button

I am looking to add a checkmark on my button in the right corner. I have set the input value and it displays a button with a check mark, but I want it to be positioned in the right corner. .buttoner{ background-color: #4CAF50; b ...

Setting the position of a tooltip relative to an element using CSS/JS

I'm struggling to make something work and would appreciate your help. I have a nested list of items that includes simple hrefs as well as links that should trigger a copy-to-clipboard function and display a success message in a span element afterwards ...

Error message: Unable to assign value to 'kind' property as it is undefined in Angular Webpack application

Unexpectedly, my Angular application is encountering an error during the build process. TypeError: C:\Users\c\dev\privacy\node_modules\@fortawesome\angular-fontawesome\fesm2020\angular-fontawesome.mjs: Cannot se ...

Implementing Do Not Track in an express application

I am trying to implement a feature named "consent" in my Nodejs express app that utilizes the Do Not Track (DNT) functionality from browsers. This function is supposed to integrate Google analytics on rendered pages only when DNT is not active or its state ...

Decrease the jQuery version for a particular view exclusively

Imagine a scenario where I am utilizing jQuery version 1.10 in _Layout.cshtml, but need to downgrade to 1.7.2 for certain pages. Is there a way to achieve this without altering the Layout for these specific views? Can this be done at all? :) ...

Formatting strings with positive or negative numbers can be achieved using Utilities.formatString

Looking to enhance the visual representation of numeric string data by displaying it in different colors based on whether the number is positive or negative. Current code snippet: var url = 'https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxx ...

The Node JS prompt library fails to provide password masking feature

Using the Node.js prompt library, I have the following code snippet: // Initializing variables var prompt = require ('prompt'); var Basic = require('./helper/basic'); var program = require('./helper/cli-args'); var pwd = new ...

The execution of my Nodejs API using the 'npm start' command is unsuccessful, resulting in the following error message

After cloning the project from GitLab, I proceeded to install node_modules using "npm install -g" and ran the "npm start" command in the terminal. However, I encountered errors as shown below: Error Cannot find module '../services/' Require ...

How can I eliminate the scrollbar from appearing on all browsers when visiting my website?

I've encountered an issue while building my portfolio with React.js. I'm having trouble removing the scrollbar. I've attempted using overflow: hidden for the parent element and overflow: scroll for the child div, but it's not producing ...

Find the element that contains a specific substring in its value using JavaScript

I am trying to find a way to count how many input fields with the class name "text" contain a specific value. document.getElementById('c_files').getElementsByClassName('text').length; Currently, this code counts all textboxes with the ...

Tips for populating a Django form with the test Client1. First,

Trying to test my Django forms, but encountering this error: django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with'] when using the following code: self.client.post(self.url, {"title" : 'title ...

Using a union type annotation when passing into knex will result in the return of an unspecified

Knex version: 2.5.1 Database + version: postgres15 When passing a union typescript definition into knex as a type annotation, it returns the type any. However, by using type assertion as UserRecord, we can obtain the correct UserRecord type. It is my un ...

Sidebar navigation text shifting during transition

I attempted to modify the CSS and JavaScript, but unfortunately, it had no effect and actually caused more issues. I adjusted the position and display properties in the CSS, but it seems that wasn't the root of the problem. If anyone could offer assis ...

Tips for building an interactive button with changing content and retrieving variable information when the button is clicked in an Angular framework

Received dynamic data from the server is shown below: { "data": [ { "id": 4, "first_name": "Eve", "last_name": "Holt", "lat":"25.6599899", "lng":"45.3664646", "status":"0" ...