How to import an array into a function in javascript? - javascript

I need some help with the code below:
<script type="text/javascript">
var opcao = new Array (
document.getElementById("cred_form_1864_1_wpcf-pde_Pesquisas_descontinuadas"),
document.getElementById("cred_form_1864_1_wpcf-pnps_Pesquisas_nao_patenteaveis-sigilosas")
);
function check1(){
if (opcao[0].checked == true){
for (var i = 0; i < opcao.length; i++){
if (i != 0){
opcao[i].checked = false;
opcao[i].disabled = true;
}
}
}
}
function check2(){
if (opcao[1].checked == true){
for (var i = 0; i < opcao.length; i++){
if (i != 1){
opcao[i].checked = false;
opcao[i].disabled = true;
}
}
}
}
</script>
I need to call the array 'opcao' within the functions 'check1 ()' and 'check2 ()'. How can I do this?
====================
I tried the suggestion of Mishik did not work. What I need is that the functions 'check1 ()' and 'check2 ()' to access the same array 'opcao'.
If I write the array within each function the code works perfectly. But how are the same values ​​I would have to repeat the same array for each function created.

If your code is executed before the page is loaded, then opcao array will not actually contain required elements.
You need to wrap your code in window.onload, so that by the time script is executed all the required elements will be available in the document.
window.onload = function() {
var opcao = new Array (
document.getElementById("cred_form_1864_1_wpcf-pde_Pesquisas_descontinuadas"),
document.getElementById("cred_form_1864_1_wpcf-pnps_Pesquisas_nao_patenteaveis-sigilosas")
);
function check1(){
if (opcao[0].checked == true){
for (var i = 0; i < opcao.length; i++){
if (i != 0){
opcao[i].checked = false;
opcao[i].disabled = true;
}
}
}
}
function check2(){
if (opcao[1].checked == true){
for (var i = 0; i < opcao.length; i++){
if (i != 1){
opcao[i].checked = false;
opcao[i].disabled = true;
}
}
}
}
}

Related

How do I get a toggle button to toggle an array back and forth from descending to ascending?

I am using bubbleSort, and I can get the array to toggle from its original order to descending, but I am having trouble getting it to go from descending back to ascending. Should I just copy the bubbleSort code and flip the greater than/less than signs? Any help is appreciated!
var myStuff = [];
function myfunctionA() {
var enteredvalue = document.getElementById("numbers").value;
// alert(typeof Number(document.getElementById('numbers').value));
if (enteredvalue == "") {
alert("Input is not a number");
} else if (isNaN(enteredvalue)) {
alert('You need to enter a valid number!');
}
var elementExists = false;
var x = document.getElementById('numbers').value;
for (var i = 0; i < myStuff.length; i++) {
if (myStuff[i] == Number(x)) {
elementExists = true;
}
}
if(elementExists != true) {
myStuff.push(Number(enteredvalue));
alert('Thank You for entering a valid number.');
} else {
alert('Element is here');
}
}
function myfunctionB() {
window.alert(myStuff.length);
}
function myfunctionC() {
var sum = 0;
for(var i = 0; i < myStuff.length; i++) {
sum+=myStuff[i];
}
alert(sum);
}
function myfunctionD() {
if (myStuff.length == 0) {
alert("already empty");
} else {
myStuff = [];
}
alert("Array Empty");
}
function myfunctionE() {
alert(myStuff.join('\n'));
{
if (myStuff == []) {
alert("Enter something into Array")
}
}
}
function bubbleSort() {
var sorted = true;
var temp;
while(sorted) {
sorted = false;
for(var i = 0; i < myStuff.length-1; i++) {
if(myStuff[i] < myStuff[i+1]) {
temp = myStuff[i];
myStuff[i] = myStuff[i+1];
myStuff[i+1] = temp;
sorted = true;
}
}
}
}
First you'll need a toggle to tell which way you are going.
var isAscending = false;
Then in your bubbleSort function inside the for-statement, above the if-statement.
var sortComparison;
if (isAscending) sortComparison = myStuff[i] > myStuff[i];
if (!isAscending) sortComparison = myStuff[i] < myStuff[i];
Then replace your if-statement with:
if (sortComparison)
Finally, once you have finished sorting, you can toggle your variable:
isAscending = !isAscending;
Though, I'd recommend using a toggled variable and simply using sort() and reverse() instead.
https://jsfiddle.net/ytcax0qc/

why two $scopes updates at the same time, duplicate data

I have this piece of code
$scope.addToOrder = function(index) {
var tempItem = $scope.item;
if (tempItem[index].validate == true){
if (_.isEmpty($scope.item2) == true) {
$scope.item2.push(tempItem[index]);
} else {
for (var i = 0; i < $scope.item2.length; i++) {
if ($scope.item2[i] == tempItem[index]) {
break;
}
if (i == $scope.item2.length - 1) {
$scope.item2.push(tempItem[index]);
}
}
}
}
}
I want to push data from one object to other (item to item2), it works well, but when i change data from item also item2 updates i dont want this.
What i missing?
As is, you are using an object reference. Then if modify one, the othes one is modified too.
You could use angular.copy
$scope.addToOrder = function(index) {
var tempItem = $scope.item;
var itemCopy = angular.copy(tempItem[index]);
if (tempItem[index].validate == true){
if (_.isEmpty($scope.item2) == true) {
$scope.item2.push(itemCopy);
} else {
for (var i = 0; i < $scope.item2.length; i++) {
if ($scope.item2[i] == tempItem[index]) {
break;
}
if (i == $scope.item2.length - 1) {
$scope.item2.push(itemCopy);
}
}
}
}
}
use angular.copy to cope by value
angular.copy($scope.item1, $scope.item2);
or
$scope.item1 = angular.copy($scope.item2);

javascript for loop dosn't loop through users created

OK so I am making a register and login for a forum using javascript and localstorage. "School assignment" My problem is that when i created multiple user and store them in the localstorage, my for loop does not loop through them all, only the first one. So i can only access the forum with the first user i create.
function login () {
if (checklogin()) {
boxAlert.style.display = "block";
boxAlert.innerHTML = "Welcome" + "";
wallPanel.style.display = "block";
} else {
boxAlertfail.style.display = "block";
boxAlertfail.innerHTML = "Go away, fail";
}
}
function checklogin (){
for (var i = 0; i < aUsers.length; i++){
if (aUsers[i].email == inputLoginMail.value && aUsers[i].password == inputLoginPassword.value){
return true;
}else{
return false;
}
}
}
how about:
function checklogin() {
var validLogin = false;
for (var i = 0; i < aUsers.length; i++) {
if (aUsers[i].email == inputLoginMail.value
&& aUsers[i].password == inputLoginPassword.value) {
validLogin = true;
break;
}
}
return validLogin;
}
Ouch! You are returning false on very first attempt. The best way is to set a variable and then check for it.
function checklogin() {
var z = 0;
for (var i = 0; i < aUsers.length; i++) {
if (aUsers[i].email == inputLoginMail.value && aUsers[i].password == inputLoginPassword.value) {
z = 1;
break;
} else {
z = 0;
}
if (z == 1) {
// User logged in
} else {
// Fake user
}
}

JS loop only works when matching to the last element in an array

I cannot get the loop to work in my simple js login script. When i try to login with any login other than the last one in the array (user3 and pass3) it returns false.
What am I doing wrong?
I have tried both == and ===.
var userLogins = [{user:"user1", password:"pass1"},{user:"user2", password:"pass2"},{user:"user3", password:"pass3"}]
var success = null;
function logon(user, pass) {
userok = false;
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
secret(success);
}
function getData() {
var user = document.getElementById("userid").value;
var password = document.getElementById("password").value;
logon(user, password);
}
function secret(auth){
if(auth)
{
show('success');
hide('login');
}
else
{
show('error');
hide('login');
}
}
function show(show) {
document.getElementById(show).className = "show";
}
function hide(hide) {
document.getElementById(hide).className = "hide";
}
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
You need a break in there, otherwise your true value for success simply gets overwritten with false on the next iteration... except for the last possible credentials, for which there is no "next" iteration.
Once you've done that, you don't actually need the else branch at all:
var success = false;
for (i = 0; i < userLogins.length; i++) {
if (pass == userLogins[i].password && user == userLogins[i].user) {
success = true;
break;
}
}
Use break when you found it. Otherwise the next loop will set success to false.
for (var i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
break;
}
else
{
success = false;
}
}
secret(success);

Mark unmark javascript?

I've got a function to select all checkboxes in a table:
<script type="text/javascript">
function checkAll() {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
elems[i].checked = true;
}
}
}
But I can't get it to uncheck them all if they are checked. How could I do that?
<th width='2%'>Mark</th>";
Also in javascript is it possible to rename "Mark" to "Un-Mark" if I execute checkAll()?
This should do both of the things u want:
function checkAll(obj) {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
if(elems[i].checked == true){
elems[i].checked = false;
}
else{
elems[i].checked = true;
}
}
}
if(obj.innerHTML == 'Mark') { obj.innerHTML = 'Unmark' }
else { obj.innerHTML = 'Mark' }
}
html:
<th width='2%'>Mark</th>";
1) why don't u use some js framework, like jQuery?
2) to remove checked, use elems[i].removeAttribute('checked') or set elems[i].checked = false;
3) to rename, you have to set it's innerHTML or innerText to Un-Mark
Add a little more logic to see if they're already checked. This will invert their current checked state.
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
if (!elems[i].checked) {
elems[i].checked = true;
}
else elems[i].checked = false;
}
}
If you just want to uncheck all, simply use:
elems[i].checked = false;
This will check them all regardless of their current state, or uncheck them all, depending on the current text of "Mark" or "Unmark".
<script type="text/javascript">
function checkAll(obj) {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
var state = obj.innerHTML == 'Mark';
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
elems[i].checked = state;
}
}
obj.innerHTML = state ? 'Mark' : 'Unmark';
}
And then the HTML changes to:
<th width='2%'>Mark</th>";
To uncheck, try:
elems[i].checked = false;
i sugest you use jquery, everything is easier.
with jquery you just have to do something like this (+/-):
$(function(){
$('a.ClassName').click(function(){
var oTbl = $('#tableID');
$('input[type="checkbox"]', oTbl).attr("checked", "checked")
});
})

Categories

Resources