Cara menggunakan javascript disable input checkbox

Cara penggunaan dan penulisan tag input type=”checkbox” telah kita bahas pada tutorial Belajar HTML Dasar: Cara Membuat Form di HTML (tag form), namun kali ini kita akan mempelajari beberapa atribut penting yang sering digunakan untuk tipe input ini.

Cara menggunakan javascript disable input checkbox

Pada contoh terakhir saya menggunakan tag label, tag fieldset dan tag legend yang telah kita pelajari pada tutorial form HTML: Fungsi dan Cara Penggunaan Tag Fieldset dan Tag Legend untuk menambah struktur dan mempercantik tampilan form.


Tag input type checkbox yang kita pelajari disini merupakan salah satu objek form yang penting. Checkbox sesuai untuk data form yang membolehkan user memilih lebih dari 1 inputan, namun jika anda membutuhkan objek form yang memaksa user memilih hanya satu dari beberapa pilihan, HTML menyediakan tag input type radio, yang akan kita bahas pada tutorial selanjutnya.

Ane coba buat function javascript yang bisa disable input setelah checkboxnya tercentang gan, dan skripnya jalan.. inputnya ter-disable setelah checkbox tercentang, tapi setelah saya klik lagi buat uncheck centangnya gak bisa ilang. Berikut ini ilustrasi dari skrip ane gan, maaf ga bisa ane paparin seluruhnya.
HTML:

Code:


 

Semua RT dan RW

Untuk javascript ane udah mencoba beberapa alternatif, termasuk dengan jquery

Code:


/*alternatif 1 javascript*/
function disable(id){
var checkbox = document.getElementById(id);
var rt = document.getElementById("selRT");
var rw = document.getElementById("selRW");

if(checkbox.checked = true){
rt.disabled = true;
rw.disabled = true;
}
else{
rt.disabled = false;
rw.disabled = false;
}
}
/*alternatif 2 jquery*/
$(document).ready(function() {
if($(".semua").prop('checked', false)){
$(".semua").click(function(){
$(".semua").prop('checked', true);
$("#selRT").prop('disabled', true);
$("#selRW").prop('disabled', true);
});
}
else{
$(".semua").click(function(){
$('.semua').removeAttr('checked');
$("#selRT").removeAttr('disabled');
$("#selRW").removeAttr('disabled');
});
}
});

*catatan atribut onclick udah ane ilangin pas ganti pake jquery.

Jadi dari kode diatas pas ane centang checkbox semua RT dan RW, select RT dan RW-nya terdisable, tapi pas ane ilangin centangnya di-checkbox buat enable select RT dan RW checkboxnya tidak bisa ter-uncheck alhasil inputnya juga masih ter-disable gan. Sekian gan pertanyaan ane, ane sudah berusaha menjelaskan sedetil2nya, ane harap agan bisa bantu, maaf no-cendol, karena ane belum bisa ngasih cendol, ane harap itu bukan halangan buat ane bisa dapat bantuan di sini. Sebelumnya thx ya gan
Cara menggunakan javascript disable input checkbox

A web form has a client-server relationship. They are used to send data handled by a web server for processing and storage. The form itself is the client, and the server is any storage mechanism that can be used to store, retrieve and send data when needed.

This guide will teach you how to create a web form with Next.js.

HTML forms are built using the

tag. It takes a set of attributes and fields to structure the form for features like text fields, checkboxes, dropdown menus, buttons, radio buttons, etc.

Here's the syntax of an HTML form:

The front-end looks like this:

Cara menggunakan javascript disable input checkbox

The HTML tag acts as a container for different elements like text field and submit button. Let's study each of these elements:

  • action: An attribute that specifies where the form data is sent when the form is submitted. It's generally a URL (an absolute URL or a relative URL).
  • 
      
      
    
      Submit
    
    
    0: Specifies the HTTP method, i.e.,
    
      
      
    
      Submit
    
    
    1 or
    
      
      
    
      Submit
    
    
    2 used to send data while submitting the form.
  • : An element that defines the label for other form elements. Labels aid accessibility, especially for screen readers.
  • : The form element that is widely used to structure the form fields. It depends significantly on the value of the
    
      
      
    
      Submit
    
    
    5 attribute. Input types can be text,
    
      
      
    
      Submit
    
    
    7,
    
      
      
    
      Submit
    
    
    8,
    
      
      
    
      Submit
    
    
    9, and more.
  • : Represents a clickable button that's used to submit the form data.

A process that checks if the information provided by a user is correct or not. Form validation also ensures that the provided information is in the correct format (e.g. there's an @ in the email field). These are of two types:

  • Client-side: Validation is done in the browser
  • Server-side: Validation is done on the server

Though both of these types are equally important, this guide will focus on client-side validation only.

Client-side validation is further categorized as:

  • Built-in: Uses HTML-based attributes like
    npx create-next-app
    
    0,
    
      
      
    
      Submit
    
    
    5,
    npx create-next-app
    
    2,
    npx create-next-app
    
    3,
    npx create-next-app
    
    4, etc.
  • JavaScript-based: Validation that's coded with JavaScript.
  • npx create-next-app
    
    0: Specifies which fields must be filled before submitting the form.
  • 
      
      
    
      Submit
    
    
    5: Specifies the data's type (i.e a number, email address, string, etc).
  • npx create-next-app
    
    2: Specifies minimum length for the text data string.
  • npx create-next-app
    
    3: Specifies maximum length for the text data string.

So, a form using this attributes may look like:

With these validation checks in place, when a user tries to submit an empty field for Name, it gives an error that pops right in the form field. Similarly, a roll number can only be entered if it's 10-20 characters long.

Cara menggunakan javascript disable input checkbox

Form Validation is important to ensure that a user has submitted the correct data, in a correct format. JavaScript offers an additional level of validation along with HTML native form attributes on the client side. Developers generally prefer validating form data through JavaScript because its data processing is faster when compared to server-side validation, however front-end validation may be less secure in some scenarios as a malicious user could always send malformed data to your server.

The following example shows using JavaScript to validate a form:


  
  

  
  

  Submit



The HTML script tag is used to embed any client-side JavaScript. It can either contain inline scripting statements (as shown in the example above) or point to an external script file via the

npx create-next-app
9 attribute. This example validates the name and roll number of a user. The

  
  
  
  
  Submit

0 function does not allow an empty name field, and the roll number must be at least three digits long. The validation is performed when you hit the Submit button. You are not redirected to the next page until the given values are correct.

Cara menggunakan javascript disable input checkbox

JavaScript validation with Regular Expressions uses the

npx create-next-app
4 HTML attribute. A regular expression (commonly known as RegEx) is an object that describes a pattern of characters. You can only apply the
npx create-next-app
4 attribute to the element. This way, you can validate the input value using Regular Expressions (RegEx) by defining your own rules. Once again, if the value does not match the defined pattern, the input will give an error. The below example shows using the
npx create-next-app
4 attribute on an

  
  
  
  
  Submit

5 element:


  
  

  Submit

The password form field must only contain digits (0 to 9), lowercase alphabets (a to z) and it must be no more than 15 characters in length. No other characters (#,$,&, etc.) are allowed. The rule in RegEx is written as


  
  
  
  
  Submit

6.

Cara menggunakan javascript disable input checkbox

To learn more about HTML forms, check out the MDN Web Docs.

In the following section you will be creating forms in React using Next.js.

Create a new Next.js app. You can use the for a quick start. In your command line terminal, run the following:

npx create-next-app

Answer the questions to create your project, and give it a name, this example uses


  
  
  
  
  Submit

7. Next

  
  
  
  
  Submit

8 into this directory, and run

  
  
  
  
  Submit

9 or
export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
0 command to start the development server.

Open the URL printed in the terminal to ensure that your app is running successfully.

Both the client and the server will be built using Next.js. For the server part, create an API endpoint where you will send the form data.

Next.js offers a file-based system for routing that's built on the concept of pages. Any file inside the folder

export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
1 is mapped to
export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
2 and will be treated as an API endpoint instead of a page. This API endpoint is going to be server-side only.

Go to

export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
1, create a file called
export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
4 and paste this code written in Node.js:

This form

export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
5 function will receive the request
export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
6 from the client (i.e. submitted form data). And in return, it'll send a response
export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
7 as JSON that will have both the first and the last name. You can access this API endpoint at
export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
8 or replace the localhost URL with an actual Vercel deployment when you deploy.

Moreover, you can also attach this API to a database like MongoDB or Google Sheets. This way, your submitted form data will be securely stored for later use. For this guide, no database is used. Instead, the same data is returned to the user to demo how it's done.

You can now use

export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
9 relative endpoint inside the action attribute of the form. You are sending form data to the server when the form is submitted via

  
  

  Submit

2 HTTP method (which is used to send data).


  
  
  
  
  Submit

If you submit this form, it will submit the data to the forms API endpoint

export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
9. The server then responds, generally handling the data and loading the URL defined by the action attribute, causing a new page load. So in this case you'll be redirected to
export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
8 with the following response from the server.

Cara menggunakan javascript disable input checkbox

You have created a Next.js API Route for form submission. Now it's time to configure the client (the form itself) inside Next.js using React. The first step will be extending your knowledge of HTML forms and converting it into React (using JSX).

Here's the same form in a React function component written using JSX.

export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}

Here's what changed:

  • The
    export default function PageWithoutJSbasedForm() {
      return (
        
          
          
    
          
          
    
          Submit
        
      )
    }
    
    4 attribute is changed to
    export default function PageWithoutJSbasedForm() {
      return (
        
          
          
    
          
          
    
          Submit
        
      )
    }
    
    5. (Since
    export default function PageWithoutJSbasedForm() {
      return (
        
          
          
    
          
          
    
          Submit
        
      )
    }
    
    4 is a keyword associated with the "for" loop in JavaScript, React elements use
    export default function PageWithoutJSbasedForm() {
      return (
        
          
          
    
          
          
    
          Submit
        
      )
    }
    
    5 instead.)
  • The action attribute now has a relative URL which is the form API endpoint.

This completes the basic structure of your Next.js-based form.

You can view the entire source code of next-forms example repo that we're creating here as a working example. Feel free to clone it and start right away. This demo is built with create-next-app, and you can preview the basic form CSS styles inside

export default function PageWithoutJSbasedForm() {
  return (
    
      
      

      
      

      Submit
    
  )
}
9 file.

Cara menggunakan javascript disable input checkbox

JavaScript brings interactivity to our web applications, but sometimes you need to control the JavaScript bundle from being too large, or your sites visitors might have JavaScript disabled.

There are several reasons why users disable JavaScript:

  • Addressing bandwidth constraints
  • Increasing device (phone or laptop) battery life
  • For privacy so they won’t be tracked with analytical scripts

Regardless of the reason, disabling JavaScript will impact site functionality partially, if not completely.

Next open the


  
  
  
  
  Submit

7 directory. Inside the 1 directory, create a file 2.

Quick Tip: In Next.js, a page is a React Component exported from a 3, 4, 5, or 6 file in the pages directory. Each page is associated with a route based on its file name.

Example: If you create 7, it will be accessible at 8.

Let's use the same code from above:

export default function PageWithoutJSbasedForm() {
  return (
    
      
      

      
      

      Submit
    
  )
}

With JavaScript disabled, when you hit the Submit button, an event is triggered, which collects the form data and sends it to our forms API endpoint as defined in the action attribute and using


  
  

  Submit

2 HTTP

  
  

  Submit

0. You'll be redirected to the
export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
9 endpoint since that's how form action works.

The form data will be submitted on the server as a request

export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
6 to the form handler function written above. It will process the data and return a JSON string as a response
export default function Form() {
  return (
    
      
      

      
      

      Submit
    
  )
}
7 with your submitted name included.

To improve the experience here, as a response you can redirect the user to a page and thank them for submitting the form.

Inside 1, you'll create another file called text7. This will create a text8 page on your Next.js app.

Now, as soon as the form is submitted, we prevent the form's default behavior of reloading the page. We'll take the form data, convert it to JSON string, and send it to our server, the API endpoint. Finally, our server will respond with the name submitted. All of this with a basic JavaScript text9 function.