Utilizing EXTJS 5: Choosing between a tagfield or combobox to dynamically display and conceal form fields

I am looking to create a dynamic form that shows and hides fields based on the selection made in a multi-select combo box (tagfield).

For each item selected in the combo box, there are hidden form fields associated with them.

These fields have the property "hidden:true".

I am able to show the fields based on selection, but facing issues with hiding them when items are removed from the combo box or tagfield.

listeners:{ 

    select:function( combo, records, eOpts) {

            var combo = Ext.ComponentQuery.query('#combo')[0];

            var field = Ext.ComponentQuery.query('#A')[0];                      

            var field1 =Ext.ComponentQuery.query('#B')[0];                      

            var field2 =Ext.ComponentQuery.query('#C')[0];


            var records = combo.getValue();

              console.log(records);

            for (var i = 0, count = records.length; i < count; i++) {

                    switch(records[i]) {

                    case 'itemone':

                        if(field.isHidden()) {
                            field.show();                   
                                }
                        else { 
                             field.hide();
                                }
                    break;

                    case 'itemtwo':

                        if(field1.isHidden()) {
                            field1.show();                  
                                }
                        else { 
                             field1.hide();
                                }                                       
                    break;

                    case 'itemthree':

                        if(field2.isHidden()) {
                            field2.show();                  
                                }
                        else { 
                             field2.hide();
                                }       
                    break;  
                } 
            }
        }
}

The result of console.log(records) is as follows:

Show:

["itemone"]

["itemone", "itemtwo" ]

["itemone", "itemtwo", "itemthree"]

Hide:

["itemone", "itemtwo"]

["itemone"]

Please provide suggestions for correcting the code.

Note: Apologies for the previous post being in the wrong place

I attempted to implement your suggestions but faced difficulties due to being a beginner.

My code:

 listeners:{ 

  select:function( combo, records, eOpts) {

    var combo = Ext.ComponentQuery.query('#combo')[0];

    var fields = Ext.ComponentQuery.query('[autoHideTag]');

    var records = combo.getValue();

      console.log(records);

    for (var i = 0, count = records.length; i < count; i++) {

            fields.setVisible(records.indexOf(fields.autoHideTag) !== -1 ); 

            switch(records[i]) {

            case 'itemone':

                if(field.isHidden()) {
                    field.show();                   
                        }
                else { 
                     field.hide();
                        }
            break;

            case 'itemtwo':

                if(field1.isHidden()) {
                    field1.show();                  
                        }
                else { 
                     field1.hide();
                        }                                       
            break;

            case 'itemthree':

                if(field2.isHidden()) {
                    field2.show();                  
                        }
                else { 
                     field2.hide();
                        }       
            break;  
        } 
    }
  }
} 

Firebug error message:

TypeError: fields.setVisible is not a function

Any further suggestions would be greatly appreciated.

Thank you.

Answer №1

It appears that there is a flaw in your code logic. You seem to be making all fields visible, but what happens when you remove the 3rd tag? The loop seems to only consider currently selected tags in the combo box, resulting in ["itemone", "itemtwo"], without including "itemthree". As a result, the case for hiding the 3rd field and subsequent tags is not executed properly.

A better approach would be to iterate through each field, displaying it if the corresponding tag is selected and hiding it otherwise. You can use

records.indexOf('itemone') !== -1
to check if a specific tag is selected.

Additionally, using a custom property with a unique name for each field can simplify the component query process and make it easier to identify which tag to test against the selected ones.

For instance, if you define your fields like this:

{
    xtype: 'textfield'
    ,autoHideTag: 'itemone' // custom marker
}

You can then retrieve all fields in one query:

// select all components with the autoHideTag property set to a truthy value
var fields = Ext.ComponentQuery.query('[autoHideTag]');

If needed, you can refine the query by specifying "textfield[autoHideTag]" or "field[autoHideTag]".

Lastly, you will have a clear indication of the tag to test against for each field:

// changing the visibility of a component that is already in the desired state has no impact
field.setVisible( records.indexOf(field.autoHideTag) !== -1 );

There you have it. Enjoy working with Ext!

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

Invoking a synchronous JavaScript request to an MVC 4 Controller function

For the code I'm working on, I need certain functions to be executed sequentially. I attempted to use ajax calls but ran into issues due to their asynchronous nature. function GetLibraryActivities(libraryName, callback) { $.ajax({ dataTyp ...

Normalization of Firebase Database

Recently, I developed a Tricycle Patrol app designed to address the prevalent issue of reckless tricycle drivers in our city. Users can log in and submit reports through a form that includes fields such as: - created_at - description - lat - lng - plateNu ...

The chart refreshes whenever there is a change in the component's state

Whenever I click the button to use the changeState method, the state changes and the MoreInfo component appears. However, the chart is being drawn again as shown in this GIF: Below is the code snippet: import React from 'react' import './Ho ...

What is the term used to describe the way console.log styles the Json object?

Have you ever noticed that when a JSON object is printed, say in a script run by node using console.log, it doesn't exactly pretty print the JSON? It sort of strikes a balance between showing as few lines as possible while still maintaining readabilit ...

What is the better choice in NodeJS: using "return cb(..)" or first calling cb(..) and then returning?

Forgive me if this sounds like a silly question, but I'm curious about the implications of something: Whenever I encounter an error or need to complete a function flow, I follow certain instructions such as: if(err) { cb(err); // or for exampl ...

What is the best way to transfer the value of a <span> element to a different <div> using jQuery or JavaScript

Is there a way to move or copy the price and insert it into the <div class="info"> using jQuery? The code I'm currently using is returning an unexpected result of "102030". jQuery(document).ready(function($) { $(document).ready ...

Substitute Symbolic Codes in an Object with Written Text

Here's the structure of the object: { where: { [Symbol(or)]: [ [Object], [Object] ] },hooks: true, rejectOnEmpty: false } When I use JSON.stringify on it, the result is: {"where":{},"hooks":true,"rejectOnEmpty":false} T ...

Chrome fails to select item in Protractor test, while Safari succeeds

While my test passes smoothly on Safari, I encountered an issue on Chrome where the following code snippet fails to work: it('should click the first source and get to the source preview page', function () { var grid_icon = element(by.css(&a ...

Create a CSV document using information from a JSON dataset

My main goal is to create a CSV file from the JSON object retrieved through an Ajax request, The JSON data I receive represents all the entries from a form : https://i.sstatic.net/4fwh2.png I already have a working solution for extracting one field valu ...

The compiler option 'esnext.array' does not provide support for utilizing the Array.prototype.flat() method

I'm facing an issue with getting my Angular 2 app to compile while using experimental JavaScript array features like the flat() method. To enable these features, I added the esnext.array option in the tsconfig.json file, so the lib section now includ ...

How to retrieve textfield value using Material UI and ReactJS

Just delved into the world of React and I'm struggling to figure out how to retrieve the value inputted in my textfield when the submit button is clicked. I've been referencing the examples provided here: but unfortunately, they don't addre ...

Unable to conceal adjacent element when z-index is set as 1

I encountered an issue where a modal is overlapping another element, and the close button of the underlying element has a z-index of 1. Despite creating a new modal with its own close button, the original close button remains visible on top. I attempted t ...

The state update does not seem to be affecting the DOM

I've implemented this component in my React app. It updates the state every second, but oddly enough the value <p>{this.state.time}</p> is not changing as expected. When I print the state value, it does change every second. import React f ...

How can the @blur event be added to the vue-bootstrap-typeahead in Nuxt/Vue application?

I am facing an issue where I want to trigger a function upon leaving an input field. The input in question is set up using vue-bootstrap-typeahead. Upon inspecting the DOM, I found that the structure of the input element looks like this: <div id="m ...

`How can I define dependencies and build an npm package?`

I have authored several npm modules, all of which are designed to enhance existing libraries such as three.js or react. While the packages appear to be downloaded, I have not received any feedback confirming whether they have been implemented correctly. ...

Is there a way to implement this media query within my JavaScript code?

I am attempting to make my website recognize when the screen width surpasses 1096px in order to apply some CSS styling. Below is the code I'm using: var mq = window.matchMedia('@media all and (max-width: 1096px)'); if(mq.matches) { wind ...

What causes functions operating on mapped objects with computed keys to not correctly infer types?

If you are seeking a way to convert the keys of one object, represented as string literals, into slightly modified keys for another expected object in Typescript using template string literals, then I can help. In my version 4.9.5 implementation, I also ma ...

I would greatly appreciate your assistance in deciphering the JavaScript code provided in the book "Ajax in Action"

While reading through the Ajax in Action book, I came across a code snippet that has left me with a couple of questions. As someone who is new to web programming and still getting to grips with JavaScript, I am hoping for some clarity on the following: ...

Change the direction of the arrow on the button to point downwards once the menu has slid

After hovering over a button, an arrow is added to it. Upon clicking the button, a content div slides out within its wrapper by utilizing jQuery.slideToggle(). Following the slide out of the div, I aim to rotate the arrow in the button by 180 degrees to i ...

What is the best way to divide text into key-value pairs using JavaScript?

I have data in text format from my Raspberry Pi that I need to insert into MongoDB as key-pair values or JSON for my Node.js Application. I'm relatively new to JavaScript and I'm looking for a solution. Any suggestions would be greatly appreciate ...