0

I'm using HTML to create checklists through <input>. Here's a small sample of my code.

<input type="checkbox" value="Expedia" />
<img src="http://cruise360.org/media/ex_logos/3zp4zr1avvnfydluitkn4yur31iveig3172013_111844.jpg" style="width:236px;height:135px;" />
<br />

How can I make a javascript variable that is set to 0 or 1 depending on whether the option is checked. For example I'd have something like:

if (box is checked..) {
  expediaChecked == 1
} else {
  exediaChecked==0
}

How can I connect HTML and Javascript like that? Thank you.

3 Answers 3

1

This will solve your problem :

function myFunction(cb) {
expediaChecked = cb.checked ? 1 : 0;
    console.log(expediaChecked);  
}
<input type="checkbox" value="Expedia" onchange="myFunction(this)"><img src="http://cruise360.org/media/ex_logos/3zp4zr1avvnfydluitkn4yur31iveig3172013_111844.jpg" style="width:236px;height:135px;"><br>

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

2 Comments

If I wanted to change it to say an <h1> and have it change the variables value on click would I keep it the same as onchange="myFunction(this) or should I change it to onclick and also do I need to change the cb in the first part? How should I change it?
you want checkbox to be replace with h1 ? or you want checkbox inside h1 ?
0

You'd need some way to identify that input. I'd stick an id on there to make it cleaner/faster, but you can use class/tag.

if(document.getElementById('expediaBox').checked){
  expediaChecked = 1;
}else{
  expediaChecked = 0;
}

I believe you can one line it if you wanted to:

expediaChecked = document.getElementById('expediaBox').checked ? 1 : 0;

Edit: Apparently you can use document.querySelectorAll('input[value="Expedia"]') in place of the document.getElement if you're using a modern browser.

3 Comments

Thank you. I think it worked. Question though: when does it work, does the variable change to 1 as soon as I check it?
No, in order to change the variable on the fly, you'll want to wrap that check into an eventlistener.
document.getElementById('expediaBox').addEventListener('change', function(){ //stuff you want to run goes in here}); for example. webdeb's answer is cleaner
0

Define a onchange handler

<input id="expediaBox" type="checkbox" value="Expedia" />

document.getElementById('expediaBox').onchange = function(e) {
  expediaChecked = e.target.checked ? 1 : 0;
  // debug it
  console.log('checkbox checked', expediaChecked);
}

Comments

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.