Coding Problems with solution – Web Computing

Coding Problems with solution – Web Computing

Javascript

JavaScript Code for Email Validation check for @ in input

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Email Validation</title>
</head>
<body>

  <label for="email">Enter your email:</label>
  <input type="text" id="email" placeholder="example@example.com">
  <button onclick="validateEmail()">Check Email</button>

  <p id="result"></p>

  <script>
    function validateEmail() {
      // Get the value from the input field
      var email = document.getElementById("email").value;

      // Check if the email contains the "@" symbol
      if (email.includes("@")) {
        document.getElementById("result").innerHTML = "Email is valid!";
      } else {
        document.getElementById("result").innerHTML = "Email is invalid. Please include '@' in the email.";
      }
    }
  </script>

</body>
</html>

JavaScript Code for Displaying a Digital Clock on a Web Page

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Digital Clock</title>

</head>
<body>

  <div id="clock"></div>

  <script>
    function updateClock() {
      var now = new Date();
      var timeString = now.toLocaleTimeString();

      document.getElementById("clock").innerHTML = timeString;
    }

    setInterval(updateClock, 1000);
    updateClock();
  </script>

</body>
</html>

Javascript code for  background color of the web page automatically after every 5 seconds.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Background Color Change</title>
  <script>
    function changeBackgroundColor() {
      const colors = ['red', 'blue', 'green'];
      const randomColor = colors[Math.floor(Math.random() * colors.length)];
      document.body.style.backgroundColor = randomColor;
    }

    setInterval(changeBackgroundColor, 5000);
  </script>
</head>
<body>
  <h1>Automatic Background Color Change</h1>
</body>
</html>

 To display three radio buttons on the web page, namely, “Red”, “Blue” and “Green”. Selecting any button changes the background color as per the name of the button.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Change Background Color</title>
</head>
<body>

<form>
  <label>
    <input type="radio" name="color" value="red" onclick="changeBackgroundColor(this.value)">
    Red
  </label>
  <label>
    <input type="radio" name="color" value="blue" onclick="changeBackgroundColor(this.value)">
    Blue
  </label>
  <label>
    <input type="radio" name="color" value="green" onclick="changeBackgroundColor(this.value)">
    Green
  </label>
</form>

<script>
  function changeBackgroundColor(color) {
    document.body.style.backgroundColor = color;
  }
</script>

</body>
</html>

JavaScript Code for Setting a Cookie on the User’s Computer

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Set Cookie</title>
</head>
<body>

  <script>
    // Function to set a cookie
    function setCookie(cookieName, cookieValue, expirationDays) {
      var d = new Date();
      d.setTime(d.getTime() + (expirationDays * 24 * 60 * 60 * 1000));
      var expires = "expires=" + d.toUTCString();
      document.cookie = cookieName + "=" + cookieValue + "; " + expires + "; path=/";
    }

    // Example: set a cookie named "username" with the value "JohnDoe" that expires in 7 days
    setCookie("username", "JohnDoe", 7);
  </script>

</body>
</html>

JavaScript Code for Accepting Two Numbers and Displaying Their Sum

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sum Calculator</title>
</head>
<body>

  <label for="num1">Enter the first number:</label>
  <input type="number" id="num1" placeholder="Enter a number">
  <br>

  <label for="num2">Enter the second number:</label>
  <input type="number" id="num2" placeholder="Enter another number">
  <br>

  <button onclick="calculateSum()">Calculate Sum</button>

  <p id="result"></p>

  <script>
    function calculateSum() {
      // Get values from input fields
      var num1 = parseFloat(document.getElementById("num1").value);
      var num2 = parseFloat(document.getElementById("num2").value);

      // Check if the input is valid
      if (isNaN(num1) || isNaN(num2)) {
        document.getElementById("result").innerHTML = "Please enter valid numbers.";
      } else {
        // Calculate the sum
        var sum = num1 + num2;

        // Display the result
        document.getElementById("result").innerHTML = "The sum is: " + sum;
      }
    }
  </script>

</body>
</html>

React

React Code for “Greet the User” Button and Alert Box

import React from 'react';

class GreetButton extends React.Component {
  greetUser = () => {
    // Display an alert with a greeting
    alert('Hello, User! Welcome!');
  };

  render() {
    return (
      <div>
        <button onClick={this.greetUser}>Greet the User</button>
      </div>
    );
  }
}

export default GreetButton;
import React from 'react';
import GreetButton from './GreetButton';

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>Welcome to My App</h1>
        <GreetButton />
      </div>
    );
  }
}

export default App;

Nodejs

Creating a Simple Server to Display a “Welcome” Message

// Importing the http module
const http = require('http');

// Creating a simple server
const server = http.createServer((req, res) => {
  // Setting the response header
  res.writeHead(200, { 'Content-Type': 'text/plain' });

  // Sending the response (in this case, a "Welcome" message)
  res.end('Welcome to the Node.js Server!\n');
});

// Listening on port 3000
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Code for Creating a Simple Text File with User-Provided Data

const fs = require('fs');
const readline = require('readline');

// Create a readline interface for reading user input
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Ask the user for input
rl.question('Enter data to be written to the file: ', (userData) => {
  // Close the readline interface
  rl.close();

  // Specify the file name (you can customize this)
  const fileName = 'output.txt';

  // Write the user-provided data to the file
  fs.writeFile(fileName, userData, (err) => {
    if (err) {
      console.error('Error writing to the file:', err);
    } else {
      console.log(`Data written to ${fileName} successfully.`);
    }
  });
});

Advanced React

Write the code making use of Hooks useState function that displays the number of times button named “CLICK” is clicked

import React, { useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <button onClick={handleClick}>CLICK</button>
      <p>You have clicked the button {count} times.</p>
    </div>
  );
}

export default App;

Team
Team

This account on Doubtly.in is managed by the core team of Doubtly.

Articles: 483

jsDelivr CDN plugin by Nextgenthemes

These are the assets loaded from jsDelivr CDN. Do not worry about old WP versions in the URLs, this is simply because the files were not modified. A sha384 hash check is used so you can be 100% sure the files loaded from jsDelivr are the exact same files that would be served from your server.


	

Level up your video embeds with ARVE or ARVE Pro