Check values of loop to see if ANY match? - javascript

In ruby, I would do something like:
array = [1,2,3]
array.any? {|a| a == 1}
=> true
Although, instead of an array, I am going up against a hash
var shop_products = {"607":607};
I have a checkbox loop and I want to check against all currently checked boxes for when checkboxes are both checked and unchecked to then see if there is a matching value and disable/able and hide/show a button if so.
code: https://jsfiddle.net/mk879vu2/7/
As #Mark Meyer mentioned, some can help but is there a way to use this against a hash or an alt for hashes?
I tried this: https://jsfiddle.net/jq9sgp58/
Maybe I am using this wrong?
My issue right now is when a checkbox is unchecked, it sees that the value is the "correct" one, but it isn't displaying the button when I uncheck. I'm doing something wrong in the conditional somehow.
In the jsfiddle I have all of the inputs but I only want one of the buttons (of the 2) to appear when a record with specific parameters is checked (in the example this is value=607, this can be any amount but in the example I have it as 1 record/input). But when I uncheck and the 607 is left alone as the only checked input, it runs the hide/disable and not the show.
What is wrong with my code?

It sounds like you are looking for #array.some()
let a = [1,2,3]
console.log(a.some(n => n === 1)) // true
console.log(a.some(n => n === 4)) //false

https://jsfiddle.net/2kaegb59/
The .some seemed like the way to get it done but i couldn't get it to work with the hash. I'm sure it's possible. Although, I ended up just checking for an undefined through the hash instead of trying to match up the check value with the hash value and it is likely unnoticeably faster.
for (var check of checked_checkboxes_check) {
if (shop_products[check.value] === undefined) {
print_submit.hide().prop("disabled", true);
break;
} else {
print_submit.show().prop("disabled", false);
}
}

Related

Finding the value of an array?

I am coding a sequencer that allows you to choose which sound you want to be carried into different parts of the code. I am using an array that holds the sound ID value and if a different sound is selected, the array is reset and the value changes. Initially, I thought using this snippet would work to check what sound has been chosen:
if(sounds == 1){
//insert effect of sound value
}
But, this did nothing. I then tried:
sounds == [1];
but that had no effect at all. What code should be used when trying to execute code based on the value of an array with a single item (if that makes sense)?
Firstly, by writing sounds == 1 you are checking if the size of "sounds" array is 1 or not.
To access the value of the array element itself use:
sounds[0] == n
Count in array starts from 0, and last element will be length of array sounds.length - 1
Now, if I correctly understood your question itself and you want to output certain sound based on which element is chosen from array, then you could use Switch / Case. First iterate through array using for loop. Then declare Switch() expression. Then, write what kind of output / action should happen when case happens.
for (int i = 0; i < values.length; i++) {
Switch (sounds[i]) {
case 1: // imagine sound ID is 1
//output code // this code will get executed
break;
case 2: // sound ID is 2
//output code // this code will get executed
break;
case 3: // sound ID is 2
//output code // this code will get executed
break;
}
}
As far as I understand your concern, You want to check the value inside the array right?
In that way, You can check the values of the array by using includes() method.
Like:
sounds = [1,2,3,4,5,6];
if(sounds.includes(1)) {
//insert effect of sound value
} else {
// Do else thing here.
}
This might resolve your issue.
Based on our question, you are saying you have an array of sound values. I imagine it looks like
var sounds = ["1"]
If this is the case, you can do sounds.includes("1") to see it "1" is present.

JQuery onChange uses values before change (values after change needed)

I am working on a module, which should select the only possible value of a Multi- or Single selection field, if there is only one valid value and a empty one available.
So far its working fine, until I use ACLs to disable selection values.
For example, I got a single selection field with 3 possible values. Then I disable 2 of them (ACL - if there is a special Queue selected) so theres only one value (+ an empty one) left.
My module wont pick the last value at first, but when I change anything else on the same page (second onchange call) it will pick the last possible value.
The first if condition checks if the Field has only one possible value in it. When I log the 'Change' array it always got the disbaled values still in there even when the 'change' that called the whole function was the ACL disabling those values.
Im still kinda new to javascript and havent found a solution yet.
I would realy appreciate any help.
$('.TableLike').on("change", function () {
var Change = [];
$('.Row').each( function() {
$(this).children().next().children().next().children().each( function(index) {
Change[index] = $(this).text()
} )
if ( (!Change[2] || /.*Field needed.*/i.test(Change[2])) && Change[0] === "-") {
SoleOption = Change[1];
$(this).children().next().children().next().children().each(function() {
if ($(this).text() === "-") {
$(this).removeAttr("selected");
}
if ($(this).text() === SoleOption) {
$(this).attr("selected", "selected");
}
} )
$(this).children().next().children().children().children().val(SoleOption)
}
SoleOption = "";
Change = [];
} )
} )
I managed to fix the issue with the setTimeout() Method.
So the DOM updated before the ACL did the changes.
I opened up the setTimeout Method after the onChange method and inserted all the code thats supposed to run after the change into the setTimeout method.
I hope this will be helpfull for others in the future.

Show alert after all requirements have been met

I have a form where the user can 1.) check one option and be done. or 2.) check the other option and fill out a text field.
Whole thing is, after all is said and done I'd like for my alert to show, but it doesn't.
$('.know-your-role').show('fast', function() {
var $checkboxes = $('input:checkbox.checkchoice');
if($checkboxes.is(':checked')){
// show this after checked and the input has been filled.
alert('cool');
}else if($checkboxes.is(':checked') & $(".year").va() != "" ){
alert('cool');
}
});
How do I get the alert to show after all requirements (checkboxes and input) have been met?
I've made a fiddle here to show what I'm working with.
Thank you for your help in advance.
As well as the previous correct answers (missing & and misspelled val) there is a more fundamental logical issue here. You seem to have this structure:
if (conditionA) {
// behaviorA
} else if (conditionA && conditionB) {
// behaviorB
}
You will never reach behaviorB with such logic. If conditionA fails then conditionA && conditionB will certainly also fail.
Do you need to reverse the order of your if and else-if blocks?
Missing '&'
$checkboxes.is(':checked') && $(".year").val() != ""
You should use && instead of & for boolean comparisons, and also you appear to have mis-typed val as va.
I would suggest having two events, one on the 'Teacher' check box being checked and one on the year field being completed. Both events can trigger a single function that shows your alert and whatever other logic you want. So there is little duplication.
This helps to separate the events from the logic that shows/hides the year field and more easily allows you to perform different actions for the two events if that's a requirement.

Checking all radiobuttons without Jquery

i want to check the first element of multiple radiobutton groups.
I'm using Firebug, which is why i do not want, yes i know there is firequery, but there must be a way like they did it in the old days :)
Any help yould be great, thx in advance.
Loop backwards over document.getElementsByTagName('input') and set checked to true if type is equal to "radio".
If you try to check multiple buttons in the same group, the last one will hold.
Thus, looping backwards will end up checking the first option in each group.
Update
Feeling a bit silly here, you said you were using Firebug, and thus Firefox, and so we have querySelector available. Thus checking the first radio button in any given group is a one-liner:
document.querySelector('input[type="radio"][name="theGroupName"]').checked = true;
Live example
querySelector returns the first matching element, and so the above will return the first input element with type="radio" and name="theGroupName". Then we just set its checked to true.
Granted that doesn't do the first of all groups, but it gives you more control and is (again) a one-liner — handy for Firebug.
Original answer
You can use getElementsByTagName to get all input elements in document order. Then loop through them, only processing the ones with type="radio" and remembering the last name you encoutered; mark checked = true for the first of each name.
E.g.:
var inputs = document.getElementsByTagName('input');
var lastName, index, input;
for (index = 0; index < inputs.length; ++index) {
input = inputs.item(index);
if (input.type.toLowerCase() === "radio") {
if (input.name !== lastName) {
lastName = input.name;
input.checked = true;
}
}
}
Live example
If you want to limit that to some container, you can use the element version of getElementsByTagName.

Compare old values against the new values of Form

I have a form with several fields, one of which is "counter", that gets changed constantly. When the form is edited I need to track if some fields are changed and set the "counter" field to the number of modified fields up on submission. For example, if the old value of counter is 10 and field1, field2 and field3 are modified, then on form submit counter should be incremented to 13.
Below is what I'm attempting to do just for one field but its not working correctly. I also need to check not only one field but a few other fields too. Any help is appreciated. Thanks!
$(document).ready(function(){
var oldVal = getOldValue("field1");
var oldCounter = parseInt(getOldValue("Counter"));
var curCounter;
$('field1').change(function(){
var newVal= $(this).val();
if(oldVal.val() == newVal.val()){
curCounter = oldCounter +1;
setField("Counter", parseInt(curCounter));
}
});
});
Your if statement is incorrect. It fires when the value has changed (.change()), yet you are checking if the value is the same through if(oldVal.val() == newVal.val())
Also, .val() is a method of the jQuery object, so unless the function getOldValue() returns a jQuery object, your if statement is probably not going to do what you're expecting it to do.
What I'd do is store the oldValues of the form fields inside a data attribute of the formfield, so you can easily access it from within the .change() event, something like:
$(document).ready(function(){
var oldCounter = parseInt(getOldValue("Counter"), 10); // use the second argument '10' here or you might get strange results
var curCounter = oldCounter;
$('.field').each(function() {
// store the old value
$(this).data("oldValue", getOldValue($(this).attr("id")));
})
.change(function(){
// compare values, increase counter if it is different than the original value
if($(this).data("oldValue") != $(this).val()) {
curCounter++;
setField("Counter", curCounter);
}
});
});
Untested code but you get the gist, hope this helps
3 things i've noticed
*. you are checking the newVal's value twice, it should be something like
var newVal = $(this).val();
if (oldVal == newVal).....
*. for the oldValue variable you can just do var oldVal=$('#filed1_id').val(); this will be much simpler and will get you the value needed and not the object, this is simpler to handle.
*. you say you need to check for change on submission but you're checking on change, change it to which means you'll be checking more often when you need to.
and again, it will be nice to know what's getOldValue does.
good luck
I assume you want to know whether the user modified any fields when the form is submitted. It would be easiest to use .data() to keep track of which fields have changed from their original value. As other posters have mentioned your code calls .val() redundantly, incorrectly uses == instead of !=, and might not be using jQuery objects correctly.
This fiddle should address your issues: http://jsfiddle.net/EYjxP/

Categories