简体   繁体   中英

How do I add JavaScript code on a webpage?

Could someone please tell me how to get this code working on a webpage? Particularly what should go in the header?

http://jsfiddle.net/mekwall/TJcP4/1/

Sorry if this is a basic question...steep learning curve!

Thanks

Your code is using the jQuery JavaScript library ... so your head will need to contain :

<script type="text/javascript" src="<jquery url>"></script>

Replace the <jquery url> with a valid url to the jQuery library. I suggest you use the Google CDN for the url or alternatively download a copy and store it on your server -> http://docs.jquery.com/Downloading_jQuery#Download_jQuery

Then to ensure your code runs once the DOM is ready wrap all of your JavaScript within the following :

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

Docs for ready() here

If your going to be using jQuery more I suggest you start reading here http://docs.jquery.com/How_jQuery_Works and if you going to learn JavaScript, you can't go wrong with reading this too -> https://developer.mozilla.org/en/JavaScript/Guide

Copy the code below, save it with a .html extension (eg test.html) and then double click to open.

<html>

<head>
<title>Page Title here</title>
</head>
<body>
<select id="t_dermal_name">
    <option value="t_default_dermal">-- Choose --</option>
     <option value="1" rel="30">Between Eyebrows</option>
     <option value="7" rel="30">Individual Line Softening</option>
     <option value="2" rel="30">Lip Contouring</option>
</select>
<select id="t_wrinkle_name">
    <option value="t_default_wrinkle">-- Choose --</option>
     <option value="1" rel="30">Between Eyebrows</option>
     <option value="7" rel="30">Individual Line Softening</option>
     <option value="2" rel="30">Lip Contouring</option>
</select>
<span id="output"></span>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script><!--You can use a local version of jquery-->
<script type="text/javascript">
$(document).ready(function(){
function onSelectChange(){
    var total = 0,
        dermal = $("#t_dermal_name").find('option:selected'),
        wrinkle = $("#t_wrinkle_name").find('option:selected');

    if(value = dermal.attr('rel')){
        total += parseInt(value);
    }

    if(value = wrinkle.attr('rel')){
        total += parseInt(value);
    }

   $("#output").html(total);


}

$("#t_dermal_name").change(onSelectChange);
$("#t_wrinkle_name").change(onSelectChange);
 });
</script>
</body>

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