用jquery清除没有集中的输入

时间:2013-05-01 07:54:16

标签: javascript jquery html forms

我有一个小表单,只能检查无线电或只能填充一个输入文本。有6种选择,但只会发布价值。

我有这个小jQuery,当文本聚焦时取消选中无线电,反之亦然

$('#angleform input[type=text]').focus(function() {
    $('input[type=radio]').prop('checked', false);
});

$('#angleform input[type=radio]').click(function() {
    $('input[type=text]').val('');
});

我创造了这个小提琴来演示 http://jsfiddle.net/Pdh6R/4/

我想要的是如果一个值被填充并且我关注另一个输入,那么应该清除未聚焦输入中的值。

我知道我可以通过输入ID检查它,但有一种单行方式吗?

2 个答案:

答案 0 :(得分:2)

当获得焦点时,您可以简单地清除所有text输入:

$('#angleform input[type="text"]').val('');

答案 1 :(得分:0)

只需检查输入的type属性,两种方法都将清除任何先前的输入状态,无论您的无线电名称或ID如何。这样他们都只使用一个事件处理程序来清除彼此,而不清除无线电值!

接近一个:.focus()

var inputs = $("#angleform fieldset input");

// bind focus on all inputs
inputs.focus(function () {
    // loop through all
    for (var i = 0; i < inputs.length; i += 1) {
        var el = inputs.eq(i);

        // ignore focused element
        if (inputs[i] !== this) {
            // if radio type is the same => remove state
            // all other inputs can have empty value
            if (el.prop("type") === "radio") {
                el.prop("checked", false);
            } else {
                el.val("");
            }
        }
    }
});

演示: http://jsfiddle.net/tive/uM3tk/

方法二:.blur()

var inputs = $("#angleform input"),
    myChoice;

// bind .blur() on inputs
inputs.blur(function () {
    myChoice = $(this);

    // if input type is radio
    if (myChoice.prop("type") === "radio") {
        myChoice.prop("checked", false);
    } else {
        myChoice.val("");
    }
});

演示: http://jsfiddle.net/tive/LUP4b/

相关问题