vendredi 9 mars 2018

how to define variable based on a checkbox using html and javascript

I am trying to generate a checkbox that will define a variable x based on whether a checkbox is checked or not checked. If the checkbox is checked then the variable equals myvalue and if the checkbox is unchecked the variable equals "No Value". How do I tweak the below code to get the desired result?

<!DOCTYPE html>
<html>
<body>

Checkbox: <input type="checkbox" id="myCheck" value="myvalue"     onclick="myFunction()">

<p>Click the "Try it" button to display the value of the value attribute of the checkbox.</p>



<p id="demo"></p>

<script>

function myFunction() {
    if (x == null){
        var x = "NO value"
    }
    else
    {
        var x = document.getElementById("myCheck").value
    }
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>




Aucun commentaire:

Enregistrer un commentaire