Need an Array Output from javascript function - javascript

Chech this fiddle
for all the running code i am using
i have an array i=[10,20,30,40,50,60,70]
and i m getting output as
70:checkbox(checked value 70)
.
I need all the array to be displayed along with its checkboxes,so that i can check whatever number i want and retrieve the checked ID
desired output:
70:checkbox(checked value 70)
60:checkbox(checked value 60)
50:checkbox(checked value 50)
40:checkbox(checked value 40)
30:checkbox(checked value 30)
20:checkbox(checked value 20)
10:checkbox(checked value 10)
Code for above Fiddle is here:
JS
var i=[10,20,30,40,50,60,70];
//$("#add").click(function(){
$(document).ready(function(){
// alert("ff");
var newrow=$('#services .headings').clone().removeClass('headings');
for(var k=0;k<i.length;k++)
{
var disp = {
names: i[k],
checks: i[k]
}
func.call(row,disp);
}
func(newrow,disp)
.insertAfter('#services tr.headings')
.show();
});
function func(row,disp)
{
row.find('.servicenames').text(disp.names);
row.find('.servicecheck').data('href',disp.checks);
return row;
}
$("#services").on("click", ".servicecheck",function(){
alert($(this).data('href'));
});
html
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<table id="services">
<tr class="headings" style="display:none">
<td><span class="servicenames"> service names here</span></td>
<td><span class="servicecheck" data-href=""><input type="checkbox" id="servicecheck" name="servicecheck"> </td>
</tr>
</table>

in your jsfiddle you have next code
....
var newrow=$('#services .headings').clone().removeClass('headings');
for(var k=0;k<i.length;k++)
{
var disp = {
names: i[k],
checks: i[k]
}
}
func(newrow,disp).insertAfter('#services tr.headings').show();
....
function func(row,disp)
{
row.find('.servicenames').text(disp.names);
row.find('.servicecheck').data('href',disp.checks);
i+=1;//this you try change global array, this string need remove
return row;
}
inside for loop you have only declaration disp, so you call func only once, also you once create new row. for solve this you must change your code like this
....
for(var k=0;k<i.length;k++)
{
var newrow=$('#services .headings').clone().removeClass('headings');
var disp = {
names: i[k],
checks: i[k]
}
func(newrow,disp).insertAfter('#services tr.headings').show();
}
....
function func(row,disp)
{
row.find('.servicenames').text(disp.names);
row.find('.servicecheck').data('href',disp.checks);
return row;
}

Try this,
var i=[10,20,30,40,50,60,70];
//$("#add").click(function(){
$(document).ready(function(){
// alert("ff");
var newrow=$('#services .headings').clone().removeClass('headings').css("display","block");
for(var k=0;k<i.length;k++)
{
var disp = {
names: i[k],
checks: i[k]
}
$('#services tbody').append(func(newrow,disp).html());
}
});
function func(row,disp)
{
row.find('.servicenames').text(disp.names);
row.find('.servicecheck').data('href',disp.checks);
return row;
}
$("#services").on("click", ".servicecheck",function(){
alert($(this).data('href'));
});
Fiddle
Hope it helps

Related

How to add a task in javascript function?

I have a HTML/JS code as shown below in which on click of Execute button, I want to display:
[{"detail":"Hello World"},{"detail":"Great News"}]
Currently, on clicking Execute button I am getting the following:
[{"detail":""},{"detail":""}]
I am wondering what changes I need to make in the JS code below so that on click of a Execute button, I am able to display:
[{"detail":"Hello World"},{"detail":"Great News"}]
HTML:
<input type="submit" onClick="runCode()" value="Execute" >
<div id="console-log">
</div>
Javascript:
$(document).ready(function() {
})
function runCode(){
var td=new Todo()
td.addTask("Hello World")
td.addTask("Great News")
td.printList()
}
class Todo{
constructor(name) {
this.todolist = [];
this.task={
'detail':''
}
}
addToList(newobj)
{
this.todolist.push(newobj)
}
addTask(taskDetail){
this.task.detail=taskDetail
this.todolist.push(this.task)
this.task.detail='' //clear data for next step
}
printList()
{
var consoleLine = "<p class=\"console-line\"></p>";
var text= JSON.stringify(this.todolist)
$("#console-log").append($(consoleLine).html(text));
//alert(this.todolist)
}
}
Push an object created just from the argument into the todolist property:
addTask(detail) {
this.todolist.push({ detail });
}
The this.task property only makes things more confusing, I'd recommend avoiding it.
function runCode() {
var td = new Todo()
td.addTask("Hello World")
td.addTask("Great News")
td.printList()
}
class Todo {
constructor(name) {
this.todolist = [];
}
addTask(detail) {
this.todolist.push({ detail });
}
printList() {
var consoleLine = "<p class=\"console-line\"></p>";
var text = JSON.stringify(this.todolist)
$("#console-log").append($(consoleLine).html(text))
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="submit" onClick="runCode()" value="Execute">
<div id="console-log">
</div>
It would also be trivial to remove the dependency on the big jQuery library if you wanted, it's not accomplishing anything useful. Also, it'd be good practice to use addEventListener instead of an inline handler:
document.querySelector('input').addEventListener('click', () => {
var td = new Todo()
td.addTask("Hello World")
td.addTask("Great News")
td.printList()
});
class Todo {
constructor(name) {
this.todolist = [];
}
addTask(detail) {
this.todolist.push({ detail });
}
printList() {
document.querySelector('code').appendChild(document.createElement('p'))
.textContent = JSON.stringify(this.todolist);
}
}
<input type="submit" value="Execute">
<code>
</code>

How to add values of an array dynamically

I have an array with list of values like the following
[
{
"name":"x",
"type":"deposit",
"deposit_amount":100
}
{
"name":"x",
"type":"withdraw",
"withdraw_amount":10
}
{
"name":"y",
"type":"deposit",
"deposit_amount":20
}
{
"name":"y",
"type":"withdraw",
"withdraw_amount":20
}
]
I need to add "deposit_amount" of objects having type as "deposit" and "withdraw_amount" of objects having type as "withdraw".
I have tried using ng-init using ng-repeat
<th ng-show="$last" ng-init="obj.total.deposit_amount = obj.total.deposit_amount + data.deposit_amount">Amount Collected : {{obj.total.deposit_amount}}</th>
<th ng-show="$last" ng-init="obj.total.withdraw_amount = obj.total.withdraw_amount + data.withdraw_amount">Amount Withdrawn :{{obj.total.withdraw_amount}}</th>
When I use this I got the expected one,but each time I click on search the total values get updating.
Any help would be Appreciated.Thanks
Handle that with javascript like this or something.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.data = [{"name":"x","type":"deposit","deposit_amount":100},
{"name":"x", "type":"withdraw", "withdraw_amount":10},
{"name":"y", "type":"deposit", "deposit_amount":20},
{"name":"y", "type":"withdraw", "withdraw_amount":20}
];
$scope.totalDeposit = 0;
$scope.totalWithdraw = 0;
angular.forEach($scope.data, function(obj) {
if(obj.type == 'deposit') {
$scope.totalDeposit += obj.deposit_amount;
}
else if(obj.type == 'withdraw') {
$scope.totalWithdraw += obj.withdraw_amount;
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div>Amount Collected : {{totalDeposit}}</div>
<div>Amount Withdrawn : {{totalWithdraw}}</div>
</div>
var x={}; x.test='xyz'; console.log(x);
--> obj.total.deposit_amount = 'x'

Is it possible to select element by attribute value only?

I need to find all elements in a page by attribute value only (ignoring the key) using jquery.
Is there a way to do this easily?
Currently, I am just iterating on all elements in the page, on every property etc..
You can use $.expr, Element.attributes, Array.prototype.some()
$.expr[":"].attrValue = function(el, idx, selector) {
return [].some.call(el.attributes, function(attr) {
return attr.value === selector[selector.length - 1]
})
};
// filter element having attribute with `value` set to `"abc"`
$(":attrValue(abc)").css("color", "blue");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div title="abc">abc</div>
<div title="def">def</div>
<div title="ghi">ghi</div>
<div title="jkl">jkl</div>
Use brackets []
var ElementsWithAttributeKeyTest = $('[attributeKey="Test"]');
Or pass an object with the attribute name and value as parameter to this function:
var getElemsByAttribute = function(obj) {
if (obj) {
if (obj.attributeKey && obj.attributeValue) {
return $('[' + obj.attributeKey + '="' + obj.attributeValue + '"]');
}
}
}
var attrObj = {
attributeKey: 'data-color',
attributeValue: 'red'
}
getElemsByAttribute(attrObj).css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span data-color="red">Red</span>
<span data-color="red">Red</span>
<span data-color="green">Green</span>
<span data-color="blue">Blue</span>
<span data-color="red">Red</span>
<span data-color="green">Green</span>
If you want to search all attributes values you can use this small plugin:
$.fn.search_by_attr_value = function(regex) {
return this.filter(function() {
var found = false;
$.each(this.attributes, function() {
if (this.specified && this.value.match(regex)) {
found = true;
return false;
}
});
return found;
});
};
and you can use it like this:
$('*').search_by_attr_value(/^some value$/);
Based on this answer
You could define new function take as parameter the value you want to filter with (e.g get_elements_by_value(filter)), then inside this function parse all the elements of the page using $('*').each(), after that parse the attributes of every element el of those elements using attribute attributes like below :
$.each(el.attributes, function(){ })
Then inside the each loop you could make your condition and push the matched values with the passed filter inside matched[] that should be returned.
Check working example below, hope this helps.
function get_elements_by_value(filter){
var matched=[];
$('*').each(function(index,el) {
$.each(el.attributes, function() {
if( this.value===filter )
matched.push(el);
})
})
return $(matched);
}
get_elements_by_value('my_value').css('background-color','green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div title="my_value">AA</div>
<div title="def">BB</div>
<input type='text' name='my_value' value='CC'/>
<p class='my_value'>DD</p>
<span title="test">EE</span>

how can call the scope function on ng-title attribute in angular.js

This is my html code
<td ng-title="tileOfAbsent(this.attendance.absent)" ng-
style="IsAbsOrPres(this.attendance.absent)" style="color: red">
{{attendance.absent}}</td>
This is controller
$scope.tileOfAbsent = function (value) {
var title1= "Absent";
var title2= "Present";
if (value == "AA") {
return title1;
}
else {
return title2;
}
}
$scope.IsAbsOrPres = function (value) {
var style1 = { color: "#F41212" };
var style2 = { color: "#178908" };
if (value == "AA") {
return style1;
}
else {
return style2;
}
}
Problem is tileOfAbsent function does not executed(I have checked with using break point). But the IsAbsOrPres function is executed as expected .
Why ng-title does not call the function?
I got it by using title instead of ng-title
like, title="{{tileOfAbsent(this.attendance.absent)}}"
this is my full working code
<td title="{{tileOfAbsent(this.attendance.absent)}}" ng-style="IsAbsOrPres
(this.attendance.absent)" style="color: red">{{attendance.absent}}</td>
You can use ng-attr-title instead of ng-title. In this case is mandatory write the method between double curly braces like "{{ ... }}".
ng-attr-title="{{ tileOfAbsent(this.attendance.absent) }}"

CasperJS querySelectorAll + map.call

html file
<table id="tbl_proxy_list">
...........
<tr>
......
<td align="left">
<time class="icon icon-check">1 min</time>
</td>
<td align="left">
<div class="progress-bar" data-value="75" title="4625"></div>
</td>
</tr>
</table>
ip.js file
casper.start('http://www.proxynova.com/proxy-server-list/', function() {
var info_text = this.evaluate(function() {
var nodes = document.querySelectorAll('table[id="tbl_proxy_list"] tr');
return [].map.call(nodes, function(node) {
//return node.innerText;
return node;
});
});
var tr_data = info_text.map(function(str) {
var elements = str;
var data = {
ip : elements,
port : elements[1],
lastcheck : elements[2],
speed : elements[3], // <== value is 75..
};
return data;
});
utils.dump(tr_data);
});
casper.run();
return node.innerText is only text.
ip is a text value
port is a text value
lastcheck is a text value
speed is not a text value (data-value="75")
I want to import data-value="75" (speed value is 75).
I do not know what to do.
========================================
It's work.. good. thank you Artjom.
but tr_data echo error.
first, you code modify..
return {
"ip": tr.children[0].innerText.trim(),
"port": tr.children[1].innerText.trim(),
"lastcheck": tr.children[2].innerText.trim(),
"speed": tr.children[3].children[0].getAttribute("data-value")
};
and echo..
//this.echo(tr_data.length);
for(var ii=0; ii<tr_data.length; ii++)
{
this.echo(tr_data[ii]['ip']);
}
at run, blow error..
TypeError: 'null' is not an object (evaluating 'tr_data.length'); what is problem?
I need your help.. thanks.
You cannot pass DOM elements from the page context (inside evaluate callback).
From the docs:
Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.
Returning an array of DOM elements will result in an array of as many undefined values. That means you need to map everything inside the page context and then return the resulting array. You also need only one map.
var tr_data = this.evaluate(function() {
var nodes = document.querySelectorAll('table[id="tbl_proxy_list"] tbody tr');
return Array.prototype.map.call(nodes, function(tr, i) {
if (tr.children.length != 6) {
return null; // skip ads
}
return {
ip: tr.children[0].innerText.trim(),
port: tr.children[1].innerText.trim(),
lastcheck: tr.children[2].innerText.trim(),
speed: tr.children[3].children[0].getAttribute("data-value")
};
}).filter(function(data){
return data !== null; // filter the null out
});;
});
You also might want to trim the excess white space.

Categories