The Checkboxes are used to let a user select one or more options for a limited number of choices. The :checkbox selector selects input elements with type checkbox.
Syntax:
$('#textboxID').val($("#checkboxID").is(':checked'));
In the above syntax, basically the return value of the checked or unchecked checkbox is being assigned to the textbox. Below examples will illustrate the approach:
Example 1: Here the return value of the checkbox is assigned to the textbox with a function click() whenever the checkbox is clicked to check or uncheck, it assigns the respective return value into the textbox. So, if we want to assign a certain user-defined value in the textbox according to check then we can do that with the use of if/else statement.
<!DOCTYPE html> < html > < head > < script src = </ script > < script > $(document).ready(function() { // Set initial state $('#textbox2').val($(this).is(':checked')); // It gets checked to false as uncheck // is the default $('#checkbox1').click(function() { $('#textbox2').val($(this).is(':checked')); }); }); </ script > </ head > < body > < center > < h1 style = "color:green;" > GeeksforGeeks </ h1 > < p > A Computer Science Portal for Geeks </ p > < input type = "checkbox" id = "checkbox1" /> Check if true, Uncheck if false. < br >< br > < input type = "text" id = "textbox2" /> </ center > </ body > </ html > |
Output:
Example 2: This example conatains more than one checkboxes.
<!DOCTYPE html> <html> <head> <script src= </script> <script> $(document).ready( function () { // Set initial state $( '#textbox1' ).val( 'no' ); // Returns yes or no in textbox1 // when checked and unchecked $( '#checkbox1' ).click( function () { if ($( "#checkbox1" ).is( ":checked" ) == true ) { $( '#textbox1' ).val( 'yes' ); } else { $( '#textbox1' ).val( 'no' ); } }); // Returns male in textbox2 if checkbox2 checked. $( '#checkbox2' ).click( function () { if ($( '#checkbox2' ).is( ":checked" ) == true ) { $( '#textbox2' ).val( 'Male' ); } else { $( '#textbox2' ).val( '' ); } }); // Returns female in textbox2 // if checkbox2 checked. $( '#checkbox3' ).change( function () { if ($( '#checkbox3' ).is( ":checked" ) == true ) { $( '#textbox2' ).val( 'Female' ); } else { $( '#textbox2' ).val( '' ); } }); }); </script> </head> <body> <center> <h1 style= "color:green" > GeeksforGeeks </h1> <p> A Computer Science Portal for Geeks </p> <input type= "checkbox" id= "checkbox1" /> Check If yes! <br> <input type= "text" id= "textbox1" /> <br> <input type= "checkbox" id= "checkbox2" /> Male <input type= "checkbox" id= "checkbox3" /> Female <br> <input type= "text" id= "textbox2" /> </center> </body> </html> |
Output: