Search This Blog

Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Thursday, January 4, 2024

HTML Forms Fields - Auto Save Later Using LocalStorage

Step 1: Create 3 file in the name of 

            index.html

            form.js

            form.css


Step 2: below are the code for 3 files

Step 3: once created, open index.html in browser. 

               Type some thing in field. CLICK SAVE. close the browser, open the browser again and type the index.html url. you can see the previous typed msg.



index.html

<!-- index.html -->

<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <link rel="stylesheet" href="form.css" />

    <title>Save Later</title>

  </head>

  <body>

    <div class="alert"></div>

    <form id="save-later-form">

      <h3>Simple Save Later Form</h3>

      <label for="full-name">Full Name</label>

      <input type="text" name="full-name" id="full-name" />

      <label for="email">Email</label>

      <input type="email" name="email" id="email" />

      <label for="phone">Phone Number</label>

      <input type="tel" name="phone" id="phone" maxlength="11" />

      <label for="dob">Date Of Birth</label>

      <input type="date" name="dob" id="dob" />

      <label for="security">Security Question</label>

      <select name="security" id="security" tabindex="0">

        <option value="">Select a question</option>

        <option value="best-friend">What's your best friend's name?</option>

        <option value="pet">What's the name of your first pet?</option>

        <option value="spouse">Where did you meet your spouse?</option>

      </select>

      <label for="security-answer">Answer</label>

      <input type="text" name="security-answer" id="security-answer" />

      <label for="description">Description</label>

      <textarea

        name="description"

        id="description"

        placeholder="Describe yourself in 100 words"

      ></textarea>

      <button type="submit" id="submit">SUBMIT</button>

      <button type="submit" id="save">SAVE</button>

    </form>

  </body>

  <script src="form.js"></script>

</html>



form.js

// form.js

const formId = "save-later-form"; // ID of the form

const url = location.href; //  href for the page

const formIdentifier = `${url} ${formId}`; // Identifier used to identify the form

const saveButton = document.querySelector("#save"); // select save button

const alertBox = document.querySelector(".alert"); // select alert display div

let form = document.querySelector(`#${formId}`); // select form

let formElements = form.elements; // get the elements in the form


/**

 * This function gets the values in the form

 * and returns them as an object with the

 * [formIdentifier] as the object key

 * @returns {Object}

 */

const getFormData = () => {

  let data = { [formIdentifier]: {} };

  for (const element of formElements) {

    if (element.name.length > 0) {

      data[formIdentifier][element.name] = element.value;

    }

  }

  return data;

};


saveButton.onclick = event => {

  event.preventDefault();

  data = getFormData();

  localStorage.setItem(formIdentifier, JSON.stringify(data[formIdentifier]));

  const message = "Form draft has been saved!";

  displayAlert(message);

};


/**

 * This function displays a message

 * on the page for 1 second

 *

 * @param {String} message

 */

const displayAlert = message => {

  alertBox.innerText = message;

  alertBox.style.display = "block";

  setTimeout(function() {

    alertBox.style.display = "none";

  }, 1000);

};


/**

 * This function populates the form

 * with data from localStorage

 *

 */

const populateForm = () => {

  if (localStorage.key(formIdentifier)) {

    const savedData = JSON.parse(localStorage.getItem(formIdentifier)); // get and parse the saved data from localStorage

    for (const element of formElements) {

      if (element.name in savedData) {

        element.value = savedData[element.name];

      }

    }

    const message = "Form has been refilled with saved data!";

    displayAlert(message);

  }

};


document.onload = populateForm(); // populate the form when the document is loadedd


form.css

/* form.css */

@import url("https://fonts.googleapis.com/css?family=Nunito");


*,

*:before,

*:after {

  box-sizing: border-box;

}


body {

  background-color: whitesmoke;

  font-family: "Nunito", sans-serif;

}


h3,

label {

  text-transform: uppercase;

}


.alert {

  width: 80vw;

  margin: 2rem auto;

  background-color: #d4edda;

  color: #155724;

  padding: 0.75rem 1.25rem;

  border-radius: 0.25rem;

  display: none;

}


#save-later-form {

  position: relative;

  width: 80vw;

  margin: 3rem auto;

  background-color: white;

  padding: 1rem 2rem;

  border-radius: 3px;

}


label {

  margin: 1rem 0 0;

  display: block;

}


input {

  font-size: 0.875em;

  width: 100%;

  height: 40px;

  padding: 0px 15px 0px 15px;

  background: whitesmoke;

  outline: none;

  color: #000;

  border: none;

  border-radius: 3px;

}


input:hover {

  background: whitesmoke;

  color: black;

}


button[type="submit"] {

  background-color: #349bab;

  width: calc((100% / 2) - 3px);

  display: inline-block;

  color: white;

  font-weight: 600;

  height: 2.8rem;

  border: none;

  font-family: Nunito;

  font-size: 1rem;

  cursor: pointer;

  outline: none;

}


#save {

  background-color: #30383f;

}


select {

  width: 100%;

  height: 40px;

  background: whitesmoke;

  border: none;

  padding: 0 0 0 0.5rem;

  outline: none;

}


select:focus,

input:focus,

textarea:focus {

  outline: #349bab solid 1px;

}


textarea {

  width: 100%;

  max-width: 100%;

  height: 110px;

  max-height: 110px;

  padding: 15px;

  margin: 0 0 1rem 0;

  background: whitesmoke;

  outline: none;

  color: black;

  font-size: 0.875em;

  border: none;

}

/* ========MEDIA QUERIES======== */

@media screen and (min-width: 768px) {

  #save-later-form,

  .alert {

    width: 60vw;

  }

}


@media screen and (min-width: 992px) {

  #save-later-form,

  .alert {

    width: 40vw;

  }

}



Sample Output






Tuesday, March 3, 2020

Simple 3rd party HTML Form autologin from your Application

1. simple copy the below script
2. change the login url in javascript
3. change the login authenticate url "when they click login submit" in the FORM action tag
4. change the text name value exactly same as their username,password field name
5. save and double click the HTML.


<html>

<head>

    <title>Crunchify Login Page</title>
    <script>
        function loginForm() {
            document.myform.submit();
            document.myform.action = "https://loginpage.url";
        }


    </script>
    <style type="text/css">
        body {
            background-image: url('https:///plus.medibuddy.in/bg.png');
        }
    </style>
</head>

<body onload="loginForm()">
    <form action="https://login-authenticate-url" name="myform" method="post">
        <input type="text" name="username" value="vijay@vijay.com">
        <input type="password" name="password" value="vijay">
        <input type="submit" value="Login">
    </form>

</body>

</html>

Wednesday, November 27, 2019

Flying Saucer HTML to PDF

Add this maven

<!-- https://mvnrepository.com/artifact/org.xhtmlrenderer/flying-saucer-pdf-itext5 -->

<dependency>

    <groupId>org.xhtmlrenderer</groupId>

    <artifactId>flying-saucer-pdf-itext5</artifactId>

    <version>9.1.19</version>

</dependency>


Code 

        String inputFile = "d:/xxx.html";
        String url = new File(inputFile).toURI().toURL().toString();
        String outputFile = "d:/xxx.pdf";
        OutputStream os = new FileOutputStream(outputFile);
       
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
        renderer.layout();
        renderer.createPDF(os);
       

        os.close();


Note
It will throw if any " QName production: QName::=(NCName':')?NCName. ' Exception in thread "main" org.xhtmlrenderer.util.XRRuntimeException: "  Then your html tag has problem. correct that html tag and re run it.

for ex: <Table width: 50%"> 
     to
      <table width="50%">

Thursday, November 7, 2019

NSE options Data Pulling with beta.nseindia.com

Beta version they are giving it as JSON which is very easy for us.

See the sample url. 

1. JSON output,
2. Directly use the JSON for your business logic.
3. Before install requests, simplejson plugin
     pip install simplejson
     pip install requests

Same for older version - sample code and output

http://drvijayy2k2.blogspot.com/2019/08/python-code-to-pull-nse-option.html

Code

import requests
import simplejson as json

result = requests.get ( "https://beta.nseindia.com/api/quote-derivative?symbol=NIFTY&identifier=OPTIDXNIFTY07-11-2019" );
resultJson = json.loads( result.content )
#print ( resultJson["info"] );
strikePricesDetailsJson = resultJson["stocks"]
for strikePrice in strikePricesDetailsJson:
    spDetails = strikePrice["metadata"];
    #print ( spDetails );
    print ( spDetails["optionType"] , " : ", spDetails["strikePrice"] , " : ", spDetails["lastPrice"]);



Output

Call  :  12350  :  0
Put  :  11050  :  0

Call  :  12750  :  0


{'metadata': {'instrumentType': 'Index Options', 'expiryDate': '28-Dec-2023', 'optionType': 'Put', 'strikePrice': 12700, 'identifier': 'OPTIDXNIFTY28-12-2023PE12700.00', 'openPrice': 0, 'highPrice': 0, 'lowPrice': 0, 'closePrice': 0, 'prevClose': 1005, 'lastPrice': 0, 'change': -1005, 'pChange': -100, 'numberOfContractsTraded': 0, 'totalTurnover': 0}, 'underlyingValue': 11998.1, 'volumeFreezeQuantity': 5001, 'marketDeptOrderBook': {'totalBuyQuantity': 225, 'totalSellQuantity': 0, 'bid': [{'price': 645.05, 'quantity': 75}, {'price': 645, 'quantity': 75}, {'price': 597, 'quantity': 75}, {'price': 0, 'quantity': 0}, {'price': 0, 'quantity': 0}], 'ask': [{'price': 0, 'quantity': 0}, {'price': 645, 'quantity': 0}, {'price': 0, 'quantity': 0}, {'price': 0, 'quantity': 0}, {'price': 0, 'quantity': 0}], 'carryOfCost': {'price': {'bestBuy': 645.05, 'bestSell': 0, 'lastPrice': 0}, 'carry': {'bestBuy': -70.5660812600072, 'bestSell': 0, 'lastPrice': 0}}, 'tradeInfo': {'tradedVolume': 0, 'value': 0, 'vmap': 0, 'premiumTurnover': 0, 'openInterest': 6, 'changeinOpenInterest': 0, 'pchangeinOpenInterest': 0, 'marketLot': 75}, 'otherInfo': {'settlementPrice': 0, 'dailyvolatility': 0.91, 'annualisedVolatility': 17.45, 'impliedVolatility': 0, 'clientWisePositionLimits': 19597661, 'marketWidePositionLimits': 0}}}



Friday, August 30, 2019

Python Code to pull NSE Option Derivative HTML to JSON on Every N minutes

1. Install Python, PIP
2. type the below command from your python sample folder [ by pip or pip3 cmd ].
     pip install beautifulsoup
     OR
     pip install BeautifulSoup4
     pip install requests
     pip install schedule
     python nse_options.py

-- ENJOY

nse_options.py

# author - dr. vijay
# email - drvijayy2k2@gmail.com
# date - 30-08-2019 7:30 PM

# install plugin
# pip install BeautifulSoup

import sys
import json
import requests
# Schedule Library imported
import schedule
import time
import datetime

from bs4 import BeautifulSoup

base_url = 'https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbol=';


def doScheduler ():
    print ( "Schedule starts @ ", datetime.datetime.now() );
    result = parseNseOptions ( 'NIFTY' );
    # result = parseNseOptions ( 'INFY' );
    f = open( 'D:/nseOptionst.txt', 'a' )
    f.write( str(result) + "\n" );
    print ( "Done !" );
 

def parseNseOptions ( scrip='NIFTY' ):
    url = base_url + scrip;
    response = response = requests.get( url ) 
    if( response != None and response.ok ):
        optionScripListHtml = response.content
        # print ( optionScripListHtml );
        soup = BeautifulSoup( optionScripListHtml, "html.parser" )
        tableHtml = soup.find( "table", id="octable" )
        f1 = tableHtml.findAll( "thead" )[0].findAll( 'tr' )
     
        callDataColumnEndsAt = 11
        optionStrikePriceColumnAt = ( 12 - 1 )
        putDataColumnEndsAt = 23
        headers = {}
        headersOnIndex = {}
        h1 = f1[1].findAll( "th" )
        for index, h in enumerate( h1, start=0 ):
            if ( index < callDataColumnEndsAt ):
                headers["call-" + h.text] = h.get( "title", "" )
                headersOnIndex[index] = "call-" + h.text 
            elif ( index == optionStrikePriceColumnAt ):
                 headers[h.text] = h.get( "title", "" )
                 headersOnIndex[index] = h.text 
            elif ( index < putDataColumnEndsAt ):
                headers["put-" + h.text] = h.get( "title", "" )
                headersOnIndex[index] = "put-" + h.text 
        # print(headersOnIndex)
     
        fnoDataRows = tableHtml.findAll( "tr" )
        tempMap = {}
        totalOptionPCOI = {}
        tempMapWithStrikePriceAsKey = {}
        startingRow = 3
        endingRow = len( fnoDataRows )
        callOIChangeCol = 2
        callTotalChangeInOIValue = 0
        putOIChangeCol = 20
        putTotalChangeInOIValue = 0
        index = 1
        colIndex = 1
        recordFound = False
     
        for rowIndex, x in enumerate( fnoDataRows, start=0 ):
            if ( rowIndex == endingRow - 1 ):
                xx = x.findAll( "td" )
                totalOptionPCOI = {"callTotalOI": xx[1].text, "callTotalChangeInOI": xx[2].text, "callTotalVolume": xx[3].text, "putTotalVolume": xx[5].text, "putTotalChangeInOI": xx[6].text, "putTotalOI": xx[7].text }
                # break the entire loop as we got all the information
                break;
            for colIndex, c in enumerate( x.findAll( "td" ), start=0 ):
                value = c.text.strip()
                if value == "" or value == "-":
                    value = "0"
                else:
                    value = value.replace( ",", "" )
             
                if ( colIndex == callOIChangeCol ):
                    callTotalChangeInOIValue = callTotalChangeInOIValue + int( value )
                if ( colIndex == putOIChangeCol ):
                    putTotalChangeInOIValue = putTotalChangeInOIValue + int( value )
                     
                tempMap[ headersOnIndex[colIndex]] = value
                recordFound = True
             
            if recordFound == True:
                tempMapWithStrikePriceAsKey[tempMap[headersOnIndex[optionStrikePriceColumnAt]]] = tempMap.copy()
                strikePrice = tempMap["Strike Price"]
                tempMap.clear()   

            recordFound = False
     
        return dict( { "resultFetchTime": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "totalOptionPCOI":totalOptionPCOI, "mapWithStrikePriceAsKey":tempMapWithStrikePriceAsKey} )


if __name__ == "__main__":
 
    schedule.every( 3 ).minutes.do( doScheduler )
    while True:
        schedule.run_pending()
        time.sleep( 1 )


OUTPUT

{
'mapWithStrikePriceAsKey': {
//..... other strike prices
'10850.00': {
'call-Chart': '0',
'call-OI': '49950',
'call-Chng in OI': '26475',
'call-Volume': '10689',
'call-IV': '14.71',
'call-LTP': '210.75',
'call-Net Chng': '29.00',
'call-BidQty': '300',
'call-BidPrice': '208.85',
'call-AskPrice': '215.95',
'call-AskQty': '75',
'Strike Price': '10850.00',
'put-BidQty': '300',
'put-BidPrice': '19.50',
'put-AskPrice': '20.45',
'put-AskQty': '600',
'put-Net Chng': '-25.55',
'put-LTP': '20.45',
'put-IV': '14.92',
'put-Volume': '134223',
'put-Chng in OI': '261600',
'put-OI': '399750',
'put-Chart': '0'
},
'10900.00': {
'call-Chart': '0',
'call-OI': '574650',
'call-Chng in OI': '198600',
'call-Volume': '157457',
'call-IV': '14.15',
'call-LTP': '169.05',
'call-Net Chng': '26.85',
'call-BidQty': '4350',
'call-BidPrice': '169.05',
'call-AskPrice': '170.85',
'call-AskQty': '75',
'Strike Price': '10900.00',
'put-BidQty': '150',
'put-BidPrice': '27.45',
'put-AskPrice': '28.20',
'put-AskQty': '525',
'put-Net Chng': '-33.60',
'put-LTP': '28.20',
'put-IV': '14.22',
'put-Volume': '396350',
'put-Chng in OI': '894450',
'put-OI': '1796100',
'put-Chart': '0'
}
  //..... other strike prices
},
'totalOptionPCOI': {
'callTotalOI': ' 12,057,225',
'callTotalChangeInOI': '',
'callTotalVolume': ' 2,231,841',
'putTotalVolume': ' 1,883,484',
'putTotalChangeInOI': '',
'putTotalOI': ' 12,479,775'
}

}

Tuesday, September 11, 2018

JSoup - HTML Parser for image audio video attributes

SAMPLE

package com.jsoup;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;

public class HtmlParser
{
public static String html = "<html><head><title>Sample Title</title></head>"
         + "<body>"
         + "<p>Sample Content1</p>"              
         + "<img name='pic1' id='picid1' src='test.jpg' />"  
         + "<p>Sample Content2</p>"
         + "<p>Sample Content3</p>"
         + "<img name='pic2' id='picid2' src='test2.jpg' />"
         + "<video width='320' height='240' controls>"
        + "<source id='1' src='movie.mp4' type='video/mp4'>"
        + " <source  id='2' src='movie.ogg' type='video/ogg'>"
        + "<Br/>Your browser does not support the video tag."
        + "</video>"
        + "<audio controls>"
        + "<source id='1' src='horse.ogg' type='audio/ogg'>"
        + "<source id='2' src='horse.mp3' type='audio/mpeg'>"
        + "<Br/>Your browser does not support the audio tag."
        + "</audio>"
        + "<p><a href='http://example.com/'" + " onclick='checkData()'>Link</a></p>"
         +"</body></html>";


/*output
Initial HTML: <p><a href='http://example.com/' onclick='checkData()'>Link</a></p>
Cleaned HTML: <p><a href="http://example.com/" rel="nofollow">Link</a></p>*/
public static void safeGuardHtmlSanitize ()
{
System.out.println ( "Initial HTML: " + html );
String safeHtml = Jsoup.clean ( html, Whitelist.basic () );
System.out.println ( "Cleaned HTML: " + safeHtml );
}

public static void main ( String [] args )
{

Document document = Jsoup.parse ( html );
// img with src ending .png
Elements imgs = document.select ( "img" );
for ( Element img : imgs )
{
System.out.println ( "Name: " + img.attr ( "name" ) + " id: " + img.id () + " src: " + img.attr ( "src" ) );
//to replace the value existing
img.attr ( "src", "replacedImage.jpg" ) ;
}
System.out.println ( "\n\n" );

Elements videos = document.select ( "video" );
Elements videoSrc = videos.select ( "source" );
for ( Element vSrc : videoSrc )
{
System.out.println ( " id: " + vSrc.id () + " src: " + vSrc.attr ( "src" ) + " type: " + vSrc.attr ( "type" ));
}
System.out.println ( "\n\n" );

Elements audios = document.select ( "audio" );
Elements audioSrc = audios.select ( "source" );
for ( Element aSrc : audioSrc )
{
System.out.println ( " id: " + aSrc.id () + " src: " + aSrc.attr ( "src" ) + " type: " + aSrc.attr ( "type" ));
}
System.out.println ( "\n\n" );

safeGuardHtmlSanitize();
}
}



OUTPUT

Name: pic1 id: picid1 src: test.jpg
Name: pic2 id: picid2 src: test2.jpg



 id: 1 src: movie.mp4 type: video/mp4
 id: 2 src: movie.ogg type: video/ogg



 id: 1 src: horse.ogg type: audio/ogg
 id: 2 src: horse.mp3 type: audio/mpeg



Initial HTML: Sample TitleSample Content1
Sample Content2
Sample Content3
Link
Cleaned HTML: Sample Title
Sample Content1
Sample Content2
Sample Content3


Your browser does not support the video tag.

Your browser does not support the audio tag.
Link



Hit Counter


View My Stats