Snippets Collections
const [values, setValues] = useState({
  firstName: '',
  lastName: '',
  email: ''
})

function handleChange(){
  setValues((prevState) => 
	const {name, value} = e.target;
		
      return  {
        ...prevState,
       [name]: value;
		id: Date.now().toString(36) + Math.random()
			.toString(36).substring(2, 12).padStart(12, 0)
      		}
            
	)
}
try {history.replaceState({content: document.title}, document.title, document.location.href);} catch(e) {}
/** Vanilla javascript **/

    // Get the value of the checked radio button, undefined on not checked or not found
   let radioButtonValue = (document.querySelector("input[name='radioName']:checked") || {}).value || undefined

    // Check radio button with value ...
    (document.querySelector("input[name='radioName'][value='A']") || {}).checked=true;

/** jQuery **/

    // Get the value of the checked radio button, undefined on not checked or not found
   let radioButtonValue = $("input[name='radioName']:checked").val();

    // Check radio button with value ...
   $("input[name='radioName'][value='A']").prop('checked',true);
<style> 
  INPUT:checked + label {color: #00F;} 
</style>

<input id="theId" type="checkbox"><label for="theId"> The cat is here</label> 
<fieldset style="width:fit-content"><legend>Where is the Cat?</legend>
	<input id="cat_garden" name="cat_where" type="radio"><label for="cat_garden"> Garden</label> 
	<input id="cat_bed" name="cat_where" type="radio"><label for="cat_bed"> Bed</label> 
	<input id="cat_cushion" name="cat_where" type="radio"><label for="cat_cushion"> Cushion</label> 
</fieldset>
<iframe class="airtable-embed" src="https://airtable.com/embed/appx4s1nE9Kolw7qf/pagbWILEYl1BUqofc/form" frameborder="0" onmousewheel="" width="100%" height="533" style="background: transparent; border: 1px solid #ccc;"></iframe>
import { zodResolver } from "@hookform/resolvers/zod";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";

const signUpSchema = z
  .object({
    email: z
      .string()
      .nonempty("email is required")
      .email("Invalid email address"),
    password: z.string().min(8, "Password must be at least 8 characters"),
    confirmPassword: z.string(),
  })
  // we can use zod to validate using refine method
  .refine((data) => data.password === data.confirmPassword, {
    message: "Passwords do not match",
    path: ["confirmPassword"], // it will show error in confirmPassword field
  });

type ISignUpSchema = z.infer<typeof signUpSchema>; // create type from schema

const ReactHookFormWithZod = () => {
  const [show, setShow] = useState(false);
  const [show1, setShow1] = useState(false);
  const { register, handleSubmit, formState, reset } = useForm<ISignUpSchema>({
    resolver: zodResolver(signUpSchema), //tell which schema to resolve
  });
  const { errors, isSubmitting } = formState;

  const onSubmit = async (data: ISignUpSchema) => {
    console.log(data);
    //-------send data to server----------//
    await new Promise((resolve) => setTimeout(resolve, 1000));
    //------
    reset(); // clear form
  };
  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      className="flex flex-col gap-y-4 [&>div>input]:w-full"
    >
      <label className="-mb-3 text-sm text-gray-500" htmlFor="email">
        email
      </label>
      <div className="">
        <input
          {...register("email")}
          type="text"
          placeholder="email"
          className="rounded border px-4 py-2"
        />
        {
          // granular show errors
          errors.email && (
            <p className="text-sm text-red-500">{`${errors.email.message}`}</p>
          )
        }
      </div>
      <label className="-mb-3 text-sm text-gray-500" htmlFor="password">
        password
      </label>
      <div className="relative ">
        <input
          {...register("password")}
          type={show ? "text" : "password"}
          id="password"
          placeholder="password"
          className=" block rounded border py-2 pl-2 pr-12"
        ></input>
        <p
          className="absolute  right-2 top-0 block cursor-pointer select-none py-2 "
          onClick={() => setShow((show) => !show)}
        >
          ๐Ÿ‘๏ธ
        </p>
        {
          // granular show errors
          errors.password && (
            <p className="text-sm text-red-500">{`${errors.password.message}`}</p>
          )
        }
      </div>
      <label className="-mb-3 text-sm text-gray-500" htmlFor="confirmPassword ">
        confirm password
      </label>
      <div className="relative">
        <input
          {...register("confirmPassword")}
          id="confirmPassword"
          type={show1 ? "text" : "password"}
          placeholder="confirm password"
          className="rounded border py-2 pl-2 pr-10 "
        />
        <p
          className="absolute  right-2 top-0 block cursor-pointer select-none py-2 "
          onClick={() => setShow1((show) => !show)}
        >
          ๐Ÿ‘๏ธ
        </p>
        {
          // granular show errors
          errors.confirmPassword && (
            <p className="text-sm text-red-500">{`${errors.confirmPassword.message}`}</p>
          )
        }
      </div>

      <button
        type="submit"
        className="rounded bg-blue-500 py-2 text-white disabled:cursor-no-drop disabled:bg-gray-500"
        disabled={isSubmitting}
      >
        {isSubmitting ? "loading..." : "Submit"}
      </button>
    </form>
  );
};

export default ReactHookFormWithZod;
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import type { FieldValues } from "react-hook-form";

const ReactHookForm = () => {
  const [show, setShow] = useState(false);
  const [show1, setShow1] = useState(false);
  const { register, handleSubmit, formState, reset, getValues } = useForm();
  const { errors, isSubmitting } = formState;

  const onSubmit = async (data: FieldValues) => {
    // (data:FieldValues) type is -> {[x:string] : any} //we would need zod for more typesafety
    console.log(data);
    //-------send data to server----------//
    await new Promise((resolve) => setTimeout(resolve, 1000));
    //------
    reset(); // clear form
  };
  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      className="flex flex-col gap-y-4 [&>div>input]:w-full"
    >
      <label className="-mb-3 text-sm text-gray-500" htmlFor="email">
        email
      </label>
      <div className="border">
        <input
          {...register("email", {
            required: "Email is required",
            pattern: {
              value: /\S+@\S+\.\S+/,
              message: "invaid email format",
            },
          })}
          type="email"
          placeholder="email"
          className="rounded px-4 py-2"
        />
        {
          // granular show errors
          errors.email && (
            <p className="text-sm text-red-500">{`${errors.email.message}`}</p>
          )
        }
      </div>
      <label className="-mb-3 text-sm text-gray-500" htmlFor="password">
        password
      </label>
      <div className="relative border ">
        <input
          {...register("password", {
            required: "Password is required",
            minLength: {
              value: 8,
              message: "Password must be at least 8 characters",
            },
          })}
          type={show ? "text" : "password"}
          id="password"
          placeholder="password"
          className="  block rounded py-2 pl-2 pr-12"
        ></input>
        <p
          className="absolute  right-2 top-0 block cursor-pointer select-none py-2 "
          onClick={() => setShow((show) => !show)}
        >
          ๐Ÿ‘๏ธ
        </p>
        {
          // granular show errors
          errors.password && (
            <p className="text-sm text-red-500">{`${errors.password.message}`}</p>
          )
        }
      </div>
      <label className="-mb-3 text-sm text-gray-500" htmlFor="confirmPassword ">
        confirm password
      </label>
      <div className="relative border">
        <input
          {...register("confirmPassword", {
            required: "Confirm Password is required",
            validate: (value) => {
              return (
                // getValues from "password" input
                value === getValues("password") || "Passwords do not match"
              );
            },
          })}
          id="confirmPassword"
          type={show1 ? "text" : "password"}
          placeholder="confirm password"
          className="rounded py-2 pl-2 pr-10 "
        />
        <p
          className="absolute  right-2 top-0 block cursor-pointer select-none py-2 "
          onClick={() => setShow1((show) => !show)}
        >
          ๐Ÿ‘๏ธ
        </p>
        {
          // granular show errors
          errors.confirmPassword && (
            <p className="text-sm text-red-500">{`${errors.confirmPassword.message}`}</p>
          )
        }
      </div>

      <button
        type="submit"
        className="rounded bg-blue-500 py-2 text-white disabled:cursor-no-drop disabled:bg-gray-500"
        disabled={isSubmitting}
      >
        {isSubmitting ? "loading..." : "Submit"}
      </button>
    </form>
  );
};

export default ReactHookForm;
import { useState } from "react";

const initialFormData = {
  email: "",
  password: "",
  confirmPassword: "",
};
const FormWithoutReactHookForm = () => {
  const [show, setShow] = useState(false);
  const [show1, setShow1] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState<string[]>([""]); // errors are array of strings
  const [formData, setFormData] = useState(initialFormData);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setErrors([]); // clear errors
    //-------validate data ----------//
    if (formData.password !== formData.confirmPassword) {
      setErrors((prev) => [...prev, "passwords do not match"]);
      return;
    }

    console.log(formData);
    setIsSubmitting(true); // show loading or disable submit button
    //-------send data to Server ----------//
    await new Promise((resolve) => setTimeout(resolve, 1000));
    //....
    setFormData(initialFormData); // clear form
    setIsSubmitting(false);
  };
  return (
    <form
      className="flex flex-col gap-y-4 [&>div>input]:w-full"
      onSubmit={handleSubmit}
    >
      <label className="-mb-3 text-sm text-gray-500" htmlFor="email">
        email
      </label>
      <div className="border">
        <input
          type="email"
          id="email"
          required={true}
          placeholder="email"
          className="rounded px-4 py-2"
          value={formData.email}
          onChange={(e) =>
            setFormData((prev) => ({ ...prev, email: e.target.value }))
          }
        />
      </div>
      <label className="-mb-3 text-sm text-gray-500" htmlFor="password">
        password
      </label>
      <div className="relative border ">
        <input
          type={show ? "text" : "password"}
          id="password"
          placeholder="password"
          className="  block rounded py-2 pl-2 pr-12"
          required={true}
          minLength={8}
          value={formData.password}
          onChange={(e) =>
            setFormData((prev) => ({ ...prev, password: e.target.value }))
          }
        ></input>
        <p
          className="absolute  right-2 top-0 block cursor-pointer select-none py-2 "
          onClick={() => setShow((show) => !show)}
        >
          ๐Ÿ‘๏ธ
        </p>
      </div>
      <label className="-mb-3 text-sm text-gray-500" htmlFor="confirmPassword ">
        confirm password
      </label>
      <div className="relative border">
        <input
          id="confirmPassword"
          required={true}
          type={show1 ? "text" : "password"}
          placeholder="confirm password"
          className="rounded py-2 pl-2 pr-10 "
          value={formData.confirmPassword}
          onChange={(e) =>
            setFormData((prev) => ({
              ...prev,
              confirmPassword: e.target.value,
            }))
          }
        />
        <p
          className="absolute  right-2 top-0 block cursor-pointer select-none py-2 "
          onClick={() => setShow1((show) => !show)}
        >
          ๐Ÿ‘๏ธ
        </p>
      </div>
      {
        // show errors
        errors.length > 0 && (
          <div className=" text-center text-red-500">
            {errors.map((error, i) => (
              <p key={i} className="text-sm">
                {error}
              </p>
            ))}
          </div>
        )
      }
      <button
        type="submit"
        className="rounded bg-blue-500 py-2 text-white disabled:cursor-no-drop disabled:bg-gray-500"
        disabled={isSubmitting}
      >
        {isSubmitting ? "loading..." : "Submit"}
      </button>
    </form>
  );
};

export default FormWithoutReactHookForm;
    <input type="file" name="doc_file" accept=".doc,.docx">
    <input type="file" name="image_file" accept="image/*">
/**
 * Plugin Name:       My Basics Plugin
 * Plugin URI:        https://example.com/plugins/the-basics/
 * Description:       Handle the basics with this plugin.
 * Version:           1.10.3
 * Requires at least: 5.2
 * Requires PHP:      7.2
 * Author:            John Smith
 * Author URI:        https://author.example.com/
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Update URI:        https://example.com/my-plugin/
 * Text Domain:       my-basics-plugin
 * Domain Path:       /languages
 */
function myFunction() {

  const formTitle = "sample"; // This is a form title.

  const sheetName = "Sheet1"; // This is a sheet name.



  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);

  const [, ...values] = sheet

    .getDataRange()

    .getDisplayValues()

    .filter((r) => r.join("") != "");

  const obj = values.map(([a, b, c]) => {

    const answers = b

      .split("\n")

      .map((e) => e.trim())

      .filter(String);

    const correct = c

      .split("\n")

      .map((e) => e.trim())

      .filter(String);

    return {

      question: a,

      answers,

      correct,

      point: 1,

      type: correct.length == 1 ? "addMultipleChoiceItem" : "addCheckboxItem",

    };

  });

  const form = FormApp.create(formTitle)

    .setIsQuiz(true)

    .setTitle("Sample questions");

  obj.forEach(({ question, answers, correct, point, type }) => {

    const choice = form[type]();

    const choices = answers.map((e) =>

      choice.createChoice(e, correct.includes(e) ? true : false)

    );

    choice.setTitle(question).setPoints(point).setChoices(choices);

  });

}
<script>
  var Webflow = Webflow || [];
Webflow.push(function() {  
  // unbind webflow form handling (keep this if you only want to affect specific forms)
  $(document).off('submit');

  /* Any form on the page */
  $('form').submit(function(e) {
    e.preventDefault();

  	const $form = $(this); // The submitted form
    
    if ($form.valid()) {
      const $submit = $('[type=submit]', $form); // Submit button of form
    const buttonText = $submit.val(); // Original button text
    const buttonWaitingText = $submit.attr('data-wait'); // Waiting button text value
    const formMethod = $form.attr('method'); // Form method (where it submits to)
    const formAction = $form.attr('action'); // Form action (GET/POST)
    const formRedirect = $form.attr('data-redirect'); // Form redirect location
    const formData = $form.serialize(); // Form data
    
    // Set waiting text
    if (buttonWaitingText) {
      $submit.val(buttonWaitingText); 
    }
    
    $.ajax(formAction, {
    	data: formData,
      method: formMethod
    })
    .done((res) => {
      // If form redirect setting set, then use this and prevent any other actions
      if (formRedirect) { window.location = formRedirect; return; }

    	$form
      	.hide() // optional hiding of form
    		.siblings('.w-form-done').show() // Show success
      	.siblings('.w-form-fail').hide(); // Hide failure
    })
    .fail((res) => {
      $form
      	.siblings('.w-form-done').hide() // Hide success
    	  .siblings('.w-form-fail').show(); // show failure
    })
    .always(() => {
      // Reset text
      $submit.val(buttonText);
    });
    }
  });
});
</script>
<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />

<?php

if ( isset( $_POST['animal'] ) ) {
    foreach ( $_POST['animal'] as $animal ) {
        echo $animal;
    }
}

?>
/*CSS*/
.field-item__wrapper {
    position: relative;
    padding-top: 15px;
}
.form__field {
    font-family: inherit;
    width: 100%;
    border: 0;
    border-bottom: 2px solid #000;
    outline: 0;
    color: #000;
    padding: 7px 0;
    background: 0 0;
    transition: border-color 0.2s;
}
.form__field::placeholder {
    color: transparent;
    opacity: 0;
}
.form__field:placeholder-shown ~ .form__label {
    cursor: text;
    top: 20px !important;
}
.form__label {
    position: absolute;
    top: 0;
    display: block;
    transition: 0.2s;
    color: #000;
}
.form__field:focus {
    padding-bottom: 6px;
    border-width: 3px;
    border-image-slice: 1;
    border-color: #000 !important;
}
.form__field:focus ~ .form__label {
    position: absolute;
    top: 0 !important;
    font-size: 0.8em;
    display: block;
    transition: 0.2s;
}
.form__field:invalid,
.form__field:required {
    box-shadow: none;
}
.w-input.error {
    border-color: #cc3131;
}
label.error {
    font-size: 10px;
    line-height: 24px;
    color: #cc3131;
    position: absolute;
    bottom: -25px;
}
/*CSS*/
else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            $_SESSION['errors'][] = "Invalid email format!";   
        }
button:focus { /* Some exciting button focus styles */ }
button:focus:not(:focus-visible) {
  /* Undo all the above focused button styles
     if the button has focus but the browser wouldn't normally
     show default focus styles */
}
button:focus-visible { /* Some even *more* exciting button focus styles */ }
star

Thu Apr 04 2024 01:37:52 GMT+0000 (Coordinated Universal Time)

#react #form #state
star

Wed Feb 07 2024 00:44:59 GMT+0000 (Coordinated Universal Time)

#html #form #javascript
star

Wed Feb 07 2024 00:39:20 GMT+0000 (Coordinated Universal Time)

#html #form #radio_button #javascript #jquery
star

Wed Feb 07 2024 00:31:20 GMT+0000 (Coordinated Universal Time)

#css #html #form #checkbox #radio_button
star

Tue Nov 21 2023 01:37:36 GMT+0000 (Coordinated Universal Time) https://airtable.com/appx4s1nE9Kolw7qf/pagbWILEYl1BUqofc/form/embed

#airtable #form
star

Mon Dec 12 2022 11:04:48 GMT+0000 (Coordinated Universal Time) https://www.coursera.org/learn/advanced-react/quiz/vhZwu/self-review-create-a-registration-form

#react.js #registration #form
star

Tue Sep 06 2022 12:23:03 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#html #form #uploadfile
star

Mon Aug 08 2022 04:46:18 GMT+0000 (Coordinated Universal Time) https://developer.wordpress.org/plugins/plugin-basics/header-requirements/

#php #email #form #wordpress #header
star

Mon Jun 13 2022 16:28:04 GMT+0000 (Coordinated Universal Time) https://tanaikech.github.io/2022/04/05/creating-quizzes-in-google-form-using-google-forms-service-with-google-apps-script/

#quiz #form
star

Mon Apr 11 2022 23:38:31 GMT+0000 (Coordinated Universal Time)

#form #js
star

Tue Apr 05 2022 08:31:18 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/a/6881058/3238619

#php #html #form
star

Sun Mar 20 2022 18:08:42 GMT+0000 (Coordinated Universal Time) https://agency-website-c0d1e7.webflow.io/

#css #form
star

Sun Feb 20 2022 17:49:17 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/how-to-handle-multiple-input-field-in-react-form-with-a-single-function/

#react #form
star

Tue Feb 15 2022 04:42:32 GMT+0000 (Coordinated Universal Time)

#imageupload #form #html #php
star

Fri Feb 11 2022 00:06:31 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/php/php_file_upload.asp

#imageupload #form #html #php
star

Wed Sep 08 2021 14:47:57 GMT+0000 (Coordinated Universal Time) https://css-tricks.com/keyboard-only-focus-styles/

#css #a11y #form #button

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension