对动态插入的表单元素禁用下一个表单字段

Disable next form field on dynamically inserted form elements

本文关键字:表单 下一个 字段 元素 插入 动态      更新时间:2023-09-26

我知道这个问题以前被问过很多次,但这些解决方案似乎都不适用于我的情况。

我需要每行上的复选框来禁用下一个文本字段。每个表行都是动态创建的(JS克隆)。只有第一行是静态的。接下来的每一行,名称和ID都会附加一个新的数字(formfield1、formfield2等),并在页面加载后发生。

HTML

    <div class="add_rec_container" id="fuel_stop" style="display:block;"><!--open #fuel_stop-->
    <p class="label">Enter Fuel Stop:</p>
    <table width="100%" border="0" cellspacing="0" cellpadding="0" id="fuel_stop_table" class="fuel_data">
      <tbody>
        <tr>
          <td><select name="data_fuel_state1" id="data_fuel_state1" class="state_menu">
            <option value="AZ">AZ</option>
            <option value="CA" selected="selected">CA</option>
            <option value="NM">NM</option>
            <option value="NV">NV</option>
            <option value="OR">OR</option>
            <option value="UT">UT</option>
            </select>
            </td>
          <td><input type="tel" name="data_total_gal1" id="data_total_gal1" class="help total_gal_field" title="Gallons"/></td>
          <td><input type="checkbox" name="data_yard1" id="data_yard1" class="enablePPG" value="yes" onclick="disablePPG(this);"/> Yard
          </td>
          <td>$ <input type="tel" name="data_price1" id="data_price1" class="help price_field" title="PPG" /></td>
          </tr>
        </tbody>
    </table>
    <a id="add_fuel_row" class="add_btn">+ State</a>
    </div><!--close #fuel_stop-->
  <input type="submit" name="Submit" class="send_button" value="Send"/>
</form>​
</div><!--close .record_entry_container-->

JS(不工作,但我认为应该)

function disablePPG() {
  $(this).click(function() {
    if ($(this).is(':checked')){
        $(this).next('.price_field').prop('disabled', true);
      } else {
        $(this).next('.price_field').prop('disabled', false);
      }
  });
}

下面的JS适用于表单元素的第一行,但显然不是添加多行的解决方案。

function disablePPG() {
  $(this).click(function() {
    if ($('#data_yard1').is(':checked')) {
      $('#data_price1').prop('disabled', true);
    } else {
      $('#data_price1').prop('disabled', false);      
    }
  });
}

非常感谢您的帮助。

$(".enablePPG").on("click", function()
{
    if($(this).is(":checked") == true)
        $(this).parent().next().children().attr("disabled", "disabled");
    else
        $(this).parent().next().children().removeAttr("disabled");
});