BN83
BN83

Reputation: 902

Run jQuery on page load with values from fields

I'm passing values from one page to another by posting them and then putting them in to hidden fields on the next page. I've tried using the initial values and that doesn't work either, so my assumption is that it's to do with the jquery not checking for initial values. This is what I want to run:

function check() {
    var Q1 = $("#question1").val();
    if (Q1 == 'yes') {
        $(".A1").css("display", "block");
    } else { 
        $(".A1").css("display", "none"); 
    }

Where #question1 is the ID of the field populated from the previous page, but how do I get the check function to run when the page has loaded? I've tried adding:

<script type="text/javascript">
    check();
</script>

To the bottom of the page with no success, the only way it works at the moment is by clicking a button with this applied:

$(".theanswer").click(function() {
    check();
    return false;
});

I'm sure there's probably a simple way i'm unaware of so any help is much appreciated.

Cheers

Upvotes: 1

Views: 1248

Answers (3)

user3811714
user3811714

Reputation: 276

Just create a js file and link it you your html page

JS File

$(document).ready(function(){
check();
});

function check() 
{
    var Q1 = $("#question1").val();

    if (Q1 == 'yes') 
    {        
        $(".A1").css("display", "block");
    } 
    else 
    { 
        $(".A1").css("display", "none"); 
    }
}

Html link

<script type="text/javascript" language="javascript" src="yourjsfilename.js"></script>

Upvotes: 0

SSA
SSA

Reputation: 5493

Warp it the call to check function in document.ready.

<script type="text/javascript">
$(document).ready(function(){
check();
})    

</script>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337626

Your check() function uses jQuery to retrieve elements. Because of this, you need to run the function after the DOM has been loaded. To do that, place the call to check() within a DOM ready event handler:

<script type="text/javascript">
    $(function() {
        check();  
    });
</script>

Also, you can simplify the check() function:

function check() {
    $('.A1').css('display', $('#question1').val() == 'yes' ? 'block' : 'none');
}

Upvotes: 3

Related Questions