0

I am having troubles with a script with JS, I am still learning but I am stuck for a while.

The solution should be, IF a checkbox is checked and the value is "" <-- the msgbox should say an message that the textbox should be filled with a value, and so for each checked checkbox, if you uncheck the checkbox, it should dissapear.

Code of 2 checkboxes in html page

<label>
  bangkirai
  <input id="chk_bangkirai" type="checkbox" onchange="enableTextBox()" />
</label>
<input type="text" id="bangkirai" name="bangkirai" disabled onchange="enableTextBox()" />

<label>
  beukenhout
  <input id="chk_beukenhout" type="checkbox" />
</label>
<input type="text" id="beukenhout" name="beukenhout" disabled/>

and the JavaScript, I made for each checkbox an other function, but I need to combine the error message in the same msgbox.

function enableTextBox() {
  divOutput = document.getElementById("msgbox2");
  strValideer = "<ul>";
  if (document.getElementById("chk_bangkirai").checked === true) {
      document.getElementById("bangkirai").disabled = false;
  }
  else {
    document.getElementById("bangkirai").disabled = true;
  }
  if (document.getElementById("bangkirai").value === "") {
    strValideer += "<li><b>bangkirai: </b>verplicht veld</li>";
  }
  strValideer += "</ul>";
  divOutput.innerHTML = strValideer;
}


function enableTextBox2() {
  divOutput = document.getElementById("msgbox2");
  strValideer = "<ul>";
  if (document.getElementById("chk_beukenhout").checked === true) {
    document.getElementById("beukenhout").disabled = false;
  }
  else {
    document.getElementById("beukenhout").disabled = true;
  }
  if (document.getElementById("beukenhout").value === "") {
    strValideer += "<li><b>beukenhout: </b>verplicht veld</li>";
  }
  strValideer += "</ul>";
  divOutput.innerHTML = strValideer;
}

I should probably use an array or an for each itteration ... but I can only find examples with forms ...

I will keep looking for a solution myself, but I hope I can get some inspiration here by experienced coders.

Thanks in advance

2 Answers 2

1

You could simplify this a lot and make it more... Concise and less dependent on which checkbox you have. We will do this with an external script and no onClick attributes on our HTML. This will enable us to separate our logic code from our design code. I will also use a placeholder instead of value, as it will create issues when people need to start entering a value (aka, you need to only have the text there when theres no value etc...) It just makes it more complicated.

Since we are dealing with numbers ('stuks' or amounts), lets also only allow number values to be inserted. Lastly, I have not bothered to replicate your HTML as I think the simplified example will make it easier to understand. Update I have also added the required and disabled sattributes here, settings your input to required when the checkbox is checked and disabled when not.

Check the below snippet for comments on the steps taken to do this:

// First, let select all fieldsets like this:

var fieldsets = document.querySelectorAll( 'fieldset.checkbox-message' );

// Lets loop through them

for( let i = 0; i < fieldsets.length; i++ ){
  
  // Lets create variables to store our fieldset, checkbox and input for later use.
  
  let fieldset = fieldsets[ i ];
  let checkbox = fieldset.querySelector( 'input[type="checkbox"]' );
  let input = fieldset.querySelector( 'input[type="number"]' );
  
  // Lets also store the message we put in placeholder
  // We will also give it a default value,
  // in case you forget to set the placeholder.
  
  let message = input.placeholder || 'Please fill in the amount';
  
  // Now lets define a function that will fill the placeholder
  // based on the checked value of the checkbox
  // We will be storing it in a variable because of the scope of a `for` block.
  // If you would use function setState() it might be defined globally
  // So multiply checkboxes would not work.
  
  let setState = function(){
    
    if( checkbox.checked ){
      
      input.placeholder = message;
      input.disabled = false;
      input.required = true;
      
    } else {
      
      input.placeholder = '';
      input.disabled = true;
      input.required = false;
      
    }
    
  }
  
  // Now lets listen for changes to the checkbox and call our setState
  
  checkbox.addEventListener( 'change', setState );
  
  // Lrts also call setState once to initialise the correct placeholder
  // for our input element to get started. This will remove any placeholders
  // if the checkboxes are unchecked.
  
  setState();
  
}
<fieldset class="checkbox-message">
  <label for="bangkirai">Bangkirai</label>
  <input type="checkbox" id="bangkirai" />
  <input type="number" placeholder="Tell us, how many 'bangkirai'?" />
  <span>stuks</span>
</fieldset>

<fieldset class="checkbox-message">
  <label for="beukenhout">Beukenhout</label>
  <input type="checkbox" id="beukenhout" />
  <input type="number" placeholder="How many 'beukenhout'?" />
  <span>stuks</span>
</fieldset>

Good luck coding!

Sign up to request clarification or add additional context in comments.

Comments

1

@somethinghere's answer is concise but if we modify your answer as it is you could check this

function enableTextBox() {

bangkirai_validation = document.getElementById("bangkirai_validation");


if (document.getElementById("chk_bangkirai").checked === true) {
    document.getElementById("bangkirai").disabled = false;
}
else {
    document.getElementById("bangkirai").disabled = true;
     bangkirai_validation.style.display='none';
     return;
}

if (document.getElementById("bangkirai").value =="") {
    bangkirai_validation.style.display='block';
    
}else
{
    bangkirai_validation.style.display='none';
}



}


function enableTextBox2() {
beukenhout_validation = document.getElementById("beukenhout_validation");

if (document.getElementById("chk_beukenhout").checked === true) {
    document.getElementById("beukenhout").disabled = false;
}
else {
    document.getElementById("beukenhout").disabled = true;
      beukenhout_validation.style.display='none';
     return;
}
if (document.getElementById("beukenhout").value == "") {
    beukenhout_validation.style.display='block';
}else
{
    beukenhout_validation.style.display='none';
}
}
<fieldset>
            <legend>Bestel gegevens</legend>
            <div class="container">
                <div class="row">
                    <div class="span7 id=" houtsoorten"">
                        <div class="control-group">
                            <label class="control-label">
                                bangkirai
                                <input id="chk_bangkirai" type="checkbox" 
onchange="enableTextBox()" >
                            </label>
                            <div class="controls">
                                <div class="input-append">
                                    <input class="inpbox input-mini" 
type="number" id="bangkirai" name="bangkirai" placeholder="aantal" disabled 
onkeyup="enableTextBox()" onchange="enableTextBox()">
                                    <span class="add-on">stuks</span>
                                    <div style="display:none;" id="bangkirai_validation">Please enter a value</div>
                                </div>
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label">
                                beukenhout
                                <input id="chk_beukenhout" type="checkbox" onchange="enableTextBox2()" >
                            </label>
                            <div class="controls">
                                <div class="input-append">
                                    <input class="inpbox input-mini" 
 type="number" id="beukenhout" name="beukenhout" placeholder="aantal" 
 disabled onkeyup="enableTextBox2()" onchange="enableTextBox2()" >

                                    <span class="add-on">stuks</span>
                                    <div style="display:none;" id="beukenhout_validation">Please enter a value</div>
                                </div>
                            </div>
                        </div>

5 Comments

Hey, just testing this and I think the mods on your second one aren't working (I cant get it to enable), maybe have a quick look into that?
Thanks it was missing an event handler
Looks pretty good I must say, tho I should get a modified message in the same messagebox, is that possible?
codepen.io/anon/pen/JvXbLG Can you see this code pen? When you enable a chekcbox, for EACH checkbox enabled the message should list at the bottem... This is what I get now with an other JS ... but still not proper
@VanonckelenDieter you can use the same output div if you pass the Id of it in both methods. Move the messsage div to the bottom

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.