Home > Software design >  How can I make the entered text and checkbox text go to the same textfield?
How can I make the entered text and checkbox text go to the same textfield?

Time:05-26

when the project name is entered, it populates in the same text field as the checked boxes text but at the top of the field.

I also want to create a button for sending the completed form if that's possible

html

    <div >
            <form>
                <label for="projectname">Project name:</label>
                <input type="text" id="pname" name="pname"><br>
                <br>
        </div>
                <br>
      <div > 
        <tr><input type="checkbox" rel="textbox1" name="Cabinets" class=test/>
         Cabinets</tr>
         <input type="checkbox" rel="textbox1" name="Doors" />
         Doors
         <input type="checkbox" rel="textbox1" name="Drawers">
         Drawers
         <input type="checkbox" rel="textbox1" name="Drawer Fronts">
         Drawer Fronts
         <input type="checkbox" rel="textbox1" name="Handles">
         Handles
     </div>
    
     <textarea id="textbox1" ></textarea>

js

    $('input:checkbox').click(function(){
        var tb = "#" $(this).attr('rel');
        let text_to_add = this.name   "\n";
        //when click a checkbox and show checked items in the text area
        if($(this).is(":checked")){
            $(tb).append(text_to_add);
        }else{
            let remove = this.name  "\n";
            //when a box is unchecked it clears the previously populated text from checkbox
            $(tb).text(function(i, text){
                return text .replace(text_to_add,'');
            });
        }
            
    })

CodePudding user response:

The solution i would come up with will be: to store the exist value from the textarea everytime you change the text area value.

let existValue = ''
//inside the checkbox click function:
existValue = $(tb).val()  

then to add an event listener to the input and everytime the input change to add the e.target.value to the exist value we created before

$('#pname').on('input', (e)=>{
  
  $('#textbox1').val(`${e.target.value}\n${existValue}`)
})

here is a working example: working example

  • Related