简体   繁体   中英

Showing/hiding hint text

I've created a .js file with the following in it:

$('.emailhinttext').hide();
$('select').change(function() {
if ($(this).val() == 'For yourself, your church, school, a friend etc...') {
    $('.emailhinttext').show();
}
if ($(this).val() == 'A Charity like Oxfam, Marie Curie or Help the Aged') {
    $('.emailhinttext').hide();
}
});

It does have a couple of other things in it (Should that matter?) and I include the file in the header of my page along with jQuery.

my html is:

<div class="input select">
    <label for="I am raising money for">I am raising money for...</label>
    <select name="data[I am raising money for]" id="I am raising money for">
        <option value="0">A Charity like Oxfam, Marie Curie or Help the Aged</option>
        <option value="1">For yourself, your church, school, a friend etc...</option>
</select></div>
<div class="input text required">
    <label for="UserEmail">Email&nbsp;&nbsp;<div class="emailhinttext">*Please use the same email as your paypal account</div></label>
    <input name="data[User][email]" type="text" maxlength="255" id="UserEmail" />
</div>

It doesn't work even though on jsfiddle something really similar works fine. What am I doing wrong?

The val() is either 0 or 1 (the value of value attribute), and not the text inside the option tag. So changing to if ($(this).val() == 1) will resolve your problem

Check a few things, you reference jQuery before your script, also make sure your script is wrapped in the document.ready call like:

$(document).ready(function(){
    // your code goes here
});

Any of that help?

This happens quite a lot; your jQuery code isn't executed when the page is loaded. You need to wrap it in a $(document).ready() function, like so:

$(document).ready(function()
{
    $('.emailhinttext').hide();

    $('select').change(function() 
    {
        if ($(this).val() == 'For yourself, your church, school, a friend etc...') 
        {
            $('.emailhinttext').show();
        }
        if ($(this).val() == 'A Charity like Oxfam, Marie Curie or Help the Aged') 
        {
            $('.emailhinttext').hide();
        }
    });
});

This will execute the jQuery when the document has loaded, instead of having it just sit in the DOM not doing much.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM