Dynamic dropdown form breaks when enabling last JS function - javascript

I'm desiging a dynamic dropdown form that will help my customers choose the right product for them and was looking to test the function to output the final results. When I add the JS function to take the info from the last dropdown and use it to build the results list the whole script seems to break. My console in Chrome spits out Uncaught SyntaxError: Unexpected string (pointing to the third to last line of the broken JS) although its nearly identical to my other functions except for some changed variables.
Basically, I use JS to pull info from dropdowns which sends that data using GET to a PHP script. The script then uses that data to query an SQL DB to dynamically build a list of options for the next dropdown. After the last dropdown of the form the JS would parse the PHP script to receive some data (a table eventually) and update a DIV with that data. This is where the script breaks. Adding that last JS function breaks the script while removing it keeps it working.
You can test the working script here and the broken script here.
Here's the working JS:
$(function(){
$("#type").change(function() {
var tval = document.getElementById('type').value;
$("#source").load(encodeURI("findbackend.php?type=" + tval));
});
$("#source").change(function() {
sval = document.getElementById('source').value;
$("#range").load(encodeURI("findbackend.php?source=" + sval));
});
$("#range").change(function() {
rval = document.getElementById('range').value;
$("#setpoint").load(encodeURI("findbackend.php?range=" + rval));
});
$("#setpoint").change(function() {
stval = document.getElementById('setpoint').value;
$("#dig_num").load(encodeURI("findbackend.php?range=" + rval + "&setpoint=" + stval));
});
});
And here's the broken JS:
$(function(){
$("#type").change(function() {
var tval = document.getElementById('type').value;
$("#source").load(encodeURI("findbackend.php?type=" + tval));
});
$("#source").change(function() {
sval = document.getElementById('source').value;
$("#range").load(encodeURI("findbackend.php?source=" + sval));
});
$("#range").change(function() {
rval = document.getElementById('range').value;
$("#setpoint").load(encodeURI("findbackend.php?range=" + rval));
});
$("#setpoint").change(function() {
stval = document.getElementById('setpoint').value;
$("#dig_num").load(encodeURI("findbackend.php?range=" + rval + "&setpoint=" + stval));
});
$("#dig_num").change(function() {
dnum = document.getElementById('dig_num').value;
$("#findresults").load(encodeURI("findbackend.php?range=" + rval + "&setpoint=" + stval "&dig_num=" + dnum));
});
});
I've looked it over a hundred times and can't figure out what's breaking the script.
If you'd like to see the PHP or anything just let me know.
Thanks in advance for any help.
Again, you can view the working script here and the broken script here.

You forgot to add a "+" sign after stval.
$("#findresults").load(encodeURI("findbackend.php?range=" + rval + "&setpoint=" + stval + "&dig_num=" + dnum));

Related

Cannot show TrustPilot HTML when inserted with JavaScript (jQuery)

If I added the TrustPilot html code directly on the HTML page, it works fine but I needed to insert it with jQuery. I see the HTML code when inserted but it's not displaying.
$(window).on('load', function () {
var el = $('#some-element');
el.html( trustPilotHtml() );
function trustPilotHtml() {
var str = "<div " +
"class='trustpilot-widget' " +
"data-locale='en-GB' " +
"data-template-id='123456' "+
"data-businessunit-id='123456' " +
"data-style-height='500px' " +
"data-style-width='100%' " +
"data-theme='light' " +
"data-stars='4,5' " +
"data-schema-type='Organization'>" +
"<a " +
"href='https://some-url.com' target='_blank'>Trustpilot</a> " +
"</div>";
return $(str);
}
});
Is the only way of getting the element to display properly is to directly inserted into the HTML without javascript?
No it's not the only way.
You should have a bootstrap script in your inside the HEAD part of your HTML (or close to it).
This script takes care of initializing all the widgets (TrustBoxes in Trustpilot lingo) that you have in your HTML.
Of cause that doesn't work if you are injecting the HTML dynmically, so it's also possible to call window.Trustpilot.loadFromElement(trustbox); yourself, when if you need to.
Here trustbox is a HTMLElement, you could get by using document.getElementById("some-element") or similar.
Reference: https://support.trustpilot.com/hc/articles/115011421468
The following worked for me on a product list page which returned filtered list via ajax
var element = document.getElementsByClassName("trustpilot-widget");
for(var i=0; i<element.length; i++) {
window.Trustpilot.loadFromElement(element[i]);
}
On the first page load all product reviews are displayed as expected, but if the page is updated via ajax call (using filters for example) the reviews are lost. Running the above code after ajax, reloads the reviews

Google Tag Manager DataLayer not allways Pushing

I have a Tag in tag manager that feeds me back the data of fields that have been showing as invalid when a user tries to submit a form but its missing or has invalid fields.
This is done using the following code:
// Get user Agent
var Uagent = navigator.userAgent;
// Validation Errors Check
document.getElementById("btnSubmit").onclick = function() {
errorLoop();
}
function errorLoop() {
var runner = document.getElementsByClassName("invalid"),
formEmail = document.getElementById('email').value,
dataL = [];
dataLayer.push({'formEmail' : formEmail});
if (runner) {
for (var i = 0; i < runner.length; i++) {
var errName = runner[i].getAttribute("name"),
errId = runner[i]
.getAttribute("id");
dataL.push("Field: " + errName + " - ID: " + errId);
} //End for
dataL.toString();
var vadout = dataL + " Device: " + Uagent;
console.log(dataL);
dataLayer.push({
'formEmail' : formEmail,
'validationError': vadout,
'event' : 'errorpush'
});
} //End if
} //End errorLoop
So whats basically happening here is on a submit we are checking the form to see if any of the fields have the class invalid & if it does then it add's the name & Id of the fields to an array then prints then prints the array into a data layer.
The tag itself is triggered using a custom event called errorpush.
The issue is that this works only about 80% of the time we still get alot of people get validation errors but the validation errors don't seem to make it to the datalayer and back to google analytics.
I'm considering adding a settimeout delay to the datalayer push which I will go away and try but wanted to see if anyone knows of anything right off the bat which could be causing this problem.
Your runner is declared as empty array if there are no elements with class name "invalid". But your if statement is only checking for declaration thus:
if(runner){
}
will always be true but there are no "invalid" elements. Consequently dataL.push("Field: " + errName + " - ID: " + errId);will never execute in your for loop but dataLayer.push will, and so you will get errorpush event without any errors.
To solve this, I would suggest to rewrite your if statement:
if(runner.length > 0){
}
I hope this solves your problem.

How to hard code text which are coming from javascript messages

Our application is been internationalized and being changed to different languages. For that reason we have to hard code all the messages. How can we do that for messages in javascript ?
This is how we are doing in html messages.
<span th:text="#{listTable.deletedFromTable}">deleted</span>
How do we hard code for javascript messages.(update the table)
$('#TableUpdate-notification').html('<div class="alert"><p>Update the Table.</p></div>');
You will need to put the messages in the DOM from the start, but without displaying them. Put these texts in span tags each with a unique id and the th:text attribute -- you could add them at the end of your document:
<span id="alertUpdateTable" th:text="#{listTable.updateTable}"
style="display:none">Update the Table.</span>
This will ensure that your internationalisation module will do its magic also on this element, and the text will be translated, even though it is not displayed.
Then at the moment you want to use that alert, get that hidden text and inject it where you need it:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + $('#alertUpdateTable').html() + '</p></div>');
You asked for another variant of this, where you currently have:
$successSpan.html(tableItemCount + " item was deleted from the table.", 2000);
You would then add this content again as a non-displayed span with a placeholder for the count:
<span id="alertTableItemDeleted" th:text="#{listTable.itemDeleted}"
style="display:none">{1} item(s) were deleted from the table.</span>
You should make sure that your translations also use the placeholder.
Then use it as follows, replacing the placeholder at run-time:
$successSpan.html($('#alertTableItemDeleted').html().replace('{1}', tableItemCount));
You could make a function to deal with the replacement of such placeholders:
function getMsg(id) {
var txt = $('#' + id).html();
for (var i = 1; i < arguments.length; i++) {
txt = txt.replace('{' + i + '}', arguments[i]);
}
return txt;
}
And then the two examples would be written as follows:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + getMsg('alertUpdateTable') + '</p></div>');
$successSpan.html(getMsg('alertTableItemDeleted', tableItemCount));

Having difficulty building a form summary with JS

Sorry for the noobish question but, I am trying to build a form summary that will populate a div (immediately) with all of the fields being used. Here is a small sample of the field: Fiddle
For some reason the JS is not working as I would expect it to, can anyone point out what I am doing wrong?
For example, I would like it to output: "AND name: john EXCEPT number 222".
I would also like to be able click on a result to remove it, and clear the field. Thank you
$(".allS").change(function () {
if ($(this).next('.textArea').not(':empty'))
// varible to hold string
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#text_here").text(str);
}).change();
$('.textArea').change(function(){
var $inputs = $('form#form :input[type="text"]'),
result = "";
$inputs.each(function(){
// access the individual input as jQuery object via $(this)
result += $(this).val()+"<br>";
});
// store result in some div
$('div#text_here').text(result);
}).change();
There were many mistakes in your code. I simplified it to a very short code that only does what's needed to get the output you requested. Here's the working fiddle.
$(".allS, .textArea").change(function () {
var str = '';
if ($('#name').val().length > 0 && $('#number').val().length > 0)
var str = $('#nameMod>option:selected').text() + ' name:' + $('#name').val() + ' ' + $('#numberMod>option:selected').text() + ' number ' + $('#number').val();
$("#text_here").html(str);
});
Basically, what this does is attach a change event handler to both classes (.alls, .textArea), and when the event is triggered, both input fields are tested for any content. If this test passes, a string is composed out of all the relevant values, and the div content is set. If the test failed (no content), the str variable contains an empty string and the div is cleared.
Just glancing at the code, the selector 'form#form :input[type="text"]' looks wrong. For starters, input is not a pseudoclass. Also, attribute matching shouldn't have the quotes.
This may or may not be what you want (I think it is, from looking at your html):
'form#form input[type=text]'
Also your <br>'s are not working because you called text(). call html() instead.

Fetching facebook likes count with jquery goes wrong

i have a little script which fetches the likes and tweets count about a url via jquery. Now it works great, but when a certain page has 0 like/shares, then jquery returns 'undefined' because the 'shares' part is not shown in the output.
$(document).ready(function() {
url = "http://awebsitehere.com/";
beforecounter = " <b>";
aftercounter = "</b>";
// Get Number of Facebook Shares
$.getJSON('http://graph.facebook.com/'+url+'&callback=?',
function(data) {
$('#facebook').append(beforecounter + data.shares + aftercounter);
});
// Get Number of Tweet Count
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url='+url+'&callback=?',
function(data) {
$('#twitter').append(beforecounter + data.count + aftercounter);
});
})
How would I have to edit this script to display 0 instead of undefined when facebook has got 0 shares/likes for a certain url?
try this:
$('#facebook').append(beforecounter + (data.shares || 0) + aftercounter);
and likewise for the twitter value.
At first you have to create a username of your page(see under your page name #username. Just click it...)
Then goto https://developers.facebook.com/tools/explorer/ and get an access token key
Then script something like that
function facebookLikesCount(access_token, pageusername)
{
var url = "https://graph.facebook.com/"+pageusername+"?fields=likes&access_token="+access_token+"";
$.getJSON(url,function(json){
alert(json.likes);
});
}
facebookLikesCount('your accesstoken', 'pageusername');
its work for me.

Categories

Resources