Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
hello please take a look at my code below
var vsize; //global variable
function veg7() {
vsize = 7;
}
function veg10() {
vsize = 10;
}
function getCBP() {
if (vsize == 7) {
alert(vsize);
} else {
alert(vsize);
}
}
<input type="button" onclick="getCBP()" value="getCBP()">
<div class="main-menu">
<ul style="padding-left:13px; position:relative;top:41px;margin-bottom:0px;">
<li>
7" Veg
</li>
<li>
10" Veg
</li>
<li>
7" Non Veg
</li>
<li>
10" Non Veg
</li>
<li>
Pizaxx
</li>
<li>
Side Orders
</li>
</ul>
</div>
if any event access the function veg7() or function veg10() (it is dynamic) and changes the value of vsize accordingly then why am i getting vsize as undefined.
please help me..i need the value of vsize in getCBP().
It is undefined, but declared.
You are executing your function before assigning a value to your variable vsize.
you should declare var vsize = 0 (or any value), or run one of your veg functions before running getCBP.
Try var vsize = -1;
If you now see -1 instead of undefined, that means your functions are never called.
Note: I'm using -1 because that's easier to spot as an "error" than 0.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So the task is -
Load your page with URL containing #tags=green,pink,white at the end
Write a Javascript that displays the tags from the URL in the list, where each tag is displayed as a separate list item for example, if you have #tags=green,pink,white in the URL, the list will be displayed with 3 items
I'm trying to do this on React,
and I do so,
const [ulText, setUlText] = useState(['#green', '#pink', '#white'])
<ul className='navbar-nav'>
<li className='nav-item'>
<NavLink className='nav-link' to={ulText[0]}>
First
</NavLink>
</li>
<li className='nav-item'>
<NavLink className='nav-link' to={ulText[1]}>
Second
</NavLink>
</li>
<li className='nav-item'>
<NavLink className='nav-link' to={ulText[2]}>
Three
</NavLink>
</li>
</ul>
where the output is
const [ulText, setUlText] = useState(['green', 'pink', 'white'])
<ul className='list__ul'>
{ulText.map((item, index) => (
<li key={index.toString()} id={item}>
{item}
</li>
))}
</ul>
but maybe I don't quite understand the meaning of the task
You can get the tags from the URL with location.hash which will give you the string "#tags=green,pink,white".
Then you can remove "#tags=" with substr(6) (6 being the length of #tags=) and turn the rest into an array with split(',').
const hash = location.hash;
const colors = hash.substr(6).split(',');
console.log(colors);
// colors = ["green", "pink", "white"]
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
I tried using jsfiddle, it works properly there, but for whatever reason, the file didn't work when i run it on chrome. i also have other code concurrently (specifically form validation) but they are working fine, and there are no clashing var and function too. I know that i should just use other simpler way but unfortunate this is part of the requirement to use array in the dropdown
function makeAnchor() {
var div = document.createElement('div');
var options = ['ENCLOSED SPACE SANITISATION', 'EVENT HYGIENE MANAGEMENT', 'WIDE AREA SANITISATION', 'OBJECT DISINFECTION'];
for (var i = 0; i < options.length; i++) {
// Create the list item:
var a = document.createElement('a');
var ok = options[i]
a.href = "./service" + (i + 1) + ".html"
a.appendChild(document.createTextNode(ok));
div.appendChild(a);
}
return div;
}
document.getElementById('dropsc').appendChild(makeAnchor());
<!-- Nav Bar -->
<nav class="sticky-top">
<ul>
<li class="dropdown font-josefin">
<a class="dropbtn">SERVICES</a>
<div id="dropsc" class="dropdown-content">
<!-- ENCLOSED SPACE SANITISATION
EVENT HYGIENE MANAGEMENT
WIDE AREA SANITISATION
OBJECT DISINFECTION -->
</div>
</li>
<li class="font-josefin">ABOUT ME</li>
<li class="font-josefin">ENQUIRY</li>
<li class="font-josefin">ENHANCEMENTS</li>
<li class="font-josefin">DISCLAIMER</li>
</ul>
</nav>
document.getElementById('dropsc').appendChild(makeAnchor().cloneNode(true));
Try this
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
$("#yl").click(function(){updateYear("sub")});
$("#yr").click(function(){updateYear("add")});
$("#ml").click(function(){updateMonth("sub")});
$("#mr").click(function(){updateMonth("add")});
$("#dl").click(function(){updateDay("sub")});
$("#dr").click(function(){updateDay("add")});
Is there a way to write this code cleaner, smarter without repetitions?
If you change your elements a bit, you could do something like this:
<button id='yr' data-type='update' data-date-part='year' data-date-action='add'>
Then you create an update function that starts off like this:
function update() {
const el = $(this);
const datePart = el.attr('data-date-part');
const dateAction = el.attr('data-date-action');
// do your logic to update the date based on what part and action
}
Then your click handler just needs to be:
$('button[data-type="update"]').click(update);
I forgot to mention, that newer versions of jquery will also let you just use the .data() function instead of spelling out the full data- attribute
The code is fine as it stands as it is very clear what is happening.
If you really want to do it differently, then you should probably also modify your function(s) and look into HTML attributes. It all depends what you are actually doing in those functions.
If for instance you want the user to enter a date just by pressing add/sub buttons, then the basics could look like this:
$('.change-value').click(updateDatePart);
function updateDatePart() {
// Read current date
var dateParts = $.map($(this).closest(".dateinput").find(".part-value"), function (span) {
return +$(span).text();
});
// Which part of the date needs incrementing/decrementing?
var part = $(this).closest('.part').index();
// Apply change to that part
dateParts[part] += $(this).data("inc");
// Create a date with this
var date = new Date(dateParts[0], dateParts[1]-1, dateParts[2]);
// Get the parts for the new date (which may have resolved some overflow)
dateParts = [date.getFullYear(), date.getMonth()+1, date.getDate()];
// Output the result
$('.part-value').each(function (i, elem) {
$(elem).text(dateParts[i]);
});
}
.change-value { font-size: 50% }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="dateinput">
<span class="part">
<button class="change-value" data-inc="-1">-</button>
<span class="part-value">2017</span>
<button class="change-value" data-inc="1">+</button>
</span>-
<span class="part">
<button class="change-value" data-inc="-1">-</button>
<span class="part-value">12</span>
<button class="change-value" data-inc="1">+</button>
</span>-
<span class="part">
<button class="change-value" data-inc="-1">-</button>
<span class="part-value">24</span>
<button class="change-value" data-inc="1">+</button>
</span>
</span>
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
i'm wrote some todo list app, to understand how to be more expert.
what i'm try to understand:
my problem is when user click on task to edit, because it passed by reference so if user edit task, it will change directly the task object.
(i attached my code here).
my questions:
1) in my code i wrote one way to fix it, by clone object every time.
it good practice ? if no how you recommend me to fix it?
2) because i do not want my code only work, i want to be more expert.
if you think my thinking and planning of this code is bad? how you write this app? ( i talk here only about functional, add, edit, list of task)
thanks for help :)
link to plunker: https://plnkr.co/edit/CA99iiydbD4TWaGtJZZf?p=preview
code:
HTML
<html ng-app="todos">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="main">
<ul>
<li ng-repeat="task in todosBL.tasks" ng-click="editMode.edit(task)">{{ task.content}}</li>
</ul>
<input type="text" ng-model="task">
<input type="button" value="add task" ng-click="add(task)">
<!--//for edit-->
<div>
<input type="text" ng-model="editMode.task.content">
<input type="button" value="save task" ng-click="editMode.save(editMode.task)">
</div>
</div>
</body>
</html>
SCRIPT:
(function() {
var Task = (function() {
var counter = 0;
return function(content, isDone) {
this.id = counter++;
this.content = content;
this.isDone = isDone || false;
}
}());
var app = angular.module('todos',[])
.service('todosBL', function() {
this.tasks = [];
this.add = function(content) {
this.tasks.push(new Task(content));
}
this.update = function(editedTask) {
var i = this.tasks.findIndex(function(task){
return task.id === editedTask.id
});
this.tasks[i] = editedTask;
}
})
.controller('main', function($scope, todosBL) {
$scope.todosBL = todosBL;
$scope.add = function(task) {
todosBL.add(task);
$scope.task = null;
}
$scope.editMode = {
task: {},
edit: function(task) {
this.task = task;
//BECAUSE I PASS TASK BY REFERNCE WHEN USER EDIT TASK IT CHANGE TASK DIRECTLY ,
// IF I CLONE OBJECT EVERY TIME, IT FIX BY REFERENCE PROBLEM.
// MY QUESTION IF HAVE OTHER WAY TO SLOVE THIS. MABY OTHER WAY TO THINK ABOUT APP LIKE THIS.
// for(key in task) {
// this.task[key] = task[key];
// }
},
save: function(task) {
todosBL.update(task);
this.task = {};
}
};
});
}());
I think that your controller is over complicated. The service should implement some BL like data verification and posting it to the server and/or local storage but not searching for index, it does silly things now!
In order to satisfy all your requirements one just needs a controller:
app.controller('MainCtrl', function($scope) {
$scope.tasks = [];
$scope.add = function(content){
$scope.tasks.push(new Task(content));
$scope.content = null;
}
$scope.edit = function(task){
$scope.currentlyEditing = task;
$scope.editText = task.content;
}
$scope.save= function(){
$scope.currentlyEditing.content = $scope.editText;
$scope.editText = null;
$scope.currentlyEditing = null;
mySuperSeriousService.postToServer.then(result=> {
alert('Success');
})
}
});
and template like this:
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="task in tasks" ng-click="edit(task)">{{ task.content}}</li>
</ul>
<input type="text" ng-model="content">
<button ng-click="add(content)">Add Task</button>
<!--//for edit-->
<div>
<input type="text" ng-model="editText" ng-disabled="!currentlyEditing">
<button ng-click="save()">Save</button>
</div>
</body>
So it's 2 times shorter. Here's the plunker (https://plnkr.co/edit/nN8kd5ErSDsBu6Exm1YO)
my problem is when user click on task to edit, because it passed by reference so if user edit task, it will change directly the task object. (i attached my code here).
For solving this problem, you should make a copy of your model and change it (in edit function): this.task = angular.copy(task);
in my code i wrote one way to fix it, by clone object every time. it good practice ? if no how you recommend me to fix it?
As I said, making copy is much more logical !
because i do not want my code only work, i want to be more expert. if you think my thinking and planning of this code is bad? how you write this app? ( i talk here only about functional, add, edit, list of task)
1) I don't know why you are using an array of objects ? your tasks are just strings ! so it can be better if you use an array of strings. then you won't have the struggle with sth like editMode.task.content, you just use editMode.task !
2) Don't work with ids . cause when you add the 'Deleting Task' feature, you'll got problems ...
3) What does Task() function do ? ( In this case, you don't need sth like this)
4) ...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a web page that receives the following JSON from a server
{"d":[
{"__type":"Service1.Operators:#MobileWCFService","operators":"ACCOUNTING"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"AHOFFMAN"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"AMONROY"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"APATENTAS "},
{"__type":"Service1.Operators:#MobileWCFService","operators":"WRAMOS "}
]}
From the array d in this data I need to create checkboxes, each corresponding to an element of the array, defined by the operators property of each element. I need these checkboxes to be dynamically generated with JavaScript/jQuery once the data is received. How can this be done?
Is this what you want?
var input=//get input json
var data=input.d;
for(var x in data){
var type=data[x].__type;
var ops=data[x].operators;
var id="checkbox-"+ops+Math.floor(Math.random()*100000);
$("<div><label></label><input/></div>")
.children().eq(1)
.attr({
"type":"checkbox",
"name":"insert here",
"data-type":type,
"data-operators":ops,
"id":id,
"class": "your checkbox class here"
})
.click(function(){ /////////////////////////// updated here
if($(this).prop("checked")){
// do action for checked event
} else {
// do action for unchecked event
}
})
.parent()
.children().eq(0)
.attr("for", id)
.text("whatever label you want")
.parent()
.appendTo($("container you want to put them in"));
}
You should loop over JSON result and create checkbox element and add it to div. Use jquery .each() to loop JSON. Try this:
var json = {"d":[
{"__type":"Service1.Operators:#MobileWCFService","operators":"ACCOUNTING"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"AHOFFMAN"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"AMONROY"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"APATENTAS "},
{"__type":"Service1.Operators:#MobileWCFService","operators":"WRAMOS "}
]};
$(document).ready(function() {
var $grouplist = $('#checkboxes');
$.each(json.d, function() {
$('<label>'+this.operators+': </label><input type=checkbox
value='+this.operators+'/>').appendTo($grouplist);
});
});
DEMO