I'm new to jQuery and I am trying to understand a bit of code to be able to apply a similar concept in my coursework.
$(function(){
$(".search").keyup(function() {
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\') {
}
});
})(jQuery);
What is the dataString variable trying to do?
There are quite a few things that seem "off" with this snippet of code, which I'll address below.
What is this code doing?
It looks like some basic functionality that might be used to build a search querystring that is passed onto some AJAX request that will search for something on the server.
Basically, you'll want to build a string that looks like search={your-search-term}, which when posted to the server, the search term {your-search-term} can be easily identified and used to search.
Noted Code Issues
As mentioned, there are a few issues that you might want to consider changing:
The Use of Escaped Quotes (i.e. \') - You really don't need to escape these as they aren't present within an existing string. Since you are just building a string, simply replace them with a normal ' instead. Without knowing more about your complete scenario, it's difficult to advise further on this.
Checking String Length - Your existing code once again checks if the searchId is an empty string, however you may want to consider checking the length to see if it actually empty via searchId.length != 0, you could also trim this as well (i.e. searchId.trim().length != 0).
Consider A Delay (Optional) - At present, your current code will be executed every time a key is pressed, which can be good (or bad) depending on your needs. If you are going to be hitting the server, you may consider adding a delay to your code to ensure the user has stopped typing before hitting the server.
You can see some of these changes implemented below in the annotated code snippet:
// This is a startup function that will execute when everything is loaded
$(function () {
// When a keyup event is triggered in your "search" element...
$(".search").keyup(function () {
// Grab the contents of the search box
var searchId = $(this).val();
// Build a data string (i.e. string=searchTerm), you didn't previously need the
// escaping slashes
var dataString = 'search=' + searchId;
// Now check if actually have a search term (you may prefer to check the length
// to ensure it is actually empty)
if(searchId.length != 0) {
// There is a search, so do something here
}
}
}
Related
Hope someone can help with this. I have come across an issue with the application im testing. The developers are using vue.js library and there are a couple of fields which reformat the entered test. So for example if you enter phone number, the field will automatically enter the spaces and hyphens where its needed. This is also the same with the date of birth field where it automatically enters the slashes if the user does not.
So the issue I have is that using both 'setValue()' or 'sendKeys()' are entering the text too fast and the cursor in the field sometimes cannot keep up and the text entered sometimes appears in the incorrect order. For example, if I try to enter '123456789'. Some times it ends up as '132456798' (or any other combination). This cannot be produced manually and sometimes the test does pass. But its flakey.
What I wanted to do was to write a custom command to do something where it enters the string but in a slower manner. For this I need to have control of how fast I want the text to be entered. So I was thinking of something like this where I can pass in a selector and the text and then it will enter one character at a time with a 200 millisecond pause in between each character. Something like this:
let i = 0;
const speed = 200; // type speed in milliseconds
exports.command = function customSetValue(selector, txt) {
console.log(selector);
console.log(txt);
if (i < txt.length) {
this.execute(function () {
document.getElementsByName(selector).innerHTML += txt.charAt(i);
i++;
setTimeout(customSetValue, speed);
}, [selector, txt]);
}
return this;
};
When running document.getElementsByName(selector) in browser console I get a match on the required element. But it is not entering any text. Also note that I added a console.log in there and I was actually expecting this to log out 14 times but it only logged once. So itss as if my if condition is false
I checked my if condition and it should be true. So not sure why its not reiterating the function. Any help is much appreciated.
Also if it helps. I am using the .execute() command to inject javascript which is referenced here: https://nightwatchjs.org/api/execute.html
And the idea on this type writer is based on this: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_typewriter
We ended up taking a different approach much simpler. Wanted to post here in case anyone else ever needs something similar
exports.command = function customSetValue(selector, txt) {
txt.split('').forEach(char => {
this.setValue(selector, char);
this.pause(200); // type speed in milliseconds
});
return this;
};
I am trying to implement auto-complete using CodeMirror show-hint addon, specifically with sql-hint. I want it auto-complete as I type.
What I am doing right now is,
codemirror_editor.on("change", function(instance) {
CodeMirror.commands.autocomplete(instance);
});
But the problem is, it completes words before I even type a single letter for a word. For example after space, it gives a long list of all possible tokens. I want it to show up only if some characters are typed. Can someone please help with that?
Before firing the autocomplete command, check whether the cursor is actually after 'some' (whatever 'some' means) letter characters. Also, do nothing when instance.state.completionActive is true, since that means there's already a completion popup open. Finally, you probably want to listen for the "inputRead" event instead of "change", so that you don't trigger when a change is made to the document in a way that didn't involve the user typing.
This is how I solved this, after Marijn's answer.
codemirror_editor.on("inputRead", function(instance) {
if (instance.state.completionActive) {
return;
}
var cur = instance.getCursor();
var token = instance.getTokenAt(cur);
var string = '';
if (token.string.match(/^[.`\w#]\w*$/)) {
string = token.string;
}
if (string.length > 0) {
CodeMirror.commands.autocomplete(instance);
}
});
This may be specific to SQL.
I am answering my own question to share the actual solution for the question.
Update: A Solution below!
I'm fairly new to website development but I've been tasked with developing e2e (end-to-end) tests for a developing website that uses AngularJS. As a result I've been looking down the road of using AngularJS's karma-run ngScenario testing wrapper.
Anyway, just getting started I want to make sure that a simple hyperlink's text matches part of its href address. There isn't need to know the structure of this code snippet, but these are thumbnails for user profiles, and you can click the thumbnail object completely (the first 'a') or you can click a link displaying their name (the second 'a').
There dozens of these on a page.
Here is what a part of the page looks like loaded with a user "PurplePenguin".
<div class="thumbnail__section">
<a href="/profile/PurplePenguin">
<div class="thumbnail__bottom">
<div class="thumbnail__rating ng-binding"> </div>
<div class="thumbnail__info">
<div class="thumbnail__name">
<a class="ng-binding" href="/profile/PurplePenguin">PurplePenguin</a>
</div>
[...]
Essentially I want a test that will take the text of the second 'a' element and check it against the href attribute: "assert that href '/profile/PurplePenguin' equals '/profile/' + 'PurplePenguin'"
This is what I've made just wanting to test the first thumbnail's 'a', (in my time writing "PurplePengiun" is the first user every time so I could hard code it).
it('should have the performer\'s name match the link', function() {
// "eq(n)" gets the nth instance of the element;
// "> a:eq(0)" grabs its first child a
var nameElement = element('.thumbnail__name:eq(0) > a:eq(0)');
// These work and pass
expect(nameElement.text()).toBe('PurplePenguin');
expect(nameElement.attr('href')).toBe('/profile/PurplePenguin');
// This does not
var textString = nameElement.text(); // textString == "[object Object]"
expect(nameElement.attr('href')).toBe('/profile/' + textString);
This gets returned:
expect element '.thumbnail__name:eq(0) > a:eq(0)' get attr 'href' toEqual "/profile/[object Object]"
expected "/profile/[object Object]" but was "/profile/PurplePenguin"
So I've figured out how to find the particular element on the page I need, but trying to manipulate the text of a simple 'a' element only gives me [object Object].
Some things I've tried with my basic knowledge of JS:
nameElement.text().toString(), nameElement.text().value(), nameElement[0].text()
Trying things other than text()
nameElement.html() and nameElement.val()
They too return [object Object] when trying to use them as strings.
It seems that looking at the values and attributes of these elements only works when using the very specific API functions like .toBe or .toEqual, but I want to assert that a specifically formatted string is made.
Thank you for any help!
Solution
Thanks for that bit of insight Andyrooger, I had actually taken a stab at the query function before posting my question but gave up on it too quick. Your explanation gave me the idea to start looking deeper into the samples that have been posted in the official docs. I ended up taking a hint from a Adi Roiban's post to another Angular e2e writer's question talking about query, done() messages, and promises. This ended up leading me to my eventual solution.
So I've made myself a solution and in the spirit of cooperation made a set of examples for others to learn by. There are four examples, the first two are just getting the text and the href and comparing them against hard-coded values. The third one uses indexOf to do dirt-simple comparisons. The fourth one shows how you can make your own more specific pass/fail conditions (more than what Jasmine provides with its matchers).
Number 1: User name text vs hard coded value
it('should have the user\'s name be \'PurplePenguin\'', function() {
var textPromise = element('.thumbnail__name:eq(0) > a:eq(0)').query(function (nameElement, done) {
var text = nameElement.text(); // Can finally access this guy!
// The first param null indicates a nominal execution, the second param is a return of sorts
done(null, text);
});
// Passes
expect(textPromise).toBe('PurplePenguin')
});
Number 2: Profile href value vs hard coded value
it('should have the user\'s link be \'/profile/PurplePenguin\'', function() {
var textPromise = element('.thumbnail__name:eq(0) > a:eq(0)').query(function (nameElement, done) {
var href = nameElement.attr('href');
// The first param null indicates a nominal execution, the second param is a return of sorts
done(null, href);
});
// Passes
expect(textPromise).toBe('/profile/PurplePenguin')
});
Number 3: Simple string comparison
it('should have the user\'s name match the link', function() {
var textPromise = element('.thumbnail__name:eq(0) > a:eq(0)').query(function (nameElement, done) {
var text = nameElement.text();
var href = nameElement.attr('href');
// The first param null indicates a clean pass, the second param is a return of sorts
done(null, href.indexOf(text)); // indexOf returns -1 if text is _not_ a sub-string of href
});
expect(textPromise).toBeGreaterThan(-1);
// In the case of failure reports this in the console (if using Karma):
// expect element .thumbnail__name:eq(0) > a:eq(0) custom query toBeGreaterThan -1
// expected -1 but was -1
// In the runner.html page for the test simply reports this useless/misleading log:
// expected -1 but was -1
});
Number 4: More detailed string comparison doing it your own way plus a better error message
it('should have the user\'s name match the link', function() {
var nameStringPromise = element('.thumbnail__name:eq(0) > a:eq(0)').query(function (nameElement, done) {
var text = nameElement.text();
var href = nameElement.attr('href');
var message;
if (href.indexOf(text) == -1)
message = 'Did not find "' + text + '" in "' + href + '"';
done(message, href.indexOf(text));
});
expect(nameStringPromise);
// An expect() with no Jasmine matcher means that it only uses the done message to determine
// a pass or fail for the test. So I wrote that if my conditions weren't met it would print
// an informative message in the case of failure
// Example failure output with a broken url generator:
// Did not find "PurplePenguin" in "/profile/"
});
I'm struggling to find references to back this up or explain a little more nicely, other than these docs which don't have much info. Therefore this answer is mainly from memory of reading the relevant code.
When you write a test in ngScenario, you are not writing a series of immediate actions as you would do in a unit test. What you are actually doing queuing up a list of commands to execute when the test starts.
Methods that looks like normal jQuery functions, such as text() or attr() are actually part of ngScenario's DSL and return future objects (meaning they will at some point execute and have the result of the call you wanted.)
expect() already knows this so waits for the result before comparing to your expected value. The code underneath, in your example, is reading directly and immediately so will see the future object.
If you do need to read the element in this way I suggest looking at the query function which should allow it. On the other hand if you need to just check the formatting of the string you can use toMatch which has been implemented in ngScenario too.
I'm really new to Javascript and I'm having some trouble understanding how to get the following to work. My goal is to have a certain Javascript action execute when a page loads and a variable added to the end of the URL would trigger which Javascript action to execute. The URL of the page that I'm looking to implement this on is http://www.morgantoolandsupply.com/catalog.php. Each of the "+expand" buttons, which are Javascript driven, drop-down a certain area of the page. Ultimately, I would like to be able to create a URL that would automatically drop-down a certain category when the page loads. Could anybody explain to me the process to do this? Thanks in advance for any help!
You have to parse the URL somewhat "manually" since the parameters in the url aren't automatically passed to javascript, like they are in server-side scripting (via $_GET in PHP, for instance)
One way is to the use the URL fragment identifier, i.e. the "#something" bit that can go at the end. This is probably the neatest way of doing it, since the fragment isn't sent to the server, so it won't be confused with any other parameters
// window.location.hash is the fragment i.e. "#foo" in "example.com/page?blah=blah#foo"
if( window.location.hash ) {
// do something with the value of window.location.hash. First, to get rid of the "#"
// at the beginning, do this;
var value = window.location.hash.replace(/^#/,'');
// then, if for example value is "1", you can call
toggle2('toggle' + value , 'displayText' + value);
}
The URL "http://www.morgantoolandsupply.com/catalog.php#1" would thus automatically expand the "toggle1" element.
Alternatively, you can use a normal GET parameter (i.e. "?foo=bar")
var parameter = window.location.search.match(/\bexpand=([^&]+)/i);
if( parameter && parameter[1]) {
// do something with parameter[1], which is the value of the "expand" parameter
// I.e. if parameter[1] is "1", you could call
toggle2('toggle' + parameter[1] , 'displayText' + parameter[1]);
}
window.location.search contains the parameters, i.e. everything from the question mark to the end or to the URL fragment. If given the URL "example.com/page.php?expand=foo", the parameter[1] would equal "foo". So the URL "http://www.morgantoolandsupply.com/catalog.php?expand=1" would expand the "toggle1" element.
I'd perhaps go for something more descriptive than just a number in the URL, like, say use the title of the dropdown instead (so "#abrasives" or "expand=abrasives" instead of "#1" or "expand=1"), but that would require a little tweaking of your existing page, so leave that for later
You've already got the function to call: toggle2(), which takes two parameters that happen to be identical for all categories except for a number at the end. So create a URL that includes that number: http://www.morgantoolandsupply.com/catalog.php#cat=4
Then find that number in location.hash using a regular expression. This one is robust enough to handle multiple url parameters, should you decide to use them in the future: /[\#&]cat=(\d+)/. But, if you expect to never add anything else to the url, you could use a very simple one like /(\d+)/.
Once you've got the number, it's a simple matter of using that number to create your two parameters and calling toggle2().
This should work:
window.onload = function() {
if (/[\#&]cat=(\d+)/.test(location.hash)) {
var cat = parseInt(RegExp.$1);
if (cat > 0 && cat < 13) {
toggle2("toggle"+cat, "displayText"+cat);
}
}
}
Not a complete answer ("Give a man a fish" and all that), but you can start with something along these lines:
// entire URL
var fullURL = window.location.href;
// search string (from "?" onwards in, e.g., "www.test.com?something=123")
var queryString = window.location.search;
if (queryString.indexOf("someParameter") != -1) {
// do something
}
More info on window.location is available from the Mozilla Developer Network.
Having said that, given that you're talking about a PHP page why don't you use some server-side PHP to achieve the same result?
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!