I. Valera
I. Valera

Reputation: 3

Appear a textbox only when the checkbox is checked and not save the field in the database if is not checked

Sorry for english grammar, not my native language.

I want to show a textbox only when the checkbox is checked. So, i have this code:

HTML

<table>
    <tr>
        <td>
            <input type = "checkbox" id="NCFtxt" onclick="obtenerNCF()"> Marcar casilla para generar Comprobante Fiscal
         </td>
    </tr>
    <tr>
        <td>
            NCF: <input readonly="readonly" name= "txtNCF" type= "text" id= "txtNCF" value= "<?php echo $cobro->ncf; echo $ncf; ?>" />
        </td>
    </tr>
</table>  

JAVASCRIPT

<script language="javascript">
$("#txtNCF").hide();

function obtenerNCF() { 
  var chequear = document.getElementById("NCFtxt");    

  if (chequear.checked == true){
  $("#txtNCF").show();

  } else {
    $("#txtNCF").hide();
  }
}
</script>

So, this is "working", is hiding the field when the checkbox is checked, but still saving the data at the Database. How can I do to not only hide the field, but neither saved in the database? I was trying some things but none worked, this seems simple, but it confusing me

Upvotes: 0

Views: 41

Answers (1)

IncredibleHat
IncredibleHat

Reputation: 4104

If you don't want to save something based on a checkbox... look at the $_POST if the checkbox has a value or not (if not, then it was not checked). Then save or not-save the extra data.

Give the checkbox a name and value:

<input type="checkbox" name="NCFtxt_checkbox" value="1" id="NCFtxt" onclick="obtenerNCF()">

And in PHP look for it:

if ( empty($_POST['NCFtxt_checkbox']) ) {
    // dont save extra data 
} else {
    // else do save the extra data
}

A second solution is to use a lot of javascript, and when the checkbox is UN-checked, you clear-out the content of the other text box as you hide it. That way it would be submitted 'emtpy' to begin with.

Upvotes: 1

Related Questions