I wasn't sure how to search for the answer to this on here or on Google, so I figured I would just ask. I'm an affiliate for TicketNetwork and they have a plugin generator (you can see it here if you want: http://www.ticketnetwork.com/affiliates/plug-in-maker.aspx) where you can put in a keyword and it generates a list of events based on that keyword (basically like doing a search on their site). Here's an example of the code you'd put on your site:
<script type="text/javascript">
function TN_SetWidgetOptions() {
TN_Widget.newWindow = true;
TN_Widget.trackingParams = '';
TN_Widget.custLink = true;
TN_Widget.tixUrl = 'http://www.ticketnetwork.com/tix/';
TN_Widget.trackingLink = 'http://www.tkqlhce.com/click-12345-10793961?url=';
TN_Widget.CreateCustomUrl = function(row) {
return "http://www.tkqlhce.com/click-12345-10793961?url=" + escape(this.tixUrl + row[7] + "-tickets-"+ row[6] + ".aspx");
};
}
</script>
<script type="text/javascript" src="http://site_01504_011.ticketsoftware.net/widget3_c.aspx?kwds=austin%20city%20limits%20festival&style=9&mxrslts=10"></script>
My problem is, if a keyword returns no results, instead of giving some sort of "no results found", it just shows blank space. Is there some way I can manipulate this code to make it show something other than blank space if there are no results, or is that something TicketNetwork would have to add into their plugin generator?
I think you can do this in JQuery (Pseudocode)
if ($.trim($("#DIV").text()) === '') {
document.write('No Results Returned');
}
Just replace the DIV with the ID of the html tags surrounding your output. This is untested so you might have to fiddle with it a little bit but I think this is something that would work.
Also, don't forget you'll have to include the JQuery files to get this to work also.
EDIT: You can use $('#DIVID').text('No results Returned'); to point your code to wherever you want to display the text by JQuery selector.
First I just want to say thanks to the people who tidied up my question for me.
With the help of Bryant's answer I devised this solution:
<script type="text/javascript">
var nodelist = document.getElementsByTagName("TD").length;
if (nodelist == 0){
document.write("No tickets for this event are currently available.")
}
</script>
When there are no results, all it creates is an empty table with no cells. So, I just check if any table cells exist, and if there are none, it writes my message. I tried like a hundred different things before I landed on this, but I'm glad it works! :)
Related
I am at starting web dev, already using html/css.
For a little project, I had a look at JavaScript. (My goal is that when people click a button, the site will show a random sentence that will be taken from a google sheet cell.)
Could you tell me please if it is even possible? If so, please share some ideas that I will explore. If not, please give me some alternative ideas... Thanks so much.
Have a good day!
-LeganV9
This is possible using Google Apps Script!
I have a working demo here, with the source being here. I dare you to get the jackpot. :D
In order to make this, you can go to https://script.new. Now, in code.gs put this:
function doGet() {
return HtmlService.createTemplateFromFile("index").evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getVals(){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1IDbhQhaImcQB-4j-iByajwAkvxkutptcPMhMTxNrPtU/edit#gid=0");//Put your URL here
var sheet = ss.getSheetByName("Sheet1");//Put your sheet name here
var AMOUNT_OF_SENTENCES = sheet.getMaxRows().toString().replace(".0","");//You can replace this with a number eg 20
var range = sheet.getRange(1, 1,AMOUNT_OF_SENTENCES);
var values = range.getValues();
var newValues = [];
for(var i = 1; i<values.length;i++){
if(values[i][0] === "" || values[i][0] === " "){
}else{
newValues.push(values[i][0]);
}
}
return {valuesVar: newValues };
}
After that, create a new HTML file called "index" and put this in it:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>
The results are: <span id = "results">Loading...</span>
</h1>
<button id = "yourIdHere">Click me!!</button>
<script>
var yourDataList;
function onSuccess(data) {
yourDataList= data.valuesVar;
}
google.script.run.withSuccessHandler(onSuccess).getVals();
var myBtn = document.querySelector("#yourIdHere"); //Declare button, replace yourIdHere with your ID
var randomNum = 0; //Decclre random number
function getRandom() { //Declare your function
randomNum = parseInt(Math.random() * yourDataList.length); //Get random number between 0 and the length of your datalist
return yourDataList[randomNum]; //Return your value
}
myBtn.addEventListener("click", function() { //Bind a listener to the button
document.querySelector("#results").innerText = getRandom(); //Do whatever you want to with the random value
});
document.querySelector("#results").innerText = getRandom();//Change from loading...
</script>
</body>
</html>
Welcome to the world of web development! Hope your project is a success.
It should definitely be possible, since Google Sheets offers an API which has read/write functionality (https://developers.google.com/sheets/api).
You could even later extend this so people can submit their own sentences, given that writing to a Google Sheet is also possible with this API.
However, since you're starting out, consider treating this as an iterative process. You don't have to publish your first version, but just to prevent overwhelming yourself, you might want to set small milestones along the way - each adding more functionality. For example:
Create an array of random sentences (you could, for example, start with using this to keep it simple: https://github.com/JamesFT/Database-Quotes-JSON).
Select and log a random sentence to the console (console.log()) each time the script is executed.
Transfer the random sentence to render in HTML and allow a new sentence to be generated each time a button is pressed.
Move your sentences into a Google Sheet and begin exploring the API.
This way, you achieve something in a much shorter space of time, while working towards your end goal. It's a good way to keep motivated and make things more manageable.
Best of luck!
I want to start out by saying that I do not know Java Script. I work for a travel agency and I work in content creation & design. I have done minor script work using Sabre Scribe in Eclipse. If people have recommendations on where to go to learn the basics of this, that'd be great. Edit: This is using program Adobe Captivate Execute Javascript Function.
Anyways, my goal right now is change a key-press into a symbol. I need to turn "'" into "‡". I am more than happy to put in the time to learn and research this, but all the research I have done has not got me any closer to finding a solution. I have, however, learned how to create an alert when that key is pressed, I just can't seem to get that key to type a different one.
Long story short, I would appreciate some resources or help in the matter.
Adobe Captivate seems to have its own unique flavour of Javascript. After reading the common-js-interface page, something like this may work - can you try it as a test (I don't have the program)??
window.cpAPIEventEmitter.addEventListener("CPAPI_VARIABLEVALUECHANGED", function(e) {
var value = window.cpAPIInterface.getVariableValue("myTextBox");
value += 'testing';
window.cpAPIInterface.setVariableValue('myTextBox', value);
}, 'myTextBox');
Of course change all places it says 'myTextBox' to the name of your text field variable.
If this works then I can probably figure out some code to change the ' to that symbol.
This response is invalid for reasons stated in the comments. I'm leaving this up for the comment history. It could very well be of help to others as well.
You'll want to do a search and replace (using regex) on the input's onkeyup. You can then swap out the appropriate values using a hash, and replace the value back into the input.
Here's some code I wrote around a week ago that does just that:
// note: this needs to be escaped *here*
const hotSwapVals = {
':music:': '♫',
':rocket:': '🚀',
':sat:': '🛰',
':satellite:': '🛰'
};
// swap out text with emoji on an input
function hotSwap(obj) {
if(obj.constructor !== HTMLInputElement)
throw 'Object must be HTMLInputElement';
// must be escaped prior, otherwise errors will occur
const regex = new RegExp(Object.keys(hotSwapVals).join('|'), 'g');
const val = obj.value.replace(regex, key => hotSwapVals[key]);
if(obj.value != val) // prevents moving cursor to end if not needed
obj.value = val;
}
This is then bound to the object by passing the input object as a parameter.
This code will change the ' character to the symbol when you press the key...
<!doctype html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body>
<input id="textField" type="text"></input>
<script>
jQuery(document).ready(function($) {
$('#textField').on('keydown', function(e) {
//console.log(e.keyCode); // Will tell you the code for the key pressed.
if (e.keyCode == 222) {
e.target.value += '‡'; // Add the symbol
e.preventDefault(); // Stop the single quote from being added.
}
});
});
</script>
</body>
</html>
iam trying to hide all rows in table except for the ones with <td> containing same text as user selected from dropdown. thought it should be easy but im struggling with it for long now...i tried something like this:
$(document).ready(function() {
$('select[name=selectName]').change(function() {
$("td").each(function(index, paragraph) {
$td = $(paragraph);
if ($td.html() === $('select[name=selectName]').val()) {
//hide the matched row rather than remove it
$(not(this)).parent("tr:first").hide();
}
});
$('select[name="selectName"]').on('change', function() {
$("tr").show();
});
});
});
but it didnt work so i tried this:
$(document).ready(function(){
$('select[name=selectedName]').change(function() {
$('tr').filter(function () {
return $(this).find('td').filter(function () {
return $(this).text().indexOf('$('select[name=select2]').val()') == -1;
}).length;
}).$(this).parent("tr:first").hide();
});
});
but didnt work as well...this is how i build my dropdown:
$query = "SELECT user_name FROM users";
$result = mysql_query($query); ?>
<select name="selectedName" id="userSelected">
<option value="" disabled selected>user name</option>
<?php while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { ?>
<option value="<?php echo $line['user_name'];?>">
<?php echo $line['user_name'];?>
</option>
<?php } ?>
</select>
any help to lead for solution?? thanks
Knowing you have not posted enough info for us to help you finish, I can at least point out an error in your code.
You should use the F12 tools so you can spot these errors.
Depending on the browser you are using, the Console area of the F12 tools will show ReferenceError: not is not defined.
Clicking the line number will show that the error is
$(not(this)).parent("tr:first").hide();
(unless there's another error before this in which case you need to fix that first)
So not(this) is not valid syntax. If you don't understand why, please post a separate question, more specific, and we would be happy to explain the meaning of these things.
Are you looking to filter to rows containing the text in a given value, or rows whose entire html is equal to the text in the given value? This is an important difference, an I assume you mean the former since that's the wording you use, but your code seems to do the latter.
Also keep in mind that $(element).html() will give you a very different string from $(element).text(). In the following example, $('.bunny').text() will include the string "I am a bunny" but $('.bunny').html() won't.
<div class="bunny">
Hi! I am a <strong>bunny</strong>.
</div>
If you're looking to filter rows by their text contents, I'd do something like the following:
var search_term = $(this).val();
var matching_rows $('tr').filter(function(){
var this_row_text = $(this).text();
// Standardize whitespace (in case it's useful)
this_row_text = this_row_text.replace(/\s+/g, " ");
if (this_row_text.indexOf(search_term) > -1) {
return true;
} else {
return false;
}
});
matching_rows.addClass("highlighted"); // or whatever
Note that I created lots of variables at each step; even if the var is only used once, this can lead to much more descriptive and readable code that's less of a pain for you to troubleshoot and maintain later on. When my JS code is misbehaving, the first thing I do is I go in and break out variables like this. The resulting JS is about twice as many lines, but I almost always spot and fix multiple issues just by going through that process. Jquery makes it too easy to write overly dense code. ;-)
On a more general note, I think I spot a number of Jquery errors in your code snippets above. We could point those out individually for you, but that's not what SO is here for; focus on breaking your problem down into smaller and smaller pieces so you can tackle those errors one at a time, rather than being stumped by several of them acting up at once. For example, if you're trying to troubleshoot the filtering behavior, open up Chrome's dev tools and just start playing with filters in the JS console. Then once you're confident with that, you can copy & paste back into your IDE and be confident that "OK, I know these 3 lines are working as intended".
First set up some constants for the bits of the page that aren't going to change (this will help speed up your code):
var select = $('#userSelected');
var trs = $('tr');
Then in your change function you just need to test the text in each row against the value and toggle whether the the row is hidden or not:
$(document).ready(function(){
var select = $('#userSelected');
var trs = $('tr');
select.change( function() {
var value = select.val();
trs.each(function(){
var isShown = $( 'td:first', this ).text() == value;
$(this).toggle( isShown );
});
});
});
JSFIDDLE
Basically I am trying to search the page when it loads for the string "Quantity in Stock:7". If it cannot find this string it will replace the [img id="product_photo" src="bleh.gif"] with the image listed in the source below. If the string is found then I do not want the image to bereplaced.
What we want is that if the quantity of a product on our site does not equal 7 we want to display a deposit taken image instead of the product image. However the code below is not working for me. I am not asking for a magic solution (however that would be nice) even a push in the right direction would be greatly appreciated.
Below is the code I have come up with and I am a javascript novice trying to learn as I go so forgive me if the code is not right. I have pieced this together using my limited knowledge and assistance from other stack overflow articles.
<script type="text/javascript">
window.onload = function() {
var foundin = $('*:contains("Quantity in Stock:7")');
If (foundin != "Quantity in Stock:7") {
$("#product_photo").attr("src", "/v/vspfiles/templates/Raceweek/images/dt_image.gif");
}
};
</script>
Thanks in advance,
Camo
$('*:contains("Quantity in Stock:7")') does not return a string. It returns a jQuery set of matched elements.
In your case, if it found your string, then the matched set will not be empty. So we'll check the length of the matched set:
$(function() {
var foundin = $('body:contains("Quantity in Stock:7")');
if ( ! foundin.length ) {
$("#product_photo").attr("src", "/v/vspfiles/templates/Raceweek/images/dt_image.gif");
}
});
Note: you should not have to run that contains on the whole page! Run it only on the element that holds the quantity.
So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!