2

这是小提琴:http: //jsfiddle.net/rbmako69/t5qKs/12/

这是表格:

<form id="form1" mrthod="get" action="#">
    <div date-role="fieldcontain" class="ui-hide-label">
        <label for="best_contact_method">Best Contact Method</label>
        <select data-theme="a" id="best_contact_method" name="best_contact_method" class="required" data-native-menu="false">
            <option>Best Contact Method</option>
            <option value="email">Email</option>
            <option value="daytime_phone">Daytime Phone</option>
            <option value="evening_phone">Evening Phone</option>
       </select>
    </div>
    <div data-role="fieldcontain" class="ui-hide-label">
        <label for="daytime_phone" id="daytime_phone_label">Daytime Phone</label>
        <input type="text" id="daytime_phone" name="daytime_phone" placeholder="Daytime Phone" />
    </div>
    <div data-role="fieldcontain" class="ui-hide-label">
        <label for="evening_phone" id="evening_phone_label">Evening Phone</label>
        <input type="text" id="evening_phone" name="evening_phone" placeholder="Evening Phone" />
    </div>
    <div data-role="fieldcontain" class="ui-hide-label">
        <label for="email" id="email_label">Email</label>
        <input type="text" id="email" name="email" placeholder="Email" />
    </div>
    <button type="submit" data-theme="a" name="submit" id="submit" value="validate">Validate</button>
</form>

该表单有 4 个元素、一个选择框、3 个文本输入和一个按钮。当您从选择中选择一个选项时,它会更改提交表单所需的字段。当您从下拉列表中选择选项时,您将看到输入字段更改其格式。验证工作正常,但我似乎无法弄清楚如何保持字段的格式不变。

有什么建议么?

4

1 回答 1

6

You have some mistakes in your code, I will start with .ready which should not be used with jQuery Mobile; alternatively, use pageinit.

Secondly, use .addClass and .removeClass instead of using .attr('class', 'class'). Because using the last one removes all classes and adds only the ones specified, that's why input loses formatting/style.

Another important note, with jQuery Mobile, it's better to use $('.selector').on('event', function () in case of static elements and $(document).on('event', '.selector',function () if you want to bind events to dynamically added elements

Demo

Here's the new code.

$("#best_contact_method").on('change', function () {
 var item = $("select option:selected").val();
 switch (item) {
    case "email":
        $("#email").addClass("required email");
        $("#daytime_phone, #evening_phone").removeClass("required phoneUS");
        break;
    case "daytime_phone":
        $("#daytime_phone").addClass("required phoneUS");
        $("#email, #evening_phone").removeClass("required phoneUS email");
        break;
    case "evening_phone":
        $("#evening_phone").addClass("required phoneUS");
        $("#email, #daytime_phone").removeClass("required phoneUS email");
        break;
  }
 $("#form1").validate();
});

References:

于 2013-06-19T18:03:15.667 回答