Thứ Sáu, 9 tháng 1, 2015

JavaScript

JavaScript


---o0o---


Original link

1. Change HTML Content

a) Creat content


<p id="demo">Before.</p>
                

b) Add js to change content


<button type="button" onclick="document.getElementById('demo').innerHTML = 'After'"> Click Me!</button>
                

Before

  • getElementById(): accesses the first element with the specified id
  • innerHTML: This property sets or returns the HTML content of an element.

2. Change HTML Attributes

a) Creat object


<img id="myImage" onclick="changeImage()" src="http://www.w3schools.com/js/pic_bulboff.gif" width="50">
                

b) Add js to change src of image


<script>
    function changeImage() {
        var image = document.getElementById('myImage');
        if (image.src.match("bulbon")) {
            image.src = "http://www.w3schools.com/js/pic_bulboff.gif";
        } else {
            image.src = "http://www.w3schools.com/js/pic_bulbon.gif";
        }
    }
</script>
                
  • image.src: get src of image => return a string(http://www.w3schools.com/js/pic_bulboff.gif)
  • image.src.match: Search "bulbon" text in above string => return true or false

3. Change HTML Styles

a) Creat content


<p id="demo1">Content</p>
                

b) Add js to change style


<script>
    function myFunction1() {
        var x = document.getElementById("demo1");
        x.style.fontSize = "25px";
        x.style.color = "red";
    }
</script>
                

c) Call js by onclick


<p id="demo1" onclick="myFunction1()">Content</p>
                

Click on content to change style

Content

  • x.style: Set the style properties of an existing element

4. Validate Data

a) Creat input


<input id="numb" type="number">
            

b) Add js to validate

<script>
    function myFunction2() {
        var x, text;

        // Get the value of the input field with id="numb"
        x = document.getElementById("numb").value;

        // If x is Not a Number or less than one or greater than 10
        if (isNaN(x) || x < 1 || x > 10) {
            text = "Input not valid";
        } else {
            text = "Input OK";
        }
        document.getElementById("demo2").innerHTML = text;
    }
</script>
            

c) Call function


<button type="button" onclick="myFunction2()">Submit</button>
            

d) Print result


<p id="demo2"></p>
            

Please input a number between 1 and 10:

  • isNaN(): Check whether a number is an illegal number
  • .value: Return the value property
  • innerHTML: This property sets or returns the HTML content of an element.

Không có nhận xét nào:

Đăng nhận xét