I'm showing hidden divs based on the contents of a query string parameter that's being parsed from another page, using indexof to check if a value is present - then displaying that value's corresponding div.
Query string: index.html?q1=bag1,bag2,bag3
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Then using indexOf to show divs based on the value:
if ((urlParams["q1"]).indexOf("bag1") >= 0) {
$(".content1").show();
} else
if ((urlParams["q1"]).indexOf("bag2") >= 0) {
$(".content2").show();
} else
if ((urlParams["q1"]).indexOf("bag3") >= 0) {
$(".content3").show();
}
However, it's only displaying the first div and not the second or third.
I know it'll be a simple solution - bit stuck on it. Any help appreciated!
You need to remove the else clauses, as the interpreter will stop after the first if is true. So your code should look like
if ((urlParams["q1"]).indexOf("bag1") >= 0) {
$(".content1").show();
}
if ((urlParams["q1"]).indexOf("bag2") >= 0) {
$(".content2").show();
}
if ((urlParams["q1"]).indexOf("bag3") >= 0) {
$(".content3").show();
}
I'd suggest using your bag1 etc values as IDs instead of classes to identify the separate content sections. If a class only identifies one element then you're doing it wrong.
You should then tag all of your content elements with the same class (e.g. content) so that you can .hide() on all of them before running .show on the ones that you want to remain visible. As written any elements that are already visible will remain visible when you pop state even if they weren't supposed to be.
Your parameter extracting code is OK, but having got your q1 value I would just do this:
var q1 = urlParams.q1;
if (q1 !== undefined) {
$('.content').hide(); // show nothing
q1.split(',').forEach(function(id) {
$('#' + id).show();
});
}
thereby removing all of the (broken) conditional logic.
Related
I am creating a live content editor for an element using textarea, but its output isn't like what the expected if the inputted value is symbol like > or < or mix up of those symbols and texts, instead of just texts, then it will not replacing instead of doubled it up.
Here is the Fiddle
And here is the jquery codes:
$("#changer").on("change keyup paste", function () {
// get current element
var thehtml = $("#tochange").html();
var thetext = $("#tochange").contents().filter(function () {
return this.nodeType === 3;
}).text().trim();
var thechange = $(this).val();
// if has element, then keep it, add text and put back
var thepurehtml = thehtml.replace(thetext, "");
var theoutput = thechange;
if ($.trim(thepurehtml) != '') {
var theoutput = thechange + thepurehtml;
}
$("#tochange").html("").html(theoutput);
return;
});
What's causing it and how to fix it up?
PS: I need to have the functionality of this line var theoutput = thechange + thepurehtml; because it is sometimes the edited element have html element other than just a blank or text node.
However i am going to delete this answer, As i don't have enough reputation to comment i am posting as answer.
So #SoursopTree, what you actually want to achieve?
What i found is when you enter < or > the line $.trim(thepurehtml) is returning empty string (null) and null!='', so the next statement var theoutput = thechange + thepurehtml; here thechange=> and thepurehtml=>. so you are getting two symbols instead of one.
You said you need to have the functionality of this line var theoutput = thechange + thepurehtml;
I'm trying to find if what the user typing in to an input field contain certain text - I've kinda got it works, but only working for an exact match as opposed to a partial match. If a user types anything before the text i'm matching, of course the code doesn't trigger.
What i need to do is check if the input contains #nyu.edu at all in the input field.
$('.email').keyup(function(){
if ($(".email").val() == "#nyu.edu") {
$("p.warning").css("visibility", "visible");
}
else if ($(".email").val() != "#nyu.edu") {
$("p.warning").css("visibility", "hidden");
}
});
Checking if a string contains a substring is pretty easily done by taking haystack.indexOf(needle) and checking against -1 (not found).
if ($(".email").val().indexOf("#nyu.edu") !== -1) {
// contains
} else {
// does not contain
}
There is a function in the ES6 draft which you may find more natural, called includes
You can add support for ES6's String.prototype.includes like this
if (!String.prototype.includes) {
String.prototype.includes = function (needle, pos) {
return this.indexOf(needle, pos || 0) !== -1;
};
}
"foobar".includes('foo'); // true
Working Ex:
http://codepen.io/anon/pen/XJKMjo
$('.email').keyup(function() {
var exp = /#nyu\.edu$/; // reg ex
var input = $(this).val(); // email input
var matches = exp.test(input); // boolean
// changes to hidden or visible
$("p.warning").css("visibility", (matches) ? "visible" : "hidden");
});
You can filter based on HTML elements' attribute contents with jQuery to either contain, start, or end with a string that you want. To match elements with an attribute that contain a string, you'd use [attr*="value"] in your jQuery selector, but I think that you want something where the end matches your string. Here's how that would work:
var elements = $(".email[value$='#nyu.edu']");
if(elements.length > 0) {
// Do something with the elements, such as removing an .error class
} else {
// Email doesn't end with #nyu.edu
}
Read more about the jQuery ends-with attribute selector or browse through other attribute selectors like this.
jsBin demo
var $warning = $("p.warning"); // P.S. make sure not to target a wrong .warning!
$('.email').on("input", function(){
$warning.toggle( /#nyu\.edu/ig.test(this.value) );
});
as I've mentioned .warning being a class can represent any first .warning occurrence. use rather some other selector like .next() or .closest(selector).find(".warning")
your boss fill fire you if your client loses $$$ cause you forgot to watch for copy-paste cases. ;) Kidding, use "input" event.
P.S use .warning{display:none;} instead of visibility
So I am using Node.JS and doing a small multiplayer project.
Of course I'm using JavaScript for a lot of things.
I would like to check if a div contains a certain word and if that certain word matches a variable.
How would I do this with JavaScript?
I want something like:
var teststring = "hi";
if "<div id="test">" contents matches "teststring"
{
}
I also have jQuery so that's an option too!
I'm new to JavaScript so please fire away!
This was my attempt but it didn't work:
var socket = io.connect('http://*');
socket.on('field', function (data) {
if ($("#userid").text().indexOf(data) > -1)
{
window.alert('lol');
console.log(data);
$("#field").html(data);
}
else
{
window.alert("Something has gone wrong with the node server...");
}
});
Just check the contents of the div with the text() function of jQuery, like this:
var teststring = "hi";
if ($("#test").text().indexOf(teststring) > -1)
{
alert("Match!");
}
to get the value of the div you can use
var divValue = $('#test').text();
var teststring = "hi";
and to match with the variable;
if(divValue === teststring ){
alert('Two variables are matching !!');
}
and to search a String contains a substring you can use;
if (divValue.indexOf(teststring ) >= 0)
{
alert('Two variables are matching !!');
}
please visit http://jsfiddle.net/dennypanther/ojmyobL8/
In JavaScript u can do it lyk this :
var teststring = "hi";
var div=document.getElementById('test').innerHTML;
if(div.indexOf(testString) > -1 ){
// your code goes here
}
I'm looking to add to a string's value based on the output for multiple if statements but I don't seem to be having much success. I've declared comp_string="" at the beginning of the script then tried += so that for each condition that is true it adds a section on.
For the code example below if I submitted the value of www.facebook.com and www.twitter.com I would like comp_string to return 'fb=www.facebook.com&tw=www.twitter.com'
How would I go about concatenating/adding the string together and how do I add the & if more than one link is provided. I could add it to each string for any value thats not blank, but would an & on the end of the url with nothing following mess things up?
if (facebook_url != "") {
comp_string += "fb="+facebook_url;
}
if (twitter_url != "") {
comp_string += "tw="+twitter_url;
}
alert(comp_string);
A simple approach would be to add each string to an array, then join the array elements to produce the end result you are looking for.
var params = [];
if (facebook_url !== "") {
params.push("fb=" + facebook_url);
}
if (twitter_url !== "") {
params.push("tw=" + twitter_url);
}
alert(params.join("&"));
Reference
This question already has answers here:
Adding http:// to all links without a protocol
(4 answers)
Closed 8 years ago.
I would like to detect url's that are entered in a text input. I have the following code which prepends http:// to the beginning of what has been entered:
var input = $(this);
var val = input.val();
if (val && !val.match(/^http([s]?):\/\/.*/)) {
input.val('http://' + val);
}
How would I go about adapting this to only append the http:// if it contains a string followed by a tld? At the moment if I enter a string for example:
Hello. This is a test
the http:// will get appended to hello, even though it's not a url. Any help would be greatly appreciated.
This simple function works for me. We don't care about the real existence of a TLD domain to gain speed, rather we check the syntax like example.com.
Sorry, I've forgotten that VBA trim() is not intrinsic function in js, so:
// Removes leading whitespaces
function LTrim(value)
{
var re = /\s*((\S+\s*)*)/;
return value.replace(re, "$1");
}
// Removes ending whitespaces
function RTrim(value)
{
var re = /((\s*\S+)*)\s*/;
return value.replace(re, "$1");
}
// Removes leading and ending whitespaces
function trim(value)
{
return LTrim(RTrim(value));
}
function hasDomainTld(strAddress)
{
var strUrlNow = trim(strAddress);
if(strUrlNow.match(/[,\s]/))
{
return false;
}
var i, regex = new RegExp();
regex.compile("[A-Za-z0-9\-_]+\\.[A-Za-z0-9\-_]+$");
i = regex.test(strUrlNow);
regex = null;
return i;
}
So your code, $(this) is window object, so I pass the objInput through an argument, using classical js instead of jQuery:
function checkIt(objInput)
{
var val = objInput.value;
if(val.match(/http:/i)) {
return false;
}
else if (hasDomainTld(val)) {
objInput.value = 'http://' + val;
}
}
Please test yourself: http://jsfiddle.net/SDUkZ/8/
The best solution i have found is to use the following regex:
/\.[a-zA-Z]{2,3}/
This detects the . after the url, and characters for the extension with a limit of 2/3 characters.
Does this seem ok for basic validation? Please let me know if you see any problems that could arise.
I know that it will detect email address's but this wont matter in this instance.
You need to narrow down your requirements first as URL detection with regular expressions can be very tricky. These are just a few situations where your parser can fail:
IDNs (госуслуги.рф)
Punycode cases (xn--blah)
New TLD being registered (.amazon)
SEO-friendly URLs (domain.com/Everything you need to know about RegEx.aspx)
We recently faced a similar problem and what we ended up doing was a simple check whether the URL starts with either http://, https://, or ftp:// and prepending with http:// if it doesn't start with any of the mentioned schemes. Here's the implementation in TypeScript:
public static EnsureAbsoluteUri(uri: string): string {
var ret = uri || '', m = null, i = -1;
var validSchemes = ko.utils.arrayMap(['http', 'https', 'ftp'], (i) => { return i + '://' });
if (ret && ret.length) {
m = ret.match(/[a-z]+:\/\//gi);
/* Checking against a list of valid schemes and prepending with "http://" if check fails. */
if (m == null || !m.length || (i = $.inArray(m[0].toLowerCase(), validSchemes)) < 0 ||
(i >= 0 && ret.toLowerCase().indexOf(validSchemes[i]) != 0)) {
ret = 'http://' + ret;
}
}
return ret;
}
As you can see, we're not trying to be smart here as we can't predict every possible URL form. Furthermore, this method is usually executed against field values we know are meant to be URLs so the change of misdetection is minimal.
Hope this helps.