I'm trying to create and 'edit' mode for my application on the Manage Users page. I have every users values (such as name, email, etc) inside of an <input>
tag with the readonly
attribute. I have a button at the top of the page called "Edit Mode". When that edit mode is clicked, I would like the admin to be able to then click on the input field and change it. I am able to successfully toggle the readonly
attribute on click BUT I only want that feature to happen when editing == true
but for some season it seems that the DOM is never sensing when the editing boolean has been changed. Here is the code
$(document).ready(function(){
var editing = false;
$(".edit-mode-toggle").click(function(){
editing = true;
});
if(editing){
$("user-block input").click(function(){
$(this).removeAttr("readonly");
});
}
$(".user-block input").blur(function(){
$(this).attr("readonly", true);
})
});
Again I would only like to removeAttr
when the ".edit-mode-toggle"
button is clicked and changes the editing
variable to true
. My current output is that when I click that button to toggle the boolean, I'm not able to execute my editing because the DOM hasn't seen the boolean has changed. Anyone know what might be going on. Im sure ill derp once I find a solution. I'm just drawing blanks here. Strictly jQuery by the way, I know this can be easily done with Angular or some other 3 way data binding framework but I want to avoid using those. Thank you!
Dom only runs that if(editing)
condition at load time, you want to move that part into your click
function.
$("user-block input").click(function(){
if(editing){
$(this).removeAttr("readonly");
}
});
Also, you need to define the var editing
outside of the $(document).ready()
function.
var editing = false;
$(document).ready(function(){
//other stuff
})
You should update your code because you are attaching the click events in the page load, and the second condition in the IF statement will always get attached because 'editing' variable is always set to false in the page load.
to fix it you have to make the variable 'editing' a global variable
var editing = false;
$(document).ready(function(){
$(".edit-mode-toggle").click(function(){
editing = true;
});
$("user-block input").click(function(){
if(editing){
$(this).removeAttr("readonly");
}else {
$(this).attr("readonly", true);
}
});
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.