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
Related
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
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.
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
}
);
I have a form that submits values to database via Ajax and works fine but I also need to give option to user to reset the form to its default values in case they make a mistake.
The default values are stored in a javascript variable as json object
{"field_name1":"2","field_name3":"3","field_name3":"1000"...
problem I have is that the form has multiple input types , textarea , select , radio
and I need to figure out what they are based on the object key , look for name and return type , so I could do something like if radio set checked checked and so on
I tried
Object.each(dafaultValues, function(value, key){
var filed_name = MyForm.elements[''+key+''];
console.log(filed_name.type);
});
problem with this is that radio type have same name but different id's
<input type="radio" name="field_name5" id="field_name51" value="1">
<input type="radio" name="field_name5" id="field_name52" value="1" checked="checked">
and I endup with js error
Uncaught TypeError: Cannot read property 'type' of undefined
so what would be the best way to find out what the input type is before I can do
if(field.type ='radio'){
//set checked checked..
}
Take a look at this example. I just put it together very dirty, but you will get the idea ;)
HTML:
<form id="test">
<input type="radio" name="abc" value="1"/>
<input type="radio" name="abc" value="2"/>
<input type="radio" name="abc" value="3"/>
<input type="text" name="def" value="change" />
</form>
JS:
var values = {
'abc': '2',
'def': 'original'
};
var els = $('test').getElements('[name="abc"], input');
els.each(function(el) {
var defaultVal = values[el.get('name')],
type = el.get('type');
if (typeof defaultVal != 'undefined') {
return;
}
if (type == "radio") {
if (el.get('value') == defaultVal) {
el.set('checked', 'checked');
} else {
el.erase('checked');
}
}
if (type == "text") {
el.set('value', defaultVal);
}
});
Ok, I've checked a lot of other answers but the solutions posted there are beyond the scope of the class I am taking. IE we haven't discussed how to do it that way.
Anyways, I'm simply trying to get the value from a radio button here is my html code and my javascript.
<script type="text/javascript">
function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
</script>
and the actual button looks like this in my html code.
Milwaukee: ($20) <input type="radio" name="radCity" value="20" />
When I alert(arrivalcity); all I get is NaN. I don't understand why, shouldn't it return the string 20??
Allow me to clarify. I have 3 different city choices. I have edited it to show exactly what I have when I begin my form.
<form name="reservations">
<p>First Name: <input type="text" name="txtFirstName" />
Last Name: <input type="text" name="txtLastName" /></p>
<span style="font-weight:bold;">Arrival City:</span><br />
Milwaukee: ($20) <input type="radio" name="radCity" value="20" /><br />
Detriot: ($35) <input type="radio" name="radCity" value="35" /><br />
St. Louis: ($40) <input type="radio" name="radCity" value="40" />
I need to get the value from whatever one is selected. I can't hardcode it into my script.
This function will do what you want, through the querySelector method:
function selectedRadio(){
var selValue = document.querySelector('input[name="radCity"]:checked').value;
alert(selValue);
}
JSFiddle
Reference
Do you have a form named reservation in your body?
It will work like this:
<form name="reservations">
<input type="radio" name="radCity" value="20" />
</form>
function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
See it running here: http://jsfiddle.net/eBhEm/
However, I would prefer this instead:
<input type="radio" id="radCity" value="20" />
And then use getElementById
function bookTrip()
{
var arrivalcity;
arrivalcity = document.getElementById("radCity").value;
alert(arrivalcity);
}
See this running on jsfiddle.
function bookTrip() {
var arrivalcity= document.reservations.radCity;
for (var i = 0, iLen = arrivalcity.length; i < iLen; i++) {
if (arrivalcity[i].checked) {
alert(arrivalcity[i].value);
}
}
}
i believe this should help.
see it working here
http://jsfiddle.net/eBhEm/24/
You can use querySelector in browsers that support it, but not all browsers in use do. The old fashioned (reliable, robust, works every where) method is to loop over the collection to find the one that is checked:
function getValue() {
var buttonGroup = document.forms['reservations'].elements['radCity'];
// or
// var buttonGroup = document.reservations.radCity;
// Check for single element or collection, collections don't have
// a tagName property
if (typeof buttonGroup.tagName == 'string' && buttonGroup.checked) {
return buttonGroup.value;
} else {
// Otherwise, it's a collection
for (var i=0, iLen=buttonGroup.length; i<iLen; i++) {
if (buttonGroup[i].checked) {
return buttonGroup[i].value;
}
}
}
}
Note that the test between an HTMLCollection and DOM element uses a property that DOM elements must have but an HTMLCollection should not have, unless a member of the collection has a name of "tagName".