$(document).ready(function () {
var loc = window.location.hostname;
alert(loc);
if (loc = "xyzvalue.com") {
//do some operation
}
});
I am using above jquery to get current url in jquery.Alert will show xyzvalue.com as popup. Now I want to check for "value" string in xyzvalue.com.
if (loc = "xyzvalue.com") {
should be
if (loc == "xyzvalue.com") {
Related
I have a theme that sets the selected left navigation option based on what URL you are visiting. However, it breaks if the is a variable attached to the URL, for example www.test.com/abc.aspx?delete=1. The URL www.test.com/abc.aspx works fine and sets the link ABC to active.
I have tried to modify the code to cut off everything after and including ?, but it won't work as intended (nothing in the NAV is selected).
ORIGINAL CODE:
$(function () {
var url = window.location;
var element = $('ul#sidebarnav a').filter(function () {
return this.href == url;
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});
MY EDITED CODE:
$(function () {
var url = window.location.toString();
var url_fix = url.split('?');
var element = $('ul#sidebarnav a').filter(function () {
return this.href == url_fix[0];
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});
I think it is the line with "return this.href == url_fix[0];" that is the culprit.
SOLUTION (what I came up with after reading the comments, thanks guys):
$(function () {
var url = location.href.split("/").slice(-1).toString();
var url_fix = url.split('?');
var element = $('ul#sidebarnav a').filter(function () {
return $(this).attr("href") == url_fix[0];
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});
Try comparing pathnames instead.
var element = $('ul#sidebarnav a').filter(function () {
return this.pathname == location.pathname;
}).addClass('active').parent().addClass('active');
For example on this page location.pathname returns:
"/questions/48234042/set-selected-navigation-option-using-window-locaiton/48234196"
and does not include location.hash or location.search
I used the answer by #vbguyny to solve the issue. Had to add location.href.split("/").slice(-1).toString(); to get the actual page name, but after that it worked fine. Thanks!
I've downloaded this script for use conditional fields in forms:
(function ($) {
$.fn.conditionize = function(options) {
var settings = $.extend({
hideJS: true
}, options );
$.fn.showOrHide = function(is_met, $section) {
if (is_met) {
$section.slideDown();
}
else {
$section.slideUp();
$section.find('select, input').each(function(){
if ( ($(this).attr('type')=='radio') || ($(this).attr('type')=='checkbox') ) {
$(this).prop('checked', false).trigger('change');
}
else{
$(this).val('').trigger('change');
}
});
}
}
return this.each( function() {
var $section = $(this);
var cond = $(this).data('condition');
// First get all (distinct) used field/inputs
var re = /(#?\w+)/ig;
var match = re.exec(cond);
var inputs = {}, e = "", name ="";
while(match !== null) {
name = match[1];
e = (name.substring(0,1)=='#' ? name : "[name=" + name + "]");
if ( $(e).length && ! (name in inputs) ) {
inputs[name] = e;
}
match = re.exec(cond);
}
// Replace fields names/ids by $().val()
for (name in inputs) {
e = inputs[name];
tmp_re = new RegExp("(" + name + ")\\b","g")
if ( ($(e).attr('type')=='radio') || ($(e).attr('type')=='checkbox') ) {
cond = cond.replace(tmp_re,"$('" + e + ":checked').val()");
}
else {
cond = cond.replace(tmp_re,"$('" + e + "').val()");
}
}
//Set up event listeners
for (name in inputs) {
$(inputs[name]).on('change', function() {
$.fn.showOrHide(eval(cond), $section);
});
}
//If setting was chosen, hide everything first...
if (settings.hideJS) {
$(this).hide();
}
//Show based on current value on page load
$.fn.showOrHide(eval(cond), $section);
});
}
}(jQuery));
I'm trying this because I need to use conditionize() in one of my tabs and when I reload the tab, all works but if I go to other tab and I return to the previous tab(where I need this works), I get that error.
When I change tabs, I'm only reloading one part of the page.
When I load the page this works perfectly, but if I try to call function again from browser console, it tells me that TypeError: $(...)conditionize() is not a function.
I have included the script in header tag and I'm calling it with this script on the bottom of body:
<script type="text/javascript">
$('.conditional').conditionize();
</script>
EDIT:
I have written
<script type="text/javascript">
console.log($('.conditional').conditionize);
setTimeout(function () {console.log($('.conditional').conditionize);}, 2);
</script>
and this print me at console the function, and when 2 milliseconds have passed, it print me undefined
I have found the solution.
Because any reason, the $ object and jQuery object are not the same in my code.
I have discovered it using this on browser console:
$===jQuery
This return false (This was produced because in other JS, I was using the noConflict(), which give me the problem)
Explanation: noConflict()
So I have solved it changing the last line of my JS by:
//Show based on current value on page load
$.fn.showOrHide(eval(cond), $section);
});
}
}($));
Putting the $ instead of 'jQuery'
I have this code
events.on('loaded', function() {
$('.server_details .start button').click();
});
but I only want it to run if the end of the URL is &autoconnect, can someone show example of how to do this?
Example URL http://www.example.com:7778&autoconnect
You can get the url with window.location.href
and then check that using indexOf:
events.on('loaded', function() {
if (window.location.href.indexOf("&autoconnect") > -1) {
$('.server_details .start button').click();
}
});
You say "I only want it to run if the end of the URL is &autoconnect"
I say
var url = 'http://www.example.com:7778/&autoconnect';
var param = '&autoconnect';
var valid = url.indexOf(param) == url.length - param.length;
If there is a possibility that there may be other parameters as well...
var url = 'http://www.example.com:7778/&autoconnect&alsovalid';
var param = '&autoconnect';
var valid = url.indexOf(param) >= 0;
This would be more correct I suppose.
$(window).on('load', function () {
if (window.location.href.indexOf('url-content') > -1) {
// Your function do be executed
}
});
Currently im looping through links in a page and checking if the link contains a string to determine the url. Heres my current code:
$( ".domain a" ).each( function () {
if ($(this).is(':contains("imgur")')) {
This can detect if the element contains the string "imgur", but because of this is a link goes to a site like slimgur.com, it will also return true.
How can I properly check that the url is, in this example, imgur.com or any of its subdomains (i.imgur.com & m.imgur.com) and that a url such as slimgur.com wont return true?
Rather than check the text, use the properties associated to an <a> tag like hostname.
$( ".domain a" ).filter(function(){
return this.hostname === 'imgur.com';
}).doSomething();
DEMO
This will do it:
$( ".domain a" ).each( function() {
var str = 'imgur';
if($(this)[0].hostname.split('.').indexOf(str) > -1) {
console.log('Found ' + str);
}
})
You could do something like: JS Fiddle
$('a').each(function () {
var url = "yahoo.com";
var anchor = $(this).attr('href');
var domain = url_domain(anchor);
if (url === domain) {
//Do something here
}
});
function url_domain(data) {
var a = document.createElement('a');
a.href = data;
return a.hostname;
}
url_domain() function found here: Extract hostname name from string
I'm sending a specific value through url and after that my page get refreshes.
The URL value is dynamic.Whenever URL sets I want to show div which is already hidden.
<button id="show_id" onclick="location.href='opdcasepaperreport.php?patient_nm='+document.getElementById('patient_id').value;" > View Report </button>
When user clicks on View Report , report div will be displayed.
I tried following 2 coding methods:
$( document ).ready(function()
{
$("#show_id").click(function()
{
$('#main').toggle();
});
});
and
$(document).ready(function ()
{
if(window.location.href.indexOf("?patient_nm"))
{
//alert("your url contains ");
//show code;
}
});
in 1st case because of page refresh div get visible and un visible again.
Is there any solution for this like in php if(isset(---)){//do this;}
Changing location.href value will refresh the page anyway.
In order to hide/show div depending on url value you need to:
get the value by searching in url params.
show / hide div.
Get URL params.
You can use this script in order to get url params:
var getQuery = function () {
var url_params = {};
var query = window.location.search.substring(1);
if (query.length === 0) return false;
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof url_params[pair[0]] === "undefined") {
url_params[pair[0]] = pair[1];
} else if (typeof url_params[pair[0]] === "string") {
var arr = [ url_params[pair[0]], pair[1] ];
url_params[pair[0]] = arr;
} else {
url_params[pair[0]].push(pair[1]);
}
}
return url_params;
};
It will return an object (key, value).
Show / Hide div
If you using jQuery, you can simply is .toggle()
$("#your_div_name").toggle();
Or by using .show() / .hide()
So:
var query = getQuery();
if (query && query.some_param !== undefined) {
$("#your_div_name").show()
} else {
$("#your_div_name").hide()
}
But it's better not to use url params in order to change view.
Have fun.
How about this:
$("#show_id").click(function(e)
{
e.preventDefault();//this will prevent page refresh
$('#main').toggle();
});
Try following code:
$( document ).ready(function()
{
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var hasParam = getParameterByName('patient_nm');
if(hasParam !== 'undefined') {
$('#main').toggle();
}
});
As per your code, on button click the element will get toggled but after that the page gets refreshed immediately. On page refresh the element will be hidden again, so you are not able to view the effect.
As per my code above, when the page refreshes/loads, it will search for the parameter "patient_nm" that you are adding in the URL. If this parameter is not empty it will toggle the element. Since this process happens after page load, you will be able to see the results.
Hope this helps.