[英]jQuery hide and show input value
我要寻找的是未选中该框时,在输入中不显示任何值,而选中该框时,则显示每个输入及其相应值。
这是我的代码:
$('#checkbox').change(function() {
if($('#checkbox').is(':checked')) {
$('.test').val('')
} else {
}
});
一种实现方法是声明一个变量。
var inputValue;
$('#checkbox').change(function(){
if ($('#checkbox').is(':checked')){
inputValue = $('.test').val();
$('.test').val('');
} else {
$('.test').val(inputValue);
}
});
对于多个输入字段。 @Rashid的想法很棒。 将值存储在data-value属性中。 取消选中该复选框后,您可以使用data-value属性获取值。
$('#checkbox').change(function() {
if($('#checkbox').is(':checked')) {
$.each($('.test'),function(){
$(this).attr('data-value',$(this).val()).val("");
});
} else {
$.each($('.test'),function(){
$(this).val($(this).attr('data-value'));
});
}
});
您可以尝试以下方法:
$(document).ready(function(){ $('input[type="checkbox"]').click(function(){ var $this = $(this); var $item = $this.attr('name'); var $input = $('input[name="'+$item+'"][type="text"]'); var $inputValue = $input.val(); if ($this.is(':checked')){ $input.data('oldvalue',$inputValue); $input.val(''); } else { $input.val($input.data('oldvalue')); } }); });
body{line-height: 1.5;} input{display: block;margin: 10px 0 0;} input[type="checkbox"] { display: inline;} label{ margin: 0 10px 0 5px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="options"> <input type="checkbox" name="title"><label>Title</label> <input type="checkbox" name="author"><label>Author</label> <input type="checkbox" name="category"><label>Category</label> </div> <div class="container"> <form method="post"> <input type="text" name="title" placeholder="Title:"> <input type="text" name="author" placeholder="Author:"> <input type="text" name="category" placeholder="Category:"> <input type="submit" value="Submit"> </form> </div>
在代码中, #checkbox
时,将删除该值。 这不是隐藏元素的方式。 只需使用CSS显示来隐藏/显示元素。
$('#checkbox').change(function() {
if ($('#checkbox').is(':checked')) {
$('.test').css('display', 'none');
} else {
$('.test').css('display', 'block');
}
});
$('#checkbox').change(function() { if($('#checkbox').is(':checked')) { var value = $('.test').val() $('.test').data('value',value).val('') } else { var value = $('.test').data('value') $('.test').val(value) } });
尝试这个
<input type="checkbox" id="myCheck" onclick="myFunction()">
function myFunction() {
// Get the checkbox
var checkBox = document.getElementById("myCheck");
// Get the output text
var text = document.getElementById("text");
// If the checkbox is checked, display the output text
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
我认为您应该使用toggle()
jQuery函数。
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var item = $(this).attr('name');
$('input[name="'+item+'"][type="text"]').toggle();
});
});
还检查小提琴:-http: //jsfiddle.net/aaTq3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.