好的,这是我要做的第一件事:
1) 假设用户一直在向一个或两个输入字段添加文本。现在,如果用户选择选择字段的选项值“Name1” 或选项值“Name2”,则必须重置输入字段值。如何做到这一点?
<div id='CustomerIsNotInDatabase'>
<input id='vlastname' name='ulastname' type='text' value=''></input>
<input id='vfirstname' name='ufirstname' type='text' value=''></input>
</div>
<div id='customerIsInDatabase'>
<select>
<option selected='true' value=''>Choose</option>
<option value='Name1'></option>
<option value='Name2'></option>
</select>
</div>
2) 现在反过来说:如果选择了选项值“Name1”或选项值“Name2”:如果用户向输入字段添加文本?
最佳答案
1.第一个问题。
If the user is either selecting option value 'Name1' or option value 'Name2' of the select field the input fields value have to be reseted
您可以使用 change
事件来处理用户更改并使用 val('')
重置输入:
$('#customerIsInDatabase select').change(function(){
if ( $(this).val() != '' )
{
$('#vlastname').val('');
$('#vfirstname').val('');
}
});
2.第二个问题。
If either option value 'Name1' or option value 'Name2' is selected: How can this value be reseted to the 1st option with value '' if the user adds text to an input field?
您可以使用 keyup
事件来检测在 input
字段中按下任何键时的用户操作:
$('#CustomerIsNotInDatabase input').keyup(function()
{
$('#customerIsInDatabase select').val('').change();
});
希望这对您有所帮助。
完整示例:
$('#customerIsInDatabase select').change(function()
{
if ( $(this).val() != '' )
{
$('#vlastname').val('');
$('#vfirstname').val('');
}
});
$('#CustomerIsNotInDatabase input').keyup(function()
{
$('#customerIsInDatabase select').val('').change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='CustomerIsNotInDatabase'>
<input id='vlastname' name='ulastname' type='text' value=''></input>
<input id='vfirstname' name='ufirstname' type='text' value=''></input>
</div>
<div id='customerIsInDatabase'>
<select>
<option selected='true' value=''>Choose</option>
<option value='Name1'>Name1</option>
<option value='Name2'>Name2</option>
</select>
</div>
关于javascript - 通过单击 SELECT 选项将 text-INPUT 元素的 VALUE 动态设置为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33861554/