Reputation: 2113
I have a small form, where only radio can be checked or only one input text can be filled. There are 6 choices but only only value will be posted.
I have this small jQuery that unchecks radio when a text is focused and vica versa
$('#angleform input[type=text]').focus(function() {
$('input[type=radio]').prop('checked', false);
});
$('#angleform input[type=radio]').click(function() {
$('input[type=text]').val('');
});
I have created this fiddle to demonstrate http://jsfiddle.net/Pdh6R/4/
What I want is if a value have been filled and I focus another input, values in not focused inputs should be cleared.
I know I can checked it by the inputs ID's, but is there a one-liner way?
Upvotes: 0
Views: 154
Reputation: 7059
Both approaches will clear any previous input state, regardless of your radio name or id simply by checking the type property of the input. This way they both only use one event handler to clear each other out, without clearing radio values!
Approach one: .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("");
}
}
}
});
demo: http://jsfiddle.net/tive/uM3tk/
Approach two: .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("");
}
});
demo: http://jsfiddle.net/tive/LUP4b/
Upvotes: 0
Reputation: 20250
You can simply clear all of the text
inputs when one gets focus:
$('#angleform input[type="text"]').val('');
Upvotes: 2