Summary of javascript common methods

  • 2020-06-12 08:32:55
  • OfStack

1. JavaScript: Write HTML output


document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph</p>");

2. JavaScript: Responding to events


<button type="button" onclick="alert('Welcome!')"> Click here to </button>

3. JavaScript: Change the HTML content


x=document.getElementById("demo") // Look for the element
x.innerHTML="Hello JavaScript"; // Change the content

4. JavaScript: Change the HTML image


element=document.getElementById('myimage')
element.src="../i/eg_bulboff.gif";

5. Change the HTML style


x=document.getElementById("demo") // Find the element
x.style.color="#ff0000"; // Change the style

JavaScript is case sensitive.

JavaScript is case sensitive.
When writing the JavaScript statement, be aware that the case switch key is turned off.
The function getElementById is different from getElementbyID.
Similarly, the variable myVariable is different from MyVariable.

Tip: A good programming habit is to declare the required variables at the beginning of the code.

8, Value = undefined

In computer programs, variables with no value are often declared. A variable that is not declared with a value is actually undefined. The value of the variable carname will be undefined after the following statement is executed:
var carname;

9. Create the JavaScript object
This example creates an object named "person" and adds four properties to it:


person=new Object();
person.firstname="Bill";
person.lastname="Gates";
person.age=56;
person.eyecolor="blue";

10. JavaScript form validation

Required (or optional) items
The following function checks to see if the user has filled out a required (or optional) item in the form. If the required or required options are empty, the warning box pops up and the function returns false; otherwise, the function returns true (meaning the data is ok) :


<html>
<head>
<script type="text/javascript">

function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false}
else {return true}
}
}

function validate_form(thisform)
{
with (thisform)
{
if (validate_required(email,"Email must be filled out!")==false)
{email.focus();return false}
}
}
</script>
</head>

<body>
<form action="submitpage.htm" onsubmit="return validate_form(this)" method="post">
Email: <input type="text" name="email" size="30">
<input type="submit" value="Submit"> 
</form>
</body>

</html>

This is the end of this article, I hope you enjoy it


Related articles: