jQuery Скрыть / показать текстовое поле при выборе флажка — работает в скрипте, но не на живом сайте

#jquery #html #checkbox

#jquery #HTML #флажок

Вопрос:

У меня есть функция jQuery, которая скрывает и показывает поле формы, когда установлен флажок, следующим образом:

 $(document).ready(function (){
$("#unlistedUser").click(function () {
if ($(this).prop('checked') === true) {
    $('#unlistedCharacterName').show();
} else {
    $('#unlistedCharacterName').hide();
}
});
});
  

Когда этот флажок установлен:

 <input type="checkbox" name="unlistedUser" id="unlistedUser" />
  

Это поле ввода текста должно появляться и исчезать:

 <input type="text" name="unlistedCharacterName" id="unlistedCharacterName" placeholder="Unlisted Character Name" />
  

Это работает в Fiddle (http://jsfiddle.net/jza7Z/2 /)

Но, хоть убейте, я не могу заставить это работать в коде сайта:

 <!DOCTYPE html>
<html lang="en">
<head profile="http://www.w3.org/2005/10/profile">
<title>Heroes and Heroines New Template</title>

<meta name="Description" content="Insert Description Here"/>
<meta name="keywords" content="Insert Keywords Here"/>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<meta name="verify-v1" content="RPPDJPv5dTQ9yRcClT4OQvFw8UfoiikpHc7NMKZV1Ag=" />
<meta name="msvalidate.01" content="26F28B51162242249219D0C4D1BAD146" />

<link rel="alternate" type="application/rss xml" title="Heroes and Heroines News" href="/HandHRSS.xml" />

<link rel="shortcut icon" type="image/png" href="http://www.heroesandheroines.org/favicon.ico">

<link rel="stylesheet" type="text/css" href="/Styles/reset.css" />
<link rel="stylesheet" type="text/css" href="/Styles/newMain.css" />
<link rel="stylesheet" type="text/css" href="/Styles/DatePicker.css" />
<!--[if gte IE 9]>
<style type="text/css">
    .gradient {
       filter: none;
    }
  </style>
<![endif]-->
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="/Styles/newMainIe.css" />
<![endif]-->
<!--[if lte IE 7]>
<link rel="stylesheet" type="text/css" href="/Styles/newMainIe876.css" />
<script type="text/javascript" src="/js/unitpngfix.js"></script>
<![endif]-->

<link rel="stylesheet" type="text/css" href="/Styles/admin.css" />
<link rel="stylesheet" type="text/css" href="/modules/events/events.css" />

<script type="text/javascript" src="Jquery/jquery.js"></script>
<script type="text/javascript" src="Jquery/jquery-ui-1.8.6.custom.min.js"></script>
<script type="text/javascript" src="/CC.js" language="JScript"></script>
<script type="text/javascript" src="/AJAX.js" language="JScript"></script>
<script type="text/javascript">
function confirmPost()
{
var agree=confirm("Are you sure you want to delete?");
if (agree)
return true ;
else
return false ;
}
</script><script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<script>
$(document).ready(function (){
$("#role").change(function() {
if ($(this).val() == "Player") {
$("#CharacterName").show();
}else{
$("#CharacterName").hide();
} 
});
});
</script>
<script>
function confirmAction(){
var confirmed = confirm("Are you sure you want to delete this?");
return confirmed;
}
</script>
<script>
$(document).ready(function (){
$("#unlistedUser").click(function () {
if ($(this).prop('checked') === true) {
    $('#unlistedCharacterName').show();
} else {
    $('#unlistedCharacterName').hide();
}
});
});
</script>
</head>

<body>

    <div id="container">

        <div id="header">

            <div id="site_logo">
                <a href="/index.php">
                    <img src="/img/hand-of-good-symbol.png" alt="Heroes and Heroines Live Action Roleplaying (Larp)" 
                        title="Heroes and Heroines Live Action Roleplaying (Larp)" />
                </a>
            </div>

            <div id="site_name">
                <p class="site_title">Heroes and Heroines</p>
                <p class="site_sub_title">Live Action Roleplaying</p>

            </div>

            <div id="info_box">
                <div id="nextEvent">
                    <a href="http://www.heroesandheroines.org/heroes-and-heroines-larp-and-lrp-events.php"><img src="/img/template/calendar-logo.png" alt="next event" /></a>Next Event: <a href="http://www.heroesandheroines.org/heroes-and-heroines-larp-and-lrp-events/101_bring-him-home.html">11 - 13 July 2014</a>
                </div>
                <div id="galleryUpdate">
                    <a href="/heroes-and-heroines-larp-and-lrp-photo-gallery.php"><img src="/img/template/gallery-logo.png" alt="next event" /></a>
                    5 New Images in the <a href="/heroes-and-heroines-larp-and-lrp-photo-gallery.php">Gallery</a>
                </div>
                <div id="messageUpdate">
                    <!-- <a href="/heroes-and-heroines-message-system.php"><img src="/img/template/message-logo.png" alt="next event" /></a>
                    1 New <a href="/heroes-and-heroines-message-system.php">Message</a> -->
                    <a href="/new-forums/ucp.php?i=pmamp;folder=inbox"><img src="/img/template/message-logo.png" alt="Private Messages" /></a>
0 New <a href="/new-forums/ucp.php?i=pmamp;folder=inbox">Messages</a>

                </div>
                <div id="forumUpdate">
                    <!-- <a href="/heroes-and-heroines-live-action-roleplaying-forum.php"><img src="/img/template/forum-logo.png" alt="next event" /></a>
                    1 New <a href="/heroes-and-heroines-live-action-roleplaying-forum.php">Forum Post</a> -->
                    <a href="/new-forums/search.php?search_id=unreadposts"><img src="/img/template/forum-logo.png" alt="Forum Posts" /></a>
0 New <a href="/new-forums/search.php?search_id=unreadposts">Forum Posts</a>
                </div>
                <div id="newsUpdate">
                    <a href="/heroes-and-heroines-live-action-roleplaying-news.php"><img src="/img/template/news-logo.png" alt="next event" /></a>
                    1 New <a href="/heroes-and-heroines-live-action-roleplaying-news.php">News Item</a>
                </div>
            </div>

            <div id="character_selector">
            Logged in as sebsmith <br /><div class="linkButton"><form method="post" action="http://www.heroesandheroines.org/new-forums/ucp.php?mode=logoutamp;amp;sid=c8a6b8f8ecae9a5736bd9a057c763521"><input type="submit" value="Logout" /></form></div><div class="linkButton"><form method="post" action="http://www.heroesandheroines.org/new-forums/ucp.php"><input type="submit" value="Control Panel" /></form></div>
            </div>


        </div> 

        <div id="body">

            <div id="main_menu_container">

                <div class="menu_bottom_bar"></div>
            </div>

            <div id="content_container">
                <HHTEMPLATE::siteMsg>
                <h1><span class="firstWord">Heroes</span> and Heroines Live Action Roleplay (Larp/LRP)</h1>
                <h2 id="siteSubHeader">A UK Live Roleplaying Group Based in The West Midlands</h2>

                <h2>Welcome to the Heroes and Heroines Event Booking Manager</h2>
 <h3>Make a booking for a friend for Bring him home (Fri 11 Jul - Sun 13 Jul 2014) </h3>
<div class="eventBookingForm">
 <div class="bookingFormDiv RefName">
<strong>Ref</strong>: Katie
 </div>
 <div class="bookingFormDiv Rank">
<strong>Rank</strong>: Low rank 5-26
 </div>
 <div class="bookingFormDiv Location">
<strong>Location</strong>: Consall Scout camp
 </div>
 <div class="bookingFormDiv Cost">
<strong>Cost</strong>: 
 </div>
 <h3>Booking Form</h3>
<p><form method="post" action="/heroes-and-heroines-larp-and-lrp-events.php?task=submitFriendBooking" class="bookingForm"><p><input type="checkbox" name="unlistedUser" id="unlistedUser" /> I am booking for a friend without a Heroes and Heroines User Account</p>
<label for="role">Booking:</label>
<select name="role" id="role">
<option value="Player">Play</option>
<option value="Monster">Monster</option>
<option value="MIA">Unable to Attend</option>
<option value="Referee">Referee</option>
</select><br />
<div id="CharacterName"><label for="characterName">Character Name:</label><select  name="CharacterName"><option value="122">Jack Dawkins</option><option value="197">Reverand Blighty Shrewson</option><option value="243">Sydion</option><option value="257">Englebert Waddicore-Critchley</option><option value="308">Brishen</option><option value="1015">yArp</option><option value="1017">NPC</option>
</select> <input type="text" name="unlistedCharacterName" id="unlistedCharacterName" placeholder="Unlisted Character Name" /></div>
<label for="bookingName">Attendee Name:</label><select name="bookingName">
<option value="112">3rd spearman</option>
</select> <input type="text" name="unlistedUserName" placeholder="Unlisted User Name" />
<div id="telephoneNumber"><label for="telephone">Telephone Number:</label>
<input required type="tel" id="telephone" name="telephone" value="01772 461406" /> <input type="tel" name="unlistedUserTelephone" placeholder="Unlisted User Telephone Number" /></div>
<div id="emailAddress"><label for="email">E-mail Address:</label>
<input required type="email" id="email" name="email" value="sebsmith@blueyonder.co.uk" /> <input type="email" name="unlistedUserEmail" placeholder="Unlisted User Email" /></div>
<div id="notes"><label for="notes">Notes:</label>
<textarea id="notes" name="notes" rows="4" cols="50" placeholder="notes" /></textarea>
</div><input type="hidden" name="returnPage" value="http://www.heroesandheroines.org/heroes-and-heroines-larp-and-lrp-events/101_bring-him-home.html" />
<input type="hidden" name="dungeonid" value="101" /> <input type="hidden" name="unlistedUserBookerID" value="2"/>
<input type="submit" name="submit Booking" value="Submit Booking" />
<input type="submit" name="cancel Booking" value="Cancel Booking"></p>
</form>
</div><div class="clearDiv"></div>

            </div>

        </div>

        <div id="footer">

            <div id="footer_menu_container">
                <div id="copyright_statement">
                    amp;copy; All content, images and design copyright Heroes and Heroines Live Roleplaying Club, 2012 unless otherwise specified
                </div>
            </div>


        </div>
    </div>
</body>
</html>
  

За последние пару дней я перепробовал все, что мог придумать, добавляя и удаляя элементы, переименовывая элементы, разбирая материал, пока почти ничего не осталось, ругаясь, выпивая, и все безрезультатно. jQuery далек от моей сильной стороны. Кто-нибудь может увидеть что-нибудь очевидное, что мешает моему скрипту работать так, как это происходит в Fiddle?

Спасибо!

Seb

Комментарии:

1. Какие ошибки вы получаете в консоли?

2. Использование getUserData() или setUserData() устарело. Вместо этого используйте WeakMap или element.dataset. requestNotifier.js:63 SyntaxError: Использование //@ для указания прагм sourceMappingURL устарело. Используйте //# вместо jquery.min.js: Ошибка 4: ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js присваивается //# sourceMappingURL, но уже имеет одно использование getPreventDefault(), которое устарело. Вместо этого используйте defaultPrevented. jquery.min.js:2 Использование указанного атрибута attributes устарело. Он всегда возвращает true. jquery.min.js: 1

Ответ №1:

попробуйте:

 $(document).ready(function (){
$("#unlistedUser").click(function () {
if ($(this).is(':checked')) {
    $('#unlistedCharacterName').show();
} else {
    $('#unlistedCharacterName').hide();
}
});
});
  

jQuery говорит, что prop и is должны возвращать одно и то же, но я чувствую себя более комфортно с is . Кроме того, убедитесь, что вы используете версию jQuery > = 1.8.3, поскольку ваш fiddle работает с этой версией.

измените это:

 <script type="text/javascript" src="Jquery/jquery.js"></script>
  

к этому:

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  

РЕДАКТИРОВАТЬ: я изменил весь HTML с помощью скриптов, вот полный исходный код:

 <!DOCTYPE html>
<html lang="en">
<head profile="http://www.w3.org/2005/10/profile">
<title>Heroes and Heroines New Template</title>

<meta name="Description" content="Insert Description Here"/>
<meta name="keywords" content="Insert Keywords Here"/>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<meta name="verify-v1" content="RPPDJPv5dTQ9yRcClT4OQvFw8UfoiikpHc7NMKZV1Ag=" />
<meta name="msvalidate.01" content="26F28B51162242249219D0C4D1BAD146" />

<link rel="alternate" type="application/rss xml" title="Heroes and Heroines News" href="/HandHRSS.xml" />

<link rel="shortcut icon" type="image/png" href="http://www.heroesandheroines.org/favicon.ico">

<link rel="stylesheet" type="text/css" href="/Styles/reset.css" />
<link rel="stylesheet" type="text/css" href="/Styles/newMain.css" />
<link rel="stylesheet" type="text/css" href="/Styles/DatePicker.css" />
<!--[if gte IE 9]>
<style type="text/css">
    .gradient {
       filter: none;
    }
  </style>
<![endif]-->
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="/Styles/newMainIe.css" />
<![endif]-->
<!--[if lte IE 7]>
<link rel="stylesheet" type="text/css" href="/Styles/newMainIe876.css" />
<script type="text/javascript" src="/js/unitpngfix.js"></script>
<![endif]-->

<link rel="stylesheet" type="text/css" href="/Styles/admin.css" />
<link rel="stylesheet" type="text/css" href="/modules/events/events.css" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<!--<script type="text/javascript" src="Jquery/jquery-ui-1.8.6.custom.min.js"></script>-->
<script type="text/javascript" src="/CC.js"></script>
<script type="text/javascript" src="/AJAX.js"></script>
<script type="text/javascript">
    // short form for $(document).ready()
    $(function () {
        $("#role").change(function () {
            $('#unlistedCharacterName').css('display', ($(this).val() == "Player") ? 'inline' : 'none');
        });

        $("#unlistedUser").click(function () {
            $('#unlistedCharacterName').css('display', $(this).is(':checked') ? 'inline' : 'none');
        });
    });

    function confirmAction() {
        return confirm("Are you sure you want to delete this?");
    }

    function confirmPost() {
        return confirm("Are you sure you want to delete?");
    }
</script>
</head>

<body>

    <div id="container">

        <div id="header">

            <div id="site_logo">
                <a href="/index.php">
                    <img src="/img/hand-of-good-symbol.png" alt="Heroes and Heroines Live Action Roleplaying (Larp)" 
                        title="Heroes and Heroines Live Action Roleplaying (Larp)" />
                </a>
            </div>

            <div id="site_name">
                <p class="site_title">Heroes and Heroines</p>
                <p class="site_sub_title">Live Action Roleplaying</p>

            </div>

            <div id="info_box">
                <div id="nextEvent">
                    <a href="http://www.heroesandheroines.org/heroes-and-heroines-larp-and-lrp-events.php"><img src="/img/template/calendar-logo.png" alt="next event" /></a>Next Event: <a href="http://www.heroesandheroines.org/heroes-and-heroines-larp-and-lrp-events/101_bring-him-home.html">11 - 13 July 2014</a>
                </div>
                <div id="galleryUpdate">
                    <a href="/heroes-and-heroines-larp-and-lrp-photo-gallery.php"><img src="/img/template/gallery-logo.png" alt="next event" /></a>
                    5 New Images in the <a href="/heroes-and-heroines-larp-and-lrp-photo-gallery.php">Gallery</a>
                </div>
                <div id="messageUpdate">
                    <!-- <a href="/heroes-and-heroines-message-system.php"><img src="/img/template/message-logo.png" alt="next event" /></a>
                    1 New <a href="/heroes-and-heroines-message-system.php">Message</a> -->
                    <a href="/new-forums/ucp.php?i=pmamp;folder=inbox"><img src="/img/template/message-logo.png" alt="Private Messages" /></a>
0 New <a href="/new-forums/ucp.php?i=pmamp;folder=inbox">Messages</a>

                </div>
                <div id="forumUpdate">
                    <!-- <a href="/heroes-and-heroines-live-action-roleplaying-forum.php"><img src="/img/template/forum-logo.png" alt="next event" /></a>
                    1 New <a href="/heroes-and-heroines-live-action-roleplaying-forum.php">Forum Post</a> -->
                    <a href="/new-forums/search.php?search_id=unreadposts"><img src="/img/template/forum-logo.png" alt="Forum Posts" /></a>
0 New <a href="/new-forums/search.php?search_id=unreadposts">Forum Posts</a>
                </div>
                <div id="newsUpdate">
                    <a href="/heroes-and-heroines-live-action-roleplaying-news.php"><img src="/img/template/news-logo.png" alt="next event" /></a>
                    1 New <a href="/heroes-and-heroines-live-action-roleplaying-news.php">News Item</a>
                </div>
            </div>

            <div id="character_selector">
            Logged in as sebsmith <br /><div class="linkButton"><form method="post" action="http://www.heroesandheroines.org/new-forums/ucp.php?mode=logoutamp;amp;sid=c8a6b8f8ecae9a5736bd9a057c763521"><input type="submit" value="Logout" /></form></div><div class="linkButton"><form method="post" action="http://www.heroesandheroines.org/new-forums/ucp.php"><input type="submit" value="Control Panel" /></form></div>
            </div>


        </div> 

        <div id="body">

            <div id="main_menu_container">

                <div class="menu_bottom_bar"></div>
            </div>

            <div id="content_container">
                <HHTEMPLATE::siteMsg>
                <h1><span class="firstWord">Heroes</span> and Heroines Live Action Roleplay (Larp/LRP)</h1>
                <h2 id="siteSubHeader">A UK Live Roleplaying Group Based in The West Midlands</h2>

                <h2>Welcome to the Heroes and Heroines Event Booking Manager</h2>
 <h3>Make a booking for a friend for Bring him home (Fri 11 Jul - Sun 13 Jul 2014) </h3>
<div class="eventBookingForm">
 <div class="bookingFormDiv RefName">
<strong>Ref</strong>: Katie
 </div>
 <div class="bookingFormDiv Rank">
<strong>Rank</strong>: Low rank 5-26
 </div>
 <div class="bookingFormDiv Location">
<strong>Location</strong>: Consall Scout camp
 </div>
 <div class="bookingFormDiv Cost">
<strong>Cost</strong>: 
 </div>
 <h3>Booking Form</h3>
<p><form method="post" action="/heroes-and-heroines-larp-and-lrp-events.php?task=submitFriendBooking" class="bookingForm"><p><input type="checkbox" name="unlistedUser" id="unlistedUser" /> I am booking for a friend without a Heroes and Heroines User Account</p>
<label for="role">Booking:</label>
<select name="role" id="role">
<option value="Player">Play</option>
<option value="Monster">Monster</option>
<option value="MIA">Unable to Attend</option>
<option value="Referee">Referee</option>
</select><br />
<div id="CharacterName"><label for="characterName">Character Name:</label><select  name="CharacterName"><option value="122">Jack Dawkins</option><option value="197">Reverand Blighty Shrewson</option><option value="243">Sydion</option><option value="257">Englebert Waddicore-Critchley</option><option value="308">Brishen</option><option value="1015">yArp</option><option value="1017">NPC</option>
</select> <input type="text" name="unlistedCharacterName" id="unlistedCharacterName" style="display: none;" placeholder="Unlisted Character Name" /></div>
<label for="bookingName">Attendee Name:</label><select name="bookingName">
<option value="112">3rd spearman</option>
</select> <input type="text" name="unlistedUserName" placeholder="Unlisted User Name" />
<div id="telephoneNumber"><label for="telephone">Telephone Number:</label>
<input required type="tel" id="telephone" name="telephone" value="01772 461406" /> <input type="tel" name="unlistedUserTelephone" placeholder="Unlisted User Telephone Number" /></div>
<div id="emailAddress"><label for="email">E-mail Address:</label>
<input required type="email" id="email" name="email" value="sebsmith@blueyonder.co.uk" /> <input type="email" name="unlistedUserEmail" placeholder="Unlisted User Email" /></div>
<div id="notes"><label for="notes">Notes:</label>
<textarea id="notes" name="notes" rows="4" cols="50" placeholder="notes" /></textarea>
</div><input type="hidden" name="returnPage" value="http://www.heroesandheroines.org/heroes-and-heroines-larp-and-lrp-events/101_bring-him-home.html" />
<input type="hidden" name="dungeonid" value="101" /> <input type="hidden" name="unlistedUserBookerID" value="2"/>
<input type="submit" name="submit Booking" value="Submit Booking" />
<input type="submit" name="cancel Booking" value="Cancel Booking"></p>
</form>
</div><div class="clearDiv"></div>

            </div>

        </div>

        <div id="footer">

            <div id="footer_menu_container">
                <div id="copyright_statement">
                    amp;copy; All content, images and design copyright Heroes and Heroines Live Roleplaying Club, 2012 unless otherwise specified
                </div>
            </div>


        </div>
    </div>
</body>
</html>
  

Я также сделал текстовое поле изначально скрытым, но вы можете изменить это, удалив атрибут style: style="display: none;"

Комментарии:

1. Спасибо за вашу помощь, попробовал это только сейчас, но все еще без радости … : (

2. @ The All Powerful Жаль это слышать .. не могли бы вы, пожалуйста, попробовать обновленный исходный код? У меня это работает в Firefox, Chrome и IE.

3. ТЫ МОЙ ГЕРОЙ! Ваш новый код работает отлично! Большое спасибо! 🙂 Итак, если я правильно смотрю на это, пользовательский интерфейс jQuery был причиной ошибки? или это было в моем скрипте jQuery?

4. Я не думаю, что пользовательский интерфейс jQuery был проблемой. Я полагаю, что ваш скрипт был неправильным / не обновленным. Причина, по которой я так считаю, заключается в том, что в JSFiddle вы не поместили свой скрипт jQuery, но использовали скрипт Fiddle, и он отлично работал. Итак, я бы рекомендовал всегда использовать размещенные библиотеки от Google или Microsoft. Поскольку другие пользователи посещают другой веб-сайт, у них, скорее всего, jQuery уже кэширован, и им не нужно будет загружать его снова, уменьшая трафик. Проверьте это: developers.google.com/speed/libraries Приветствия!