what is wrong with this code I get an undefined error. my checkbox is not an array on front end it uses different names and I want user to select only one checkbox:
function select_item(index){
var choice_options = [];
choice_options['S'] = 'item_cb_S';
choice_options['T'] = 'item_cb_T';
choice_options['Z'] = 'item_cb_Z';
choice_options['D'] = 'item_cb_D';
choice_options['N'] = 'item_cb_N';
for (i in choice_options) {
var vl = choice_options[i];
if(vl.substring(8) == index) {
document.wizardform.choice_options[index].checked = true;
//alert("true");
}
else {
document.wizardform.vl.checked = false;
}
}
return true;
}
It's not so pretty but you could use eval......
function select_item(index){
var choice_options = [];
choice_options['S'] = 'item_cb_S';
choice_options['T'] = 'item_cb_T';
choice_options['Z'] = 'item_cb_Z';
choice_options['D'] = 'item_cb_D';
choice_options['N'] = 'item_cb_N';
for (i in choice_options) {
var vl = choice_options[i];
if(vl.substring(8) == index) {
eval("document.wizardform." + choice_options[index] + ".checked = true;");
//alert("true");
}
else {
document.wizardform.vl.checked = false;
}
}
return true;
}
Related
I have a javascript snippet that doesn't work properly on Safari / iOS and would like some help.
let coverageAtt1 = document.getElementById("att-check1");
let coverageAtt2 = document.getElementById("att-check2");
let coverageAtt3 = document.getElementById("att-check3");
let coverageAtt4 = document.getElementById("att-check4");
let checkboxes = [coverageAtt1, coverageAtt2, coverageAtt3, coverageAtt4];
let attributeCond = [];
let coverageCond = '';
for (let checkbox of checkboxes) {
checkbox.oninput = function() {updateAtt()};
function updateAtt() {
if (checkbox.checked) {
attributeCond.push(checkbox.value);
}
else if (attributeCond.includes(checkbox.value)) {
attributePosition = attributeCond.indexOf(checkbox.value);
attributeCond.splice(attributePosition, 1);
}
else {
null;
}
console.log(attributeCond);
sliders();
}
}
function sliders() {
filteredPlans = plans.filter((item) => {
if (attributeCond.length == 0) {
coverageCond = attributeCond.includes(item.coverage) == false;
}
else {
coverageCond = attributeCond.includes(item.coverage) == true;
}
return (coverageCond);
});
Opening the console in Safari states that the "checkbox" variable have not been declared/cannot be found.
I am trying to fix this script to automatically connect people you may know on Linkedin based on User roles (CEO e.t.c), Can someone help me fix this, Below is my code; I have tried the script on almost all browsers, Somebody help fix this.
var userRole = [
"CEO",
"CIO"
];
var inviter = {} || inviter;
inviter.userList = [];
inviter.className = 'button-secondary-small';
inviter.refresh = function () {
window.scrollTo(0, document.body.scrollHeight);
window.scrollTo(document.body.scrollHeight, 0);
window.scrollTo(0, document.body.scrollHeight);
};
inviter.initiate = function()
{
inviter.refresh();
var connectBtns = $(".button-secondary-small:visible");
//
if (connectBtns == null) {var connectBtns = inviter.initiate();}
return connectBtns;
};
inviter.invite = function () {
var connectBtns = inviter.initiate();
var buttonLength = connectBtns.length;
for (var i = 0; i < buttonLength; i++) {
if (connectBtns != null && connectBtns[i] != null) {inviter.handleRepeat(connectBtns[i]);}
//if there is a connect button and there is at least one that has not been pushed, repeat
if (i == buttonLength - 1) {
console.log("done: " + i);
inviter.refresh();
}
}
};
inviter.handleRepeat = function(button)
{
var nameValue = button.children[1].textContent
var name = nameValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
function hasRole(role){
for(var i = 0; i < role.length; i++) {
// cannot read children of undefined
var position = button.parentNode.parentNode.children[1].children[1].children[0].children[3].textContent;
var formatedPosition = position.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var hasRole = formatedPosition.indexOf(role[i]) == -1 ? false : true;
console.log('Has role: ' + role[i] + ' -> ' + hasRole);
if (hasRole) {
return hasRole;
}
}
return false;
}
if(inviter.arrayContains(name))
{
console.log("canceled");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (hasRole(userRole) == false) {
console.log("cancel");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (button.textContent.indexOf("Connect")<0){
console.log("skipped");
inviter.userList.push(name); // it's likely that this person didn't join linkedin in the meantime, so we'll ignore them
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else {
console.log("added");
inviter.userList.push(name);
button.click();
}
};
inviter.arrayContains = function(item)
{
return (inviter.userList.indexOf(item) > -1);
};
inviter.usersJson = {};
inviter.loadResult = function()
{
var retrievedObject = localStorage.getItem('inviterList');
var temp = JSON.stringify(retrievedObject);
inviter.userList = JSON.parse(temp);
};
inviter.saveResult = function()
{
inviter.usersJson = JSON.stringify(inviter.userList);
localStorage.setItem('inviterList', inviter.usersJson);
};
setInterval(function () { inviter.invite(); }, 5000);
`
When I try executing this, I get the following error:
VM288:49 Uncaught TypeError: Cannot read property 'children' of undefined
at hasRole (<anonymous>:49:71)
at Object.inviter.handleRepeat (<anonymous>:66:11)
at Object.inviter.invite (<anonymous>:30:69)
at <anonymous>:108:35
Any ideas as to how to fix it?
Here is the page where I'm trying to display content. It's showing up blank. My application is a single page application, so most of the code is in the index.html file
verbPractice.html
<div>
<h1>Practice verbs here</h1>
<div class="row" ng-repeat="sentence in listOfSentences">
<div class="col-xs-12">
<p>{{sentence.first}} {{sentence.second}} {{sentence.third}}</p>
</div>
</div>
</div>
This page is linked to from another page called verbSelect.html. Here is the relevant code from that page
<div class="btn btn-primary" ui-sref="app.verbPractice" ng-click="storeInfo(); generateSentences()">Submit</div>
Both the above pages are under the same controller called verbController:
(function() {
'use strict';
angular.module('arabicApp')
.controller('verbController', ['$scope', 'verbFactory', 'pronounFactory', 'attachedFactory', function($scope, verbFactory, pronounFactory, attachedFactory){
//Gets verbs from server
$scope.verbArray = verbFactory.getVerbs().query(
function(response) {
$scope.verbArray = response;
}
);
//Gets pronouns from server
$scope.pronouns = pronounFactory.getPronouns().query(
function(response) {
$scope.pronouns = response;
}
);
$scope.attached = attachedFactory.getAttached().query(
function(response) {
$scope.attached = response;
}
);
//Stores the array of selected verbs
$scope.selectedVerbs = [];
$scope.numSelectedVerbs = 0;
//Searches theArray for name and returns its index. If not found, returns -1
$scope.searchArray = function(theArray, name) {
for (var i = 0; i < theArray.length; i++) {
if (theArray[i].name === name) {
return i;
}
}
return -1;
};
//Adds verbs to selected list
$scope.addToSelected = function(theVerb) {
var num = $scope.searchArray($scope.selectedVerbs, theVerb.name);
var divToChange = document.getElementById("verbSelect_"+theVerb.name);
if (num > -1) { //Found. Remeove it from selectedVerbs
$scope.selectedVerbs.splice(num, 1);
divToChange.className = divToChange.className.replace( /(?:^|\s)listItemActive(?!\S)/g , '' );
$scope.numSelectedVerbs = $scope.numSelectedVerbs - 1;
} else { //Not found. Add it in
$scope.selectedVerbs.push(theVerb);
divToChange.className += " listItemActive";
$scope.numSelectedVerbs = $scope.numSelectedVerbs + 1;
}
};
//Stores how many practice questions the user wants
$scope.howMany = 0;
//Stores what tense of verbs the user wants
$scope.verbTense = "Both";
//Stores what form the user wants
$scope.verbVoice = "Both";
//Include commands?
$scope.includeCommands = false;
//Sentense that will be generated
$scope.listOfSentences = [];
$scope.generateSentence = function(isCommand, theTense, theVoice) {
var sent = {"first": "", "second": "", "third": ""};
var attachedPicker = Math.floor(Math.random()*14);
var attachedToUse = $scope.attached[attachedPicker].attached;
var pronounPicker = Math.floor(Math.random()*14);
var pronounToUse = $scope.pronouns[pronounPicker].pronoun;
sent.first = pronounToUse;
var verbPicker = Math.floor(Math.random()*$scope.numSelectedVerbs);
var verbToUse = $scope.selectedVerbs[verbPicker][theTense][pronounToUse];
if (isCommand === true) {
sent.second = verbToUse;
} else {
if (theVoice === "Passive") {
if (theTense === "Past") { sent.second = "were"; }
else { sent.second = "are"; }
sent.third = verbToUse;
} else {
sent.second = verbToUse;
sent.third = attachedToUse;
}
}
return sent;
};
$scope.storeInfo = function() {
localStorage.setItem("howMany", $scope.howMany);
localStorage.setItem("verbTense", $scope.verbTense);
localStorage.setItem("verbVoice", $scope.verbVoice);
localStorage.setItem("includeCommands", $scope.includeCommands);
};
$scope.getStoredInfo = function() {
$scope.howMany = localStorage.getItem("howMany");
$scope.verbTense = localStorage.getItem("verbTense");
$scope.verbVoice = localStorage.getItem("verbVoice");
$scope.includeCommands = localStorage.getItem("includeCommands");
};
//Generates sentences using the variables from verbSelect
$scope.generateSentences = function() {
$scope.getStoredInfo();
var tensePicker;
var voicePicker;
var doCommand;
var rand;
for (var i = 0; i < $scope.howMany; i++) {
//Picks the verb tense
if ($scope.verbTense === "Both") {
rand = Math.floor(Math.random());
if (rand === 0) { tensePicker = "Past"; }
else { tensePicker = "Present"; }
} else {
tensePicker = $scope.verbTense;
}
//Picks the verb voice
if ($scope.verbVoice === "Both") {
rand = Math.floor(Math.random());
if (rand === 0) { voicePicker = "Active"; }
else { voicePicker = "Passive"; }
} else {
voicePicker = $scope.verbVoice;
}
//If the voice is passive, use past tense
if ($scope.verbVoice === "Passive") { tensePicker = "Past"; }
//Determines if the sentence will be a command sentence or not
if ($scope.includeCommands === true) {
rand = Math.floor(Math.random() * 6);
if (rand === 0) { doCommand = true; }
else { doCommand = false; }
} else {
doCommand = false;
}
var sentence = $scope.generateSentence(doCommand, tensePicker, voicePicker);
$scope.listOfSentences.push(sentence);
}
console.log($scope.listOfSentences);
};
}])
;
})();
The variables: howMany, verbTense, verbVoice, isCommand, are set on this verbSelect.html page using ng-model. Both the verbSelect.html page and verbPractice.html page are under the same controller.
Everything seems to be working fine. At the end of my generateSentences() function, I output $scope.listOfSentences to the log, and it shows up without any problems, the array is being populated just fine. However, in my verbPractice.html page, nothing is showing up except the <h1> heading. For some reason, even though the $scope.listOfSentences array is populated, ng-repeat doesn't seem to be looping. Does anyone have any idea why?
Sorry for the long post
Thanks for taking the time to read and answer this question!
I have a result table like this (left table)
I want it to become like (right table)
In my previous question here,
#Clayton has already provide answer how to do it in php laravel (grouped in front end)
$data = [];
foreach ($result as $row) {
if (!isset($data[ $row['nama_customer'] ])) {
$data[ $row['nama_customer'] ] = [];
}
$data[ $row['nama_customer'] ][] = $row;
}
var_dump($data);
but for some reason now I need to make it in ajax
I already try something like this
$.post('myurl', {id:id} , function(result) {
var data = []; var idcustomer;
for (x in result) {
idcustomer = result[x]['id_customer'];
if(typeof( data[idcustomer] ) != "undefined" && data[idcustomer] !== null)
data[idCustomer] = [];
data[idCustomer][] = data[x];
}
console.log(data);
});
I think I already solved isset function with that code
but when I find 2 dimensional array I get confused
can someone give me an idea of how to do it in ajax
#Solved
function groupedTable() {
var seen = []; var a = 0;
$('#mytable td:first-child').each(function()
{
var $this = $(this);
var index = $this.index();
var txt = $this.text();
if (seen[index] === txt)
{
$($this.parent().prev().children()[index]).attr('rowspan', a);
$this.hide();
}
else {
seen[index] = txt;
a = countLoop(txt, $this);
}
});
}
function countLoop(txt) {
var span = 0;
$('#mytable td:first-child').each(function()
{
$this = $(this);
var txt1 = $this.text();
if (txt1 == txt)
span++;
});
return span;
}
<script>
$(document).ready(function() {
function MergeCommonRows(table, columnIndexToMerge) {
previous = null;
cellToExtend = null;
table.find("td:nth-child(" + columnIndexToMerge + ")").each(function() {
jthis = $(this);
content = jthis.text() if (previous == content) {
jthis.remove();
if (cellToExtend.attr("rowspan") == undefined) {
cellToExtend.attr("rowspan", 2);
} else {
currentrowspan = parseInt(cellToExtend.attr("rowspan"));
cellToExtend.attr("rowspan", currentrowspan + 1);
}
} else {
previous = content;
cellToExtend = jthis;
}
});
};
MergeCommonRows($("#aTable"), 1);
}
</script>
We can achieve by jquery. refer the below url and call the MergeCommonRows function inside body tag it will work
function MergeCommonRows(table, columnIndexToMerge){ previous = null; cellToExtend = null; table.find("td:nth-child("+columnIndexToMerge+")").each(function(){ jthis = $(this); content = jthis.text() if(previous == content){ jthis.remove(); if(cellToExtend.attr("rowspan") == undefined){ cellToExtend.attr("rowspan", 2); } else{ currentrowspan = parseInt(cellToExtend.attr("rowspan")); cellToExtend.attr("rowspan", currentrowspan+1); } } else{ previous = content; cellToExtend = jthis; } }); };
I have a sample code:
function getKeyword() {
var instance = this;
var googlePattern = /(www\.google\..*)/;
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var p in params) {
var kv = params[p].split("=");
result[kv[0]] = kv[1];
}
return result;
};
this.googleKeywords = function(params){
var query = params["q"];
var pattern = /"(.*?)"|(\w+)/g;
return decodeURIComponent(query).replace(/\+/g, " ").match(pattern);
};
this.parseReferrer = function(){
var result = [];
var pathAndParams = document.referrer.split("?");
if(pathAndParams.length == 2) {
var path = pathAndParams[0];
var params = this.params(pathAndParams[1]);
if(path.search(googlePattern) > 0) {
result = this.googleKeywords(params);
}
}
return result;
};
return this.parseReferrer();
}
And then:
<script type="text/javascript">
if (document.referrer && document.referrer != "") {
if (document.referrer.search(/google\.*/i) != -1){
var keyword = getKeyword();
alert(keyword);
} else {
alert('Not search from google');
}
} else {
alert('Not referrer');
}
</script>
Ex: when i search with keyword is "iphone 5", result not show alert("iphone 5") ? How to fix it ?
The JavaScript for in construct loops over more than just the entries in the array. If you want to use for in you need to make sure that you're only processing the actual parameters. This is easiest accomplished by checking for hasOwnProperty:
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var p in params) {
if (params.hasOwnProperty(p))
{
var kv = params[p].split("=");
result[kv[0]] = kv[1];
}
}
return result;
};
Alternatively you can use a regular for loop over the array:
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var i=0; i < params.length; i++) {
var kv = params[i].split("=");
result[kv[0]] = kv[1];
}
return result;
};