


How to populate the state dropdown with the correct options based on the selected country when loading an edit form in jqGrid?
The value of the drop-down option in the edit box of jqgrid is incorrect
When editing the form, you need to use two drop-down boxes in the form. The first drop-down box selects the country, and the second drop-down box selects the state to which the corresponding country belongs. The option value in the country drop-down box is equivalent to the country's id, while the option value in the state drop-down box is related to the country's id. For example:
Country:
美国 (选项值=1) 英国 (选项值=2)
US state:
阿拉巴马州 (选项值=1) 加利福尼亚州 (选项值=2) 佛罗里达州 (选项值=3) 夏威夷州 (选项值=4)
British state:
伦敦 (选项值=5) 牛津 (选项值=6)
It can be seen that the option value of the British state is from 5 starts. When the edit record contains country id=2 (UK) and state id=6 (Oxford), the edit form displays correctly - the country is UK and the state is Oxford. However, if I expand the status dropdown box, I see that the option text is correct (London and Oxford are shown), but the option values start at 0. The correct result should be that the option value starts from 5.
If you select and change the country dropdown to the United States, then change it back to the United Kingdom, the option values will be populated correctly (starting at 5).
Question: When loading the edit form using the edit box, how to correctly populate the option values in the status drop-down box according to the country?
Answer:
The answer to your question depends on where you get the information for "US states" and "UK states". jqGrid supports two possibilities: 1) using the value parameter of editoptions, or 2) using the dataUrl and buildSelect parameters of editoptions. The first method is best suited for local editing or where the list of options may be static. The second method is used when obtaining country, state, and state information for a country from the database through an AJAX request. The following example demonstrates the first case of the solution (using the value parameter):
To avoid dependencies on server components, you can use local examples. The value is overwritten in the dataInit function, but after changing the value in the first select/drop-down box, the second select/drop-down box needs to be manually rebuilt. To do this, you need to understand that the id of the select HTML element consists of the table row id '_' and the column name: rowId "_State". Additionally, it is important that the value of editoptions must be reset to its initial value in order to decode any state ids into state names.
Sample code below:
var countries = { '1': 'US', '2': 'UK' }; var states = { '1': 'Alabama', '2': 'California', '3': 'Florida', '4': 'Hawaii', '5': 'London', '6': 'Oxford' }; var statesOfCountry = { 1: { '1': 'Alabama', '2': 'California', '3': 'Florida', '4': 'Hawaii' }, 2: { '5': 'London', '6': 'Oxford' } }; var mydata = [ { id: '0', Country: '1', State: '1', Name: "Louise Fletcher" }, { id: '1', Country: '1', State: '3', Name: "Jim Morrison" }, { id: '2', Country: '2', State: '5', Name: "Sherlock Holmes" }, { id: '3', Country: '2', State: '6', Name: "Oscar Wilde" } ]; var lastSel = -1; var grid = jQuery("#list"); var resetStatesValues = function () { grid.setColProp('State', { editoptions: { value: states} }); }; grid.jqGrid({ data: mydata, datatype: 'local', colModel: [ { name: 'Name', width: 200 }, { name: 'Country', width: 100, editable: true, formatter: 'select', edittype: 'select', editoptions: { value: countries, dataInit: function (elem) { var v = $(elem).val(); // 为了拥有与国家对应的选项列表,我们需要暂时更改列属性 grid.setColProp('State', { editoptions: { value: statesOfCountry[v]} }); }, dataEvents: [ { type: 'change', fn: function(e) { // 为了能够保存当前选择的查看结果,列属性值至少应该包含 // 当前选定的状态。因此,我们必须将列属性重置为以下值 //grid.setColProp('State', { editoptions:{value: statesOfCountry[v]} }); //grid.setColProp('State', { editoptions: { value: states} }); resetStatesValues(); // 根据选定的国家值创建状态选项 var v = parseInt($(e.target).val(), 10); var sc = statesOfCountry[v]; var newOptions = ''; for (var stateId in sc) { if (sc.hasOwnProperty(stateId)) { newOptions += '<option role="option" value="' + stateId + '">' + states[stateId] + '</option>'; } } // 填充新值到 select/drop-down if ($(e.target).is('.FormElement')) { // 表单编辑 var form = $(e.target).closest('form.FormGrid'); $("select#State.FormElement", form[0]).html(newOptions); } else { // 内联编辑 var row = $(e.target).closest('tr.jqgrow'); var rowId = row.attr('id'); $("select#" + rowId + "_State", row[0]).html(newOptions); } } } ] } }, { name: 'State', width: 100, editable: true, formatter: 'select', edittype: 'select', editoptions: { value: states } } ], onSelectRow: function (id) { if (id && id !== lastSel) { if (lastSel != -1) { resetStatesValues(); grid.restoreRow(lastSel); } lastSel = id; } }, ondblClickRow: function (id, ri, ci) { if (id && id !== lastSel) { grid.restoreRow(lastSel); lastSel = id; } resetStatesValues(); grid.editRow(id, true, null, null, 'clientArray', null, function (rowid, response) { // aftersavefunc grid.setColProp('State', { editoptions: { value: states} }); }); return; }, editurl: 'clientArray', sortname: 'Name', height: '100%', viewrecords: true, rownumbers: true, sortorder: "desc", pager: '#pager', caption: "使用依赖 select/drop-down 列表(双击编辑)" }).jqGrid('navGrid','#pager', { edit: true, add: true, del: false, search: false, refresh: false }, { // 编辑选项 recreateForm:true, onClose:function() { resetStatesValues(); } }, { // 添加选项 recreateForm:true, onClose:function() { resetStatesValues(); } });
Update: The above code has been updated to work properly in form editing situations as well. This code cannot be tested since jqGrid does not support local editing for form editing. Hopefully I've made most of the changes needed, though.
Update 2: The above code has been extended to support:
- Inline editing, form editing, search toolbar and advanced search
- Previous or next navigation buttons in edit forms
- Improved selection within different browsers Keyboard support (fixes refresh select dependent issue in some browsers)
The latest version of the demo can be found [here](http://www.trirand.com/blog/ jqgrid/jqgridfromformwithdependseditboxes.html) found.
The following modified demo code:
美国 (选项值=1) 英国 (选项值=2)
The above is the detailed content of How to populate the state dropdown with the correct options based on the selected country when loading an edit form in jqGrid?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.
