我有两个按钮,编辑和保存。当用户单击编辑时,输入框变为可访问。如何让保存按钮正常工作?这意味着,当用户单击“保存”时,他们输入的文本将更新到数据库。我有以下代码,编辑按钮工作,但当我单击保存按钮时,它消失,“编辑”按钮变得无法访问。请帮忙!
JS:
$(".home").html('<label>Name:</label><input id="editInput" disabled="true" id="userFullName" value="' + ui.fullName +'" type="text"><button class="edit">Edit</button><button class="save">Save</button>');
$(".edit").click(function (e) {
$("#editInput").prop('disabled',false);
});
$(".save").click(function (e) {
$(this).closest('div').find('input').attr('readonly', 'readonly');
$(this).closest('div').find('.save').hide();
$(this).closest('div').find('.edit').show();
var inputValue=$(this).closest('div').find('input').val();
$.ajax({ URL:"https://api.mlab.com/api/1/databases/spk-db/collections/dwUsers/58f62d66c2ef164e6b93a162?apiKey=apiKey",
type:"POST",
data:{ inputValue:inputValue },
success:function(data){
swal("Congrats", "Your name has been saved!", "success");
}
});
});
}
答案 0 :(得分:2)
请检查代码中的以下行:
$(this).closest('div').find('input').attr('readonly', 'readonly');
单击“保存”按钮时,上面的代码只读输入。因此看起来编辑按钮已无法访问(如您的问题中所述)。
$(this).closest('div').find('.save').hide();
以上行隐藏了保存按钮。
<强>解决方案强>
更改编辑按钮上的点击事件代码,如下所示:
$(".edit").click(function (e) {
$("#editInput").prop('disabled',false);
// Make input accessible
$("#editInput").prop('readonly', false);
// Show the save button
$(".save").show();
});
$(document).ready(function(){
$(".home").html('<label>Name:</label><input id="editInput" disabled="true" id="userFullName" value="" type="text"><button class="edit">Edit</button><button class="save">Save</button>');
$(".edit").click(function (e) {
$("#editInput").prop('disabled',false);
$("#editInput").prop('readonly', false);
$(".save").show();
});
$(".save").click(function (e) {
$(this).closest('div').find('input').prop('disabled',true);
$(this).closest('div').find('input').attr('readonly', 'readonly');
$(this).closest('div').find('.save').hide();
$(this).closest('div').find('.edit').show();
var inputValue=$(this).closest('div').find('input').val();
$.ajax({ URL:"https://api.mlab.com/api/1/databases/spk-db/collections/dwUsers/58f62d66c2ef164e6b93a162?apiKey=apiKey",
type:"POST",
data:{ inputValue:inputValue },
success:function(data){
alert('name saved');
},
error: function(){
alert('ajax error. Maybe StackOverflow does not allow ajax requests');
}
});
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="home"></div>
&#13;