jQuery: if value is true without user action
I want to show a div if the value of an input =='CP'.
Right now this is my code:
$(".register-type").chan开发者_开发知识库ge(function(){
var value = $(this).val();
if(value == 'CP'){
$('.cp-show').show();
This works fine if they change the input, but if things get validated false and the page reloads, this input is still 'CP', but the div doesn't show...
Is there a way to correct this so that jquery checks if this is set on the page load?
Use document.ready
for checking at load time.
var register = $(".register-type")[0];
function show_cp() {
if(register.value == 'CP') {
$('.cp-show').show();
}
}
reg_type.change(show_cp); // when the input changes
$(document).ready(show_cp); // when the page is loaded
Why not triggering it the first time..
$(".register-type")
.change(function(){
var value = this.value; // changeed the .val() since it is not needed here.
if(value == 'CP'){
$('.cp-show').show();
})
.trigger('change');
Yes, add to your 'document ready' function:
$(document).ready(function() {
if($(".register-type").val() == 'CP'){
$('.cp-show').show();
}
});
精彩评论