簡體   English   中英

如何使用 jQuery 啟用禁用字段?

[英]How to enable disabled fields using jQuery?

 function disableField() { var Count = $('#dataTable tr').length; if (Count == 2){ $("input").not('.DeleteButton').prop('disabled', false); }else{ $("input").prop('disabled', false); } } //-------------------------------------------------- var regex = /^([a-zA-Z0-9 _-]+)$/; var cindex = 0; var quicklink = '' ; $(document).on('click','.Buttons', function(addrow) { var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length; if(count || !$('.id_100 option[value=code]').attr('selected','selected')){ alert("Please fill the current row"); return false; } var $tr = $('#dataTable tbody tr:last'); var $clone = $tr.clone(true); cindex++; $clone.find(':input').not('select').not('.DeleteButton').val('').attr('disabled', true); $clone.attr('id', 'id'+(cindex) ); //update row id if required //update ids of elements in row $clone.find("*").each(function() { var id = this.id || ""; if(id != ""){ var match = id.match(regex) || []; if (match.length == 2) { this.id = this.name + (cindex); } } }); $tr.after($clone); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td> <div class="toppanel"><ul><li></li></ul></div> <div class="abcd"> <!--mainbox middlepanel start--> <table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable"> <tr> <td valign="top"> <div id="pageheadingpanel"> <div id="pageheading">Quick Link Widget Configuration</div> <div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div> </div> </td> </tr> <tr> <td height="100%" valign="top"> <div class="y_scroll" id="contentarea"> <div class="contentarea"><!--contentarea start--> <span id="box" class="box"> <!--rounded curve/border start--> <div class="middlepanel"> <!--contentarea box middlepanel start--> <div style="display:block" id="textBox1" > <span id="box1" class="box"> <div class="toppanel"><ul><li></li></ul></div> <div class="middlepanel"> <table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable"> <thead> <tr> <td class="headingalign" width="16%">Links</td> <td class="headingalign" width="32%">Desciption</td> <td class="headingalign" width="16%">Image</td> <td class="headingalign" width="16%">URL</td> <td class="headingalign" width="05%"></td> </tr> </thead> <tbody> <tr id="id0" class="vals" name="id0"> <td> <div class="id_100"> <select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField()" > <option value="">Select</option> <xsl:for-each select="values from local db"> <xsl:sort order="ascending" select="description"/> <option value="{description}"> <xsl:value-of select="description"/> </option> </xsl:for-each> </select> </div> </td> <td> <input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" /> </td> <td> <input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" /> </td> <td> <input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" /> </td> <td> <input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" /> </td> </tr> </tbody> </table> <div class="buttonarea"> <ul> <li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li> </ul> </div>

我有一個帶有下拉列的表格。 每當我更改下拉列表的值時,我的相應字段就會啟用。 我遇到的問題是,如果我更改前一行下拉列表的值,當前行的列也會啟用。任何幫助將不勝感激。 謝謝。 編輯:我在我的代碼中也添加了“添加行”功能。

我在您的disableField函數中添加了一些更改。 在 chnage 事件中在該函數中傳遞參數(this) disableField(this)

 function disableField(elem) { var Count = $('#dataTable tr').length; if (Count == 2){ $(elem).closest('tr').find("input").not('.DeleteButton').prop('disabled', false); } else{ $(elem).closest('tr').find("input").prop('disabled', false); }} //-------------------------------------------------- var regex = /^([a-zA-Z0-9 _-]+)$/; var cindex = 0; var quicklink = '' ; $(document).on('click','.Buttons', function(addrow) { var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length; if(count || !$('.id_100 option[value=code]').attr('selected','selected')){ alert("Please fill the current row"); return false; } var $tr = $('#dataTable tbody tr:last'); var $clone = $tr.clone(true); cindex++; $clone.find(':input').not('select').attr('disabled', true); $clone.attr('id', 'id'+(cindex) ); //update row id if required //update ids of elements in row $clone.find("*").each(function() { var id = this.id || ""; if(id != ""){ var match = id.match(regex) || []; if (match.length == 2) { this.id = this.name + (cindex); } } }); $tr.after($clone); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td> <div class="toppanel"><ul><li></li></ul></div> <div class="abcd"> <!--mainbox middlepanel start--> <table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable"> <tr> <td valign="top"> <div id="pageheadingpanel"> <div id="pageheading">Quick Link Widget Configuration</div> <div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div> </div> </td> </tr> <tr> <td height="100%" valign="top"> <div class="y_scroll" id="contentarea"> <div class="contentarea"><!--contentarea start--> <span id="box" class="box"> <!--rounded curve/border start--> <div class="middlepanel"> <!--contentarea box middlepanel start--> <div style="display:block" id="textBox1" > <span id="box1" class="box"> <div class="toppanel"><ul><li></li></ul></div> <div class="middlepanel"> <table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable"> <thead> <tr> <td class="headingalign" width="16%">Links</td> <td class="headingalign" width="32%">Desciption</td> <td class="headingalign" width="16%">Image</td> <td class="headingalign" width="16%">URL</td> <td class="headingalign" width="05%"></td> </tr> </thead> <tbody> <tr id="id0" class="vals" name="id0"> <td> <div class="id_100"> <select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField(this)" > <option value="">Select</option> <xsl:for-each select="values from local db"> <xsl:sort order="ascending" select="description"/> <option value="{description}"> <xsl:value-of select="description"/> </option> </xsl:for-each> </select> </div> </td> <td> <input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" /> </td> <td> <input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" /> </td> <td> <input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" /> </td> <td> <input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" /> </td> </tr> </tbody> </table> <div class="buttonarea"> <ul> <li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li> </ul> </div>

總而言之,有太多無關的代碼,因此以下答案具有不同的代碼,但可以應用於所提供的笨重代碼。 我建議您像此答案中提供的以下演示一樣更加精簡您的代碼。

這里有一些建議:

  • 如果您使用多個表單控件(例如<button><input><textarea><select>等), <select>所有內容包裝到<form>

  • 如果您有多個標簽(又名元素),用戶可以clicksubmitresetchangeinput等將事件注冊到<form>

  • 為了找到被單擊、更改等的確切表單控件,請使用Event.target屬性來查找它或使用this關鍵字和Event.data參數。

     $('form selector').on('event type', Event.data, callback function)
  • #id[name]屬性是不必要的,除非您使用某些 Web API,例如HTMLFormControlsCollectionHTMLFormElement

  • 使用 jQuery 時切勿使用事件屬性(例如onchange="callback()" )。 使用正確的 jQuery 方法或.on()方法

     // jQuery method $(selector).click(callback) // .on() method $(selector).on('click', callback)

末節:

  • [type]屬性不適用於<select>標記。

  • <thead>使用<th>而不是<td> <thead>

  • [maxlength]500是荒謬的。 使用<textarea>而不是<input>


詳情見demo
 /* Register form.io to the 'submit', 'click', and 'change' events Note the callback function does not have `()` suffixed because it would be interpreted as: "run function now" The callback function doesn't run immediately it runs when a registered event is triggered. */ $('.io').on('submit click change', eventHandler); // Define the counter let counter = 0; // Always pass the Event Object when defining a callback function function eventHandler(event) { // The Event Object has several properties... // Get the type of event triggered (ie submit, change, or click) let eType = event.type; /* Get the origin element of event if 'submit' target will be <form> if 'click' target will be <button> if 'change' target will be <select> */ let eNode = event.target; // Pass the event type through a switch() function... switch (eType) { // if type is 'submit'... case 'submit': // Create a deep clone of the first row let clone = $('.grid tr:first-child').clone(true, true); // Add clone as the last child of the <tbody> $('.grid').append(clone); // On .each() elment with class '.data' found within the clone... clone.find('.data').each(function(i) { // disable it this.disabled = true; // remove its value this.value = ''; }); // Increment the counter by 1 counter++; // Dereference the clone and assign id as row+counter clone[0].id = `row${counter}`; /* Prevent default behavior: Reset <form> Send data to a server */ event.preventDefault(); // Stop event from bubbling any further up the event chain event.stopPropagation(); // ...otherwise skip this case and continue onto the next case break; // if type is 'click'... case 'click': // if the clicked element (ie <button>) has class: '.del'... if ($(eNode).hasClass('del')) { // Get the clicked <button>'s ancestor <tr> let row = $(eNode).closest('tr'); // if that <tr> is NOT the first <tr>... if (row.index() !== 0) { // remove the <tr> row.remove(); } } event.stopPropagation(); break; // if type is 'change'... case 'change': // if changed element (ie <select>) class is '.type'... if ($(eNode).hasClass('type')) { // Get the changed <select>'s ancestor <tr> let row = $(eNode).closest('tr'); // if changed <select>'s value is NOT "X" return true otherwise return false let pick = eNode.value !== "X" ? true : false; /* On .each() element with class .data within the <tr> disable the .data if <select>'s value is "X" Otherwise enable the .data and then remove the .data value */ row.find('.data').each(function(i) { this.disabled = !pick; this.value = ''; }); } event.stopPropagation(); break; default: event.stopPropagation(); break; } }
 :root { font: 400 3vw/1.2 Arial } form { width: max-content; margin: 10px auto } table { table-layout: fixed; border-collapse: separate; border-spacing: 4px; width: 90vw } th:first-of-type { width: 20% } th:nth-of-type(2) { width: 35% } th:nth-of-type(3) { width: 35% } th:last-of-type { width: 10% } td { padding: 0 8px } select, textarea, button { display: block; min-width: 97%; min-height: 1.2rem; font-size: initial; } select { padding: 2px 0 2px 2px } textarea { resize: vertical; overflow-y: auto; overflow-x: hidden }
 <form class='io'> <table> <thead> <tr> <th>Type</th> <th>Desciption</th> <th>Image/URL</th> <th><button>➕</button></th> </tr> </thead> <tbody class='grid'> <tr> <td> <select class='type'> <option value="X" default></option> <option value="GDS">Guides</option> <option value="PRO">Promos</option> <option value="TEM">Templates</option> <option value="VID">Videos</option> </select> </td> <td><textarea class='desc data' rows='1' cols='20' disabled></textarea></td> <td><textarea class='urls data' rows='1' cols='20' disabled></textarea></td> <td><button class='del' type='button'>❌</button></td> </tr> </tbody> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM