Tricky javascript logic - javascript

I wanna ask about little tricky javascript, this is about if/else if/else question.
I want make question about 'YES' or 'NO', this is the logic : If question1 is 'yes' and question2 is 'yes' and question3 is 'NO' the result is 'good', and if question1 is 'yes' and question2 is 'no' and question3 is 'yes'the result is 'not good'. I was make the code for this case but not working properly, this is my codes, i use checkbox in html for choice answers :
javascript
<script type="text/javascript">
var question1 = document.getElementById("a");
question2 = document.getElementById("b");
question3 = document.getElementById("c");
answer1 = document.getElementById("d");
answer2 = document.getElementById("e");
answer3 = document.getElementById("f");
answer4 = document.getElementById("g");
answer5 = document.getElementById("h");
answer6 = document.getElementById("i");
function TheResult(form){
if(question1 == answer1 && question2 == answer3 && question3 == answer6 ){
document.write('good');
}else if(question1 == answer1 && question2 == answer4 && question3 == answer5 ){
document.write('not good');
}else {
document.write('ERROR');
}
}
html
<form>
<p id = "a"><b>Question1</b></p>
<input type="checkbox" name="a1" value="YES" id = "d">YES
<input type="checkbox" name="a1" value="NO" id = "e">NO<br><br>
<p id = "b"><b>Question2</b></p>
<input type="checkbox" name="a2" value="YES" id = "f" >YES
<input type="checkbox" name="a2" value="NO" id = "g" >NO<br><br>
<p id = "c"><b>Question3</b></p>
<input type="checkbox" name="a3" value="YES" id = "h">YES
<input type="checkbox" name="a3" value="NO" id = "i">NO<br><br>
<input type="button" name="Submit" value="Result" style="margin-left:100px;" onClick="TheResult(this.form)" >
</form>
my codes always print out 'good' in every situation, please help.

I'm actually pretty confused by the logic that you're presenting. As many have pointed out, you're trying to compare elements against each other. This won't give you the result that you want. You'll want to use .innerHTML or .value depending on the element type.
The next problem that I see is that your HTML structure, the Questions & Answers aren't associated with each other in any way.
Another problem I see comes when you are declaring your JS variables. You're trying to chain your declarations, which is fine. Although you need to be using , instead of ;. The ; should only be on the last one to be declared.
I assume most of these problems just came from you giving us some sample code. I expect your real code doesn't look like this, or you'd be having other problems noted in your question.
Regardless, I have a solution for you. I rewrote it in a way that makes more sense to me:
View Demo Here - JSFiddle
HTML:
<form>
<label for="a1" id="a">Question 1</label>
<input type="radio" name="a1" value="YES" id="d">YES
<input type="radio" name="a1" value="NO" id="e">NO
<br>
<br>
<label for="a2" id="b">Question 2</label>
<input type="radio" name="a2" value="YES" id="f">YES
<input type="radio" name="a2" value="NO" id="g">NO
<br>
<br>
<label for="a3" id="c">Question 3</label>
<input type="radio" name="a3" value="YES" id="h">YES
<input type="radio" name="a3" value="NO" id="i">NO
<br>
<br>
<input type="button" name="Submit" value="Result" style="margin-left:100px;" onClick="theResult()">
</form>
I made 2 changes. I got rid of the <p> elements in favor of <label>. And then I changed the checkboxes to radio buttons.
The JS
function theResult(){
var inputs = document.getElementsByTagName('input');
var question = [ {selected: '', expected: 'YES'},
{selected: '', expected: 'YES'},
{selected: '', expected: 'NO'}
];
var tmpSelected = [];
for(var i = 0; i < inputs.length; i++){
var tmp = inputs[i];
if(tmp.type == 'radio' && tmp.checked){
tmpSelected.push(tmp.value);
}
}
for(var i = 0; i < tmpSelected.length; i++){
question[i].selected = tmpSelected[i];
}
validateResults(question);
};
function validateResults(results){
var status = '';
for(var i = 0; i < results.length; i++){
if(results[i].selected != results[i].expected){
status = 'Not Good'
break;
} else {
status = 'Good';
}
}
console.log(status);
return status;
}
As you can see, I've made a lot of changes to this one. I wanted to make a better mapping between selected answer & the expected.
We then go through and grab all the inputs on the page. In the first loop, we make sure that we're only accepting radio buttons & only looking at the ones that have been checked or selected. We stuff those off into an array tmpSelected for a bit.
Then we assign the values of tmpSelected to our question object, specifically to .selected. This will make it easy to compare against the expected answer.
Then we'll make a call to a different function to validate the results (this logic could've been kept in the previous function, I just like splitting things up a bit to make them more modular).
the validateResults() simple compares .selected with .expected. If they don't match, we break our loop and return the status of 'Not Good'. Otherwise we keep evaluating. I did it this way because it seemed like your code was just returning a success/failure type message, and not necessarily saying which answers were incorrect.
The results are correctly logged to the console. So you'd just need to change that back to your document.write().

Try using this in each case:
var question1 = document.getElementById("a").innerHTML;
var answer1 = document.getElementById("d").innerHTML;
if(question1 == answer1 ){
document.write('good');
}
Start simple and build up.

Related

How to get the selected radio buttons value?

i am trying to get the value of selected radio buttons so i can submit my form using Ajax i searched here for some help but i couldn't find any useful solution
<input type="radio" id="answer" name="answer<?php echo $function::escape_string($question_row->question_id); ?>"
value="<?php echo $function::escape_string($answer_row>answer_id); ?>"/>
-HTML Output
<input type="radio" id="answer" name="answer16" value="107"/>
<input type="radio" id="answer" name="answer17" value="109"/>
<input type="radio" id="answer" name="answer15" value="104"/>
i found this function here
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert("Size is " + sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
var radioinputs = findSelection("answer");
But I do not know what to change so I can make it work with me properly
You can structure like this:
function findSelection(field) {
var test = document.getElementsByClassName(field);
var sizes = test.length;
//alert("Size is " + sizes);
result = [];
// result[16]=107;
// result[17]=109;
// result[15]=104;
for (i=0; i < sizes; i++) {
var index = test[i].dataset.index;
if(test[i].checked == true){
result[index] = test[i].value;
}else{
result[index] = undefined; // for a answer doesn't have a value
}
}
return result;
}
function checkfunction(){
var radioinputs = findSelection("radioanswer");
console.log(radioinputs);
console.log(radioinputs[15]);
};
<form id="form1">
<input type="radio" class="radioanswer" name="answer16" data-index="16" value="107"/>
<input type="radio" class="radioanswer" name="answer17" data-index="17" value="109"/>
<input type="radio" class="radioanswer" name="answer15" data-index="15" value="104"/>
<button type="button" onclick="checkfunction();"> Check </button>
</form>
A class can has multiple instances, but id has only one! And you can see document about data attributes here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
From the looks of it you have a dynamic name field, i.e. name="answer2", name="answer3", etc. Because of that your query document.getElementByName(field) will not find a field matching "answer".
To remedy this either get rid of the dynamic name or if you really need it then I would say add a class to all those radio buttons and use document.getElemenetsByClassName.

radio button .checked to perform a math expression using user input javascript

I have two textboxes where a user enters a number into each one and then clicks a radio button to select the mathematical operation to be performed upon the calculate button.This is for a homework assignment, so only javascript and html
are being used, no jquery. Currently when I click the button, nothing appears to happen and I am getting no console errors...
HTML
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1">
2nd number: <input type="text" name="number2">
<br>
<input type="radio" name="add">Add <br>
<input type="radio" name="subtract">Subtract <br>
<input type="radio" name="multiply">Multiply <br>
<input type="radio" name="division">Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
Javascript
function calculate(){
var num1 = parseInt("document.getElementsByName('number1').value;", 10);
var num2 = parseInt("document.getElementsByName('number2').value;", 10);
var add = document.getElementsByName("add");
var sub = document.getElementsByName("subtract");
var multi = document.getElementsByName("multiply");
var divis = document.getElementsByName("division");
var res = document.getElementById("math_res").innerHTML;
if (add.checked == true){
res = num1 + num2;
}
else if ( sub.checked == true){
res = num1 + num2;
}
else if (multi.checked == true){
res = num1 * num2;
}
else if (divis.checked == true){
res = num1 / num2;
}
}
I thought my function would take the input from the two text boxes and convert the user input to an integer and assign them to variable num1 and num2. Then assign each radio button to a variable to reduce typing of document.get...
that each if statement would check to see if that radio but was checked. If true perform calculation if false move to next if statement and display the results in a paragraph element.
where did I go wrong?
You have a couple of issues.
getElementsByName returns a collection of elements, not a single element so:
var add = document.getElementsByName("add");
will assign undefined to add. But you don't need to use it, just reference the controls as named properties of the form. Pass a reference to the button from the listener:
<input type="button" name="calc" onclick="calculate(this)" value="Calculate">
Then in the function get the form:
function calculate(element) {
var form = element.form;
Now just do:
var num1 = parseInt(form.number1.value, 10);
and so on, which also fixes the other issues you have with referencing the controls.
Also, radio buttons need to have the same name so that only one is selectable, so as Felix says, give them all the same name and differentiate on value (or class or some other attribute value). You'll need to loop over them to find out the operation to perform, so the HTML might be:
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
Then to get the operation:
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
Now check the value of op to work out whether to add, subtract, etc.
Here's a quick example, I don't recommend inline scripts like this but it's handy for playing.
<form>
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
<input type="button" onclick="
var form = this.form;
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
form.selectedOperation.value = op || 'No operation selected';
" value="Get selected operation">
<input type="text" readonly name="selectedOperation"><br>
<input type="reset">
</form>
There are a few issues I can notice.
1.
getElementsByName returns a NodeList, which is Array-like. You need to retrieve the first element in the NodeList before accessing its value. For example,
document.getElementsByName('number1')[0].value
2.
You are passing a literal code string to parseInt. You should write something like
parseInt(document.getElementsByName('number1')[0].value, 10);
3.
The code var res = document.getElementById('math_res').innerHTML stores a reference to the innerHTML of the element. When you assign res = num1 + num2 for example, you are simply overwriting the reference, instead of actually altering the innerHTML. To correct this,
var elem = document.getElementById('math_res');
// later...
elem.innerHTML = num1 + num2;
4. You are incorrectly defining multiple radio buttons with different names. In order for the browser to render them as a "radio button group" where only one can be selected, they must have the same name, but different "value" attributes. See RobG's answer or the Plunkr below for an example of how to define the radio button group and extract its value using JavaScript.
A working version of your code is here.
Edit Please note that these are minimal edits to make your code work. RobG's answer shows a more correct way of extracting the values of form fields.
Here is my version, hope it helps you.
<!DOCTYPE html>
<html>
<body>
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1" id = 'number1'>
2nd number: <input type="text" name="number2" id = 'number2'>
<br>
<input type="radio" name="button" id = 'add' >Add <br>
<input type="radio" name="button" id = 'substract'>Subtract <br>
<input type="radio" name="button" id = 'multiply'>Multiply <br>
<input type="radio" name="button" id = 'division'>Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
<script>
function calculate(){
//Obtaining the references to the text inputs
var number1 = parseInt(document.getElementById('number1').value);
var number2 = parseInt(document.getElementById('number2').value);
//Reference of the result Box
var resultBox = document.getElementById('math_res');
resultBox.innerHTML = '';
//Reference of the radio buttons
var buttonAdd = document.getElementById('add');
var buttonSubstract = document.getElementById('substract');
var buttonMultiply = document.getElementById('multiply');
var buttonDivision = document.getElementById('division');
//Make the magic
if(buttonAdd.checked == true){
resultBox.innerHTML = number1 + number2
}
else{
if(buttonSubstract.checked == true){
resultBox.innerHTML = number1 - number2
}
else{
if(buttonMultiply.checked == true){
resultBox.innerHTML = number1 * number2
}
else{
if(buttonDivision.checked == true){
resultBox.innerHTML = number1 / number2
}
}
}
}
}
</script>
</body>

Looping through checkboxes with javascript

I have a number of checkboxes which I am wanting to check if they are checked (1) or not checked (0). I want to place the results in an array so that I can send them to the server to saved in a table. I have tried the below code:
<input class="publish" id="chkBox1" type="checkbox" checked>
<input class="publish" id="chkBox2" type="checkbox" checked>
<input class="publish" id="chkBox3" type="checkbox" checked>
<input class="publish" id="chkBox4" type="checkbox" checked>
<input class="publish" id="chkBox5" type="checkbox" checked>
<script>
$('#save-btn').click(function(evt){
evt.preventDefault();
var numberOfChBox = $('.publish').length;
var checkArray = new Array();
for(i = 1; i <= numberOfChBox; i++) {
if($('#chkBox' + i).is(':checked')) {
checkArray[i] = 1;
} else {
checkArray[i] = 0;
}
}
alert(checkArray);
});
</script>
but the alert outputs this:
,1,0,1,0,1,1
The values are correct except the first index in undefined. There are only a total of 5 checkboxes and yet the array is 6 indexes long. Why is this?
Try this efficient way bruvo :) http://jsfiddle.net/v4dxu/ with proper end tag in html: http://jsfiddle.net/L4p5r/
Pretty good link: https://learn.jquery.com/javascript-101/arrays/
Also in your html end your tag /> i.e.
<input class="publish" id="chkBox4" type="checkbox" checked>
rest should help :)
Code
var checkArray = new Array();
$('input[type=checkbox]').each(function () {
this.checked ? checkArray.push("1") : checkArray.push("0");
});
alert(checkArray);
As mentioned in the answers above the problem is with the index(i). But if you want to simplify the code further, How about the following code?
var checkArray = [];
$('input.publish').each(function () {
checkArray.push($(this).is(':checked'));
});
alert(checkArray);
Take into account that the first element you write is checkArray[1], as i starts with 1, instead of checkArray[0].
Replace checkArray[i] with checkArray[i-1] inside the for bucle

Submiting values

I would like to create form with xy results
For example checking 'A' alone may produce result 1, while if both 'A' and 'B' are checked then the answer is result 2. D,E,A may give result 3 while B,E,A give result 2. Hopefully you get the point.
<form action="">
<input type="checkbox" name="options" value="A" />Choice A<br />
<input type="checkbox" name="options" value="B" />Choice B<br />
<input type="checkbox" name="options" value="C" />Choice C<br />
<input type="checkbox" name="options" value="D" />Choice D<br />
<input type="checkbox" name="options" value="E" />Choice E<br />
<br />
<input type="submit" value="answer">
and the jquery would be something along these lines
$(':checkbox').click(function () {
var value = $(this).val();
if ($(this).val(["A","B","C"]).is(':checked'))
$('.result1').show(value);
else
$('.result1').hide(value);
if ($(this).val(["A","D","E"]).is(':checked'))
$('.result2').show(value);
else
$('.result2').hide(value);
This don't work so if you could help me it would be great!
So, given A, B and C you want to do something. Which is different to A, B and E which might do something else. I've come up with this:
$(':checkbox').click(function () {
var checkedBoxes = $(':checked');
var values = new Array();
$.each(checkedBoxes, function(index, value) {
var checkboxValue = $(value).val();
values.push(checkboxValue);
});
if (containsOnly(values, ['A', 'B', 'C'])) {
alert('Hi');
}
if (containsOnly(values, ['A', 'D', 'E'])) {
alert('Bye');
}
});
function containsOnly(needles, haystack){
if (needles.length !== haystack.length) {
return false;
}
var result = _.intersection(needles, haystack).length === haystack.length;
return result;
}
So, what this does is it grabs all the checked checkboxes and then grabs the values contained within. Once it has the values, it compares them using UnderscoreJS's (underscorejs.org) intersection. That means we can check to see if (and only if) ALL of the values are contained within the array.
Once the check is complete and if it satisfies the conditions, it will do something.
Also, why underscore js? It provides a lot of really useful LINQ-like expressions for javascript and it saves you reinventing the wheel. Definitely worthwhile for iterator functions because it saves you time and effort.
As always, Fiddle: http://jsfiddle.net/KyleMuir/bUdra/5/
Hope this helps

how to use javascript to handle a large html checkbox?

So I have something like this inside a form
<input type="checkbox" name="arr" value="A" />A
<input type="checkbox" name="arr" value="B" />B
<input type="checkbox" name="arr" value="C" />C
<input type="checkbox" name="arr" value="D" />D
<input type="checkbox" name="arr" value="E" />E
...
<more checkboxes here>
...
In my Javascript I want to create an array that consists the values of boxes that are checked. So if B and D are checked it should be [B, D].
thanks
EDIT: My bad for not including a jQuery tag, but the guy who deleted his answer gave me a nice and short working solution using jQuery:
var valueArray = $('input[type="checkbox"][name="arr"]:checked').map(function() {
return this.value;
}).get();
Depending on what you're using it for, it may be enough to just use name="arr[]". When the form is submitted, the server-side will automatically convert the selected checkbox values to an array.
However, if you're trying to get this array purely in the client-side JavaScript, it's a little more involved. Try this:
function getCheckedBoxes(name) {
if( document.querySelectorAll) {
var qsa = document.querySelectorAll("input[type=checkbox][name='"+name+"']"),
l = qsa.length, i, out = [];
for( i=0; i<l; i++) if( qsa[i].checked) out.push(qsa[i].value);
}
else {
var qsa = document.getElementsByTagName('input'), l = qsa.length, i, out = [];
for( i=0; i<l; i++) {
if( qsa[i].type == 'checkbox' && qsa[i].name == name && qsa[i].checked)
out.push(qsa[i].value);
}
}
return out;
};
you could use jquery like this:
$("input[type=checkbox][name=arr][checked]").each(
function() {
// collect the values
}
);

Categories

Resources