How to organize the JavaScript function that uses jQuery
Hello all,
I have the following code and would like to know how to move the change function
$("#sweets").change
outside this HTML file and use <script src=""></script> to include that function and trigger the function inside this HTML.
Thank you
- <!DOCTYPE html>
<html>
<head>
<style>
#selecttext { color:red; }
</style>
<script src="http://code.jquery.com/jquery-1.4.2.js"></script>
</head>
<body>
<div>
<select name="sweets" id="sweets">
<option value="" selected="selected">- Select One -</option>
<option title="y" value="y">Yes</option>
<option title="n" value="n">No</option>
</select>
</div>
<div id="fnameFld">
First name: <input type="text" name="fname" id="fname" /><br />
</div>
<div id="selecttext">
</div>
<script type="text/javascript">
$("#sweets").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
if ($(this).val() == "y")
{
$("#fnameFld").show();
} else {
$("#fnameFld").hide();
}
});
$("div#selecttext").text(str);
})
.change();
</script>
</body>
</html>