Angular Select: build string - html

I want to build a url where parts of the url string are dynamic build with a select box.
The watch is only called at startup:
$scope.$watch('url', function () {
$scope.buildUrl();
}, true);
Here is the fiddle:
http://jsfiddle.net/mkeuschn/wJGFm/
best regards

The $watch will only fire if the value being watched changes. In this case, it is better to watch dimension, since this is the selection that is changing. Then, you can re-assign the dimension part of the url and re-build.
Here is an updated fiddle.
JS:
$scope.buildUrl = function () {
$scope.url.dimension = $scope.dimension.value;
$scope.completeUrl = $scope.url.base + "dateFrom=" + $scope.url.from + "&dateTo=" + $scope.url.to + "&dimension=" + $scope.url.dimension;
};
$scope.$watch('dimension', function () {
$scope.buildUrl();
}, true);

Related

jQuery trigger click after changing url

I have a function that records clicks on a link with a data tag. The code hides a telephone number until the link has been clicked, then it reveals the number. The problem I'm having is I am unable to get that revealed number to fire without user interaction once it has loaded.
I had to prevent the default event for when the button is clicked for the first time as the url does not yet contain the real data and also I don't want the page to jump.
Once clicked the new link's html will change to, example: "☎ 0123456789"
and the href will change to, example: "tel:0123456789"
This data is obtained from JSON sent from AJAX PHP file.
After this I want to programatically click the URL but I can't seem to get it to fire and keep getting a console error message saying "Uncaught TypeError: event is undefined" ~ presumably to do with the event prevent default?
Info: there will be multiple phone numbers loaded via PHP so I need to access each one individually.
HTML for the link;
<a data-num='$number' class='telephone' href='#'>☎ Click to call</a>
JS code (jQuery 3.4.1);
$(document).on('click','.telephone',function(event) {
event.preventDefault(); // Prevent page jump
var num = $(this).data("num");
$.ajax({
url: "myserverfile.php",
method: "POST",
data: {num: num},
dataType: "json",
success: function(a) {
var b = (a[0]['status']); // True or false
var c = (a[0]['tel']); // Number or error
// If result found change URL and click it to call number
if (b == true) {
$('.telephone[data-num="' + num + '"]').html("☎ " + c); // Change link text
$('.telephone[data-num="' + num + '"]').attr("href", "tel:" + c); // Change link href
$('.telephone[data-num="' + num +'"]').click(); // Update: This causes a loop because it runs the code again. I need to hide the original a tag and create a new one then trigger it.
}
}
});
});
Any suggestions?
Calling the .click() method doesn't create an event. The event is created when the user actually clicks something. If you console.log(event) it'll be undefined when called by .click(), which is where you're getting the error from. To get around that you could
if (event) { event.preventDefault(); }
But then you're going to run into recursion since you're basically
$(document).on('click', '.telephone', function() { $('.telephone').click(); });
To get around that you could add something like a loaded class
$(document).on('click', '.telephone:not(.loaded)', function() {
$('.telephone[data-num="' + num +'"]')
.addClass('loaded')
.attr(...)
.html(...)
.click();
});
Also, you'll thank yourself later for using a little more descriptive variable names. And for those unaware, jquery is chainable.
Figured it out. I was creating a loop so the click wouldn't work so I hid the first link after the click and loaded a new hidden one. I used a different column value from the table for the data tag on this new link to avoid any possible conflicts.
Apart from the loop issue the major part I was missing was [0] before assigning .click.
Thanks for the suggestions along the way.
Working code below;
$(document).on('click', '.telephone', function(event) {
event.preventDefault();
var num = $(this).data("num");
$.ajax({
url: "myserverfile.php",
method: "POST",
data: {num: num},
dataType: "json",
success: function(a) {
var b = (a[0]['status']);
var c = (a[0]['id']);
var d = (a[0]['tel']);
if (b == true) {
$('.telephone[data-num="' + num + '"]').hide(200);
$(document).ready(function() {
$(".telephone-reveal");
$('.telephone-reveal[data-id="' + c + '"]').show(200);
$('.telephone-reveal[data-id="' + c + '"]').html("☎ " + d);
$('.telephone-reveal[data-id="' + c + '"]').attr("href", "tel:" + d);
$('.telephone-reveal[data-id="' + c + '"]')[0].click();
});
}
}
});
});

variable insert to a blink function

I'm new to HTML and ajax. I'm trying to insert a ip list from flask , to the ajax and trigger the js function to blink.
but somehow I can't find a way to insert the ip variable (response[i]) into the function value column in a right way.
it is to trigger the blink on the required ip tab in html.
function ajaxForm(){
// var form= new FormData(document.getElementById("myform2"));
var data = {"name":"John Doe"}
$.ajax({
url:"{{ url_for('Submit_form') }}",
type:"post",
contentType:'application/json',
data:JSON.stringify(data),
dataType: "json",
processData:false,
// async: false
success:function(response){
// alert(response)
if (response == "success")
{alert("Success !!!" );}
else {
for(i in response)
{
BLINK(response[i]);
}
}
},
// #time out 也进入 error
error:function(e){
// alert(e.)
alert("Failed submit form trigger!!!!");
}
})
}
<script type="text/javascript">
function BLINK(){
var t = null;
function blink() {
var obj = $('input[id="IP"][value=response[i]]') . <---- here
obj.addClass("blink-class");
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
At first, you shoul always provide the HTML code too :) because now we dont know if the issue is there.
So let's try to solve the problem blindly :)
if i see this correctly, you just go wrong on the element and make it even more complicated than it is since you're using jquery, because if u have an ID on your elem, check this out:
// change this:
var obj = $('input[id="IP"][value=response[i]]') . <---- here // .. is your problem :)
obj.addClass("blink-class");
// with the dot you add this obj, which is it self, on it self :) that cant work :)
// you can try:
var obj = $('input[value="' + response[i] + '"]') // with NO dot and no fixed ID!
obj.addClass("blink-class");
// or try this
var obj = $('#' + response[i]);
obj.addClass("blink-class");
// and put the IP into the ID attraktion of your input element.
Second Problem is you are using an undefined variable "ID":
blink(IP); // in your timeout function
but you didnt declare this var, so if i understand your code right then your response[i] should be the IP?
Your function should look like this:
function BLINK(IP) { // <-- here you need the ip as parameter for your: BLINK(response[i]) from ajax
var t = null;
function blink() {
var obj = $('#' + IP) // and put IP in the id from input
obj.addClass("blink-class")
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
try this, if its doesnt work please provide complete html and your css code too, also we could need an eventually error message from console, you can see that by pressing F12 in FireFox or Chrome and then switch to the console tab, press F5 then to reload the page and see errors, post it too please.
Or try out my jsfiddle for you:
https://jsfiddle.net/AIQIA/tjg659sr/17/
You have to remove dots from your IP and put it as id in your elem you wants get to blink, further you need to remove the dots from the response[i] or in your php code before, easy use $ip = preg_replace('/\./','',$ip);
Or use this to use only the complete IP in your input value, then you dont need to remove dots:
https://jsfiddle.net/AIQIA/tjg659sr/21/
greetz Toxi

Add html asynchronously

I want to add new html in page asynchronously like
$.each(programListAll, function (j, innerItem)
{
programHtml = '<div class="row"><ul>';
$("#programList").append(programHtml);
});
It should show user that html is adding asynchronously.
How can I achieve this?
You could have a little delay in adding the items, the code would look like this:
var $programHtml = $('<ul class="row"></ul>');
$('#programList').append($programHtml);
var delay = 1000;
$.each(programListAll, function (j, innerItem)
{
$programHtml.delay(j * delay).append('<li'> + innerItem + '</li>');
});

Where do I define context (JSON object) when creating a Handlebars.registerHelper in a Backbone View?

I do not know where to define the context (JSON object) in a Handlebars.registerHelper function in a Backbone View.
I am able to render my helper function data in the console when I access it through $.getJSON, but I cannot get the data from the helper function into my template:
var SurveyView = Backbone.View.extend({
template: Handlebars.compile(
'<ul>' +
'{{#each models}}<h3>{{attributes.name}}</h3><h4>{{attributes.question}}</h4>'+
'<li>{{#answerList info}} {{{answers}}}{{/answerList}}</li>{{/each}}' +
'</ul>' +
'<button type="button" class="btn btn-danger">Next</button>' +
),
helperOne: function() {
Handlebars.registerHelper('answerList', function(context, options) {
var output = "";
$.getJSON('questions', function(info) {
for (var i = 0; i<info.length; i++ ){
var infos = info[i];
for (key in infos.answers) {
if(infos.answers.hasOwnProperty(key)) {
output += '<li>' +
'">' + info[i].answers[key] +
'</li>';
console.log(output);
}
}
}
});
return output;
}); //end register
},
initialize: function() {
this.listenTo(this.collection, "reset", this.render);
},
render: function () {
this.helperOne();
this.$el.html(this.template(this.collection));
return this;
}
});
Trying to do an AJAX call inside a Handlebars helper isn't a very productive thing to do. The helper only knows about text: the helper returns a piece of text that will probably become a set of DOM nodes but there is no way for the helper to know what the DOM nodes are so it can't update anything on the page when the AJAX call returns from the server.
You need to turn your logic around:
Figure out what AJAX calls need to be made.
Perform the AJAX calls.
When all the AJAX calls have finished, collect up the data for the template and hand it to the compiled template function.
Add the template function's return value to the DOM.
In your case, you can get rid of helperOne completely. Then, presumably you'd have an Answer Backbone model and an AnswerList collection which contains Answers. Somewhere you'd do a fetch on the AnswerList and when that returns, you can update your view.

Repeatedly Grab DOM in Chrome Extension

I'm trying to teach myself how to write Chrome extensions and ran into a snag when I realized that my jQuery was breaking because it was getting information from the extension page itself and not the tab's current page like I had expected.
Quick summary, my sample extension will refresh the page every x seconds, look at the contents/DOM, and then do some stuff with it. The first and last parts are fine, but getting the DOM from the page that I'm on has proven very difficult, and the documentation hasn't been terribly helpful for me.
You can see the code that I have so far at these links:
Current manifest
Current js script
Current popup.html
If I want to have the ability to grab the DOM on each cycle of my setInterval call, what more needs to be done? I know that, for example, I'll need to have a content script. But do I also need to specify a background page in my manifest? Where do I need to call the content script within my extension? What's the easiest/best way to have it communicate with my current js file on each reload? Will my content script also be expecting me to use jQuery?
I know that these questions are basic and will seem trivial to me in retrospect, but they've really been a headache trying to explore completely on my own. Thanks in advance.
In order to access the web-pages DOM you'll need to programmatically inject some code into it (using chrome.tabs.executeScript()).
That said, although it is possible to grab the DOM as a string, pass it back to your popup, load it into a new element and look for what ever you want, this is a really bad approach (for various reasons).
The best option (in terms of efficiency and accuracy) is to do the processing in web-page itself and then pass just the results back to the popup. Note that in order to be able to inject code into a web-page, you have to include the corresponding host match pattern in your permissions property in manifest.
What I describe above can be achieved like this:
editorMarket.js
var refresherID = 0;
var currentID = 0;
$(document).ready(function(){
$('.start-button').click(function(){
oldGroupedHTML = null;
oldIndividualHTML = null;
chrome.tabs.query({ active: true }, function(tabs) {
if (tabs.length === 0) {
return;
}
currentID = tabs[0].id;
refresherID = setInterval(function() {
chrome.tabs.reload(currentID, { bypassCache: true }, function() {
chrome.tabs.executeScript(currentID, {
file: 'content.js',
runAt: 'document_idle',
allFrames: false
}, function(results) {
if (chrome.runtime.lastError) {
alert('ERROR:\n' + chrome.runtime.lastError.message);
return;
} else if (results.length === 0) {
alert('ERROR: No results !');
return;
}
var nIndyJobs = results[0].nIndyJobs;
var nGroupJobs = results[0].nGroupJobs;
$('.lt').text('Indy: ' + nIndyJobs + '; '
+ 'Grouped: ' + nGroupJobs);
});
});
}, 5000);
});
});
$('.stop-button').click(function(){
clearInterval(refresherID);
});
});
content.js:
(function() {
function getNumberOfIndividualJobs() {...}
function getNumberOfGroupedJobs() {...}
function comparator(grouped, individual) {
var IndyJobs = getNumberOfIndividualJobs();
var GroupJobs = getNumberOfGroupedJobs();
nIndyJobs = IndyJobs[1];
nGroupJobs = GroupJobs[1];
console.log(GroupJobs);
return {
nIndyJobs: nIndyJobs,
nGroupJobs: nGroupJobs
};
}
var currentGroupedHTML = $(".grouped_jobs").html();
var currentIndividualHTML = $(".individual_jobs").html();
var result = comparator(currentGroupedHTML, currentIndividualHTML);
return result;
})();