I am trying to create an SOS page in which i am changing the links on the page after the button click. My problem here is that the links get changed but they get appended to the current pages URL.
My links do contain http:// (My reputation is less than 10 here)
Eg.
Originall link -- "htp://xyz.com?login_type=encrypted&login=&password="
Required link -- "htp://xyz.com?login_type=encrypted&loginxxx=&password=yyy"
Actual link that I am getting -- "htp://currentpageURL.com"htp://xyz.com?login_type=encrypted&login=&password=""
Here is the js I am using
function handleClick()
{
var uid, pwd;
uid = $("#uid").val();
pwd = $("#pwd").val();
if(uid != "" && pwd != "")
{
$("#links").show();
$("#login").hide();
$('a').each(function () {
var href = $(this).attr("href");
$(this).attr("href", href.replace("login=", "login=" + uid).replace("password=", "password=" + pwd));
});
}
else { alert("Please enter valid credentials"); }
}
You could find the "last part" of the script using the attached link and then just add the "login=" and "password="" to then end? See: this.href vs $(this).attr('href')
Related
I have multiple html pages
I have some specific content in Home page, its content should not be changed when the page is refreshed or reloaded.
But when I navigate to other pages and then come back to Home page, I would like to show / hide div or section of html in the Home page.
How this can be achieved?
You can use document.referrer to get the previous page URL and hide the element you want to hide using a condition.
//element to hide
var boxA = document.querySelector('.boxA');
//last page url
var lastPage = document.referrer.split("/").pop();
//checking if element exist and previous page is page B
if(boxA && lastPage === 'b.html' ){
boxA.style.display = 'none';
}
StackOverflow snippet doesn't support multiple html pages, please check this plunker to understand the above code better https://plnkr.co/edit/sbBIHf1RZA7YMTL4sJfd?p=preview
Add a querystring to the url using JS on page B, then check for it on page A and remove/modify content as needed:
// Set url parameter:
var myURL = document.location;
document.location = myURL + "?a=parameter";
// Check for url parameter:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
Link from page B to page A with a url querystring. Something like
https://mywebsite.com/a?myParam=1
Then on page A.
var myParam = location.search.split('myParam=')[1]
if(myParam == 1){
document.getElementById('hideDiv').style.display = 'none';
}
I am developing a website that works in two languages. I need to change URL to include the selected language.
What I exactly need is:
Pick the current URL
Check if the URL contains any language code
Append the code if not exist or change the code to the selected one if exists
For example, there is an URL for English (default):
http://localhost:11767/Home/resultMain?model=1&&type=1
When a user selects Spanish (es) it should be:
http://localhost:11767/es/Home/resultMain?model=1&&type=1
You can parse the URL with the help of an a element then replace the part you want and re-build the URL :
function addReplaceLangCode(url, langCode) {
var a = document.createElement('a');
a.href = document.getElementById('url').value; // or document.location.href;
var paths = a.pathname.split('/');
paths.shift();
if(paths[0].length == 2) {
paths[0] = langCode;
}else{
paths.unshift(langCode);
}
return a.protocol + '//' +
a.host + '/' + paths.join('/') +
(a.search != '' ? a.search : '') +
(a.hash != '' ? a.hash : '');
}
function onClickReplace() {
document.getElementById('result').innerHTML = addReplaceLangCode( document.location.href, 'es');
}
URL : <input type="text" id="url" style="width:400px" value="http://localhost:11767/Home/resultMain?model=1&&type=1"><input type="button" value="Replace" onclick="onClickReplace()"><br />
Result: <span id="result"></span>
I don't know if it is exactly this, what you want. But JavaScript can obtain URL using object "location". Especially location.pathname is useful for you. You can apply reg-exp on location.pathname to check if URL contain /es/ and if yes, then translate website by proper Ajax requests to your backend.
But generally I recommending to use routing of your backend. The best solution in my opinion - use http headers to inform server about preferred language.
https://www.w3.org/International/questions/qa-accept-lang-locales
Based on #Bulnet Vural's answer above, I wrote the following code because I needed to toggle the language path in and out of the url.
var getOtherLanguageLocation = function (currentUrl, languagePath) {
// based on https://stackoverflow.com/a/42176588/1378980
var anchorTag = document.createElement('a');
anchorTag.href = currentUrl;
var paths = anchorTag.pathname.split("/");
// remove all the empty items so we don't get double slash when joining later.
var paths = paths.filter(function (e) { return e !== '' })
// the language will be at index 1 of the paths
if (paths.length > 0 && paths[0].toLowerCase() == languagePath) {
// remove the language prefix
paths.splice(0, 1);
} else {
// add the language prefix
paths.unshift(languagePath);
}
return anchorTag.protocol + '//' +
anchorTag.host + '/' + paths.join('/') +
anchorTag.search + anchorTag.hash;
};
I have some problem with redirecting urls after checkboxes are selected. I am using document.location for this, but this doesn´t work in my code. I'm trying to fix it, but without success.
This is the part of my code which doesn't work:
function objednat() {
var adress = "";
if (document.getelementbyid('BoxtarifVolani1').checked == true) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/' + adresa;
}
I want to redirect this to a form, which will be filled with the selected values. I don't know why, but this document.location doesn't work in the code.
This is the part of the code I use in the formula for grabbing the hash from the url.
<script type="text/javascript">
if(window.location.hash) {
//set the value as a variable, and remove the #
var hash_value = window.location.hash.replace('#', '');
if (tarifVolani1 == true) {
document.getelementbyid('BoxtarifVolani1").checked = true;}
....
</script>
What am I doing wrong?
Whatever you have done is right, except, the function name is wrong case:
Change getelementbyid to getElementById.
Change adresa to adress.
Code:
function objednat() {
var adress = "";
if (document.getElementById('BoxtarifVolani1').checked == true) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/' + adress;
}
jQuery way of doing it
function objednat() {
var adress = "";
if ($('#BoxtarifVolani1').is(':checked')) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/'+adress;
}
For your ref: jQuery :checked Selector
I want to redirect my users to different languages/subfolders based on their IP address. To do this I use the JavaScript GeoIP API from MaxMind.
The problem: The english speaking people should stay at mydomain.com and not go to mydomain.com/en/. But when I redirect to mydomain.com the GeoIP script runs again which creates an infinite loop.
Here is my code (in index.html for mydomain.com):
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
if(country == "FR")
{
window.location = "http://mydomain.com/fr/"
}
else
{
window.location = "http://mydomain.com/";
}
</script>
In other posts I read about setting a cookie, but I wasn't able to do it in a way that solves the problem (and it would still create a loop when the user doesn't accept cookies, on mobile for example).
Another solution could be to redirect to mydomain.com/en/ and delete the /en/ folder in the URL via htaccess, but I wasn't able to get this done either.
An example of how I want it to work would be waze.com (it seems like they have the english version in the /en/ folder, but delete it from the URL).
So if anybody is able to help, I would be very grateful. Thanks a lot!
EDIT: I solved the problem myself. It's very simple: Just use the root directory for the english page and change function to "else {null;}" :-)
Your problem is not with geoip but with your code.
Try this:
var country = geoip_country_code();
var currentLocation = String(window.location);
//if geoip is equal FR and window.location is different "http://mydomain.com/fr/"
if(country === "FR" && currentLocation.indexOf("http://mydomain.com/fr/")!==0)
{
window.location = "http://mydomain.com/fr/"
}
//if geoip is different FR and window.location is equal "http://mydomain.com/fr/"
else if(currentLocation.indexOf("http://mydomain.com/fr/")===0)
{
window.location = "http://mydomain.com/";
}
To detect using multiple languages simply edit the following variables:
var defaultsLang are the languages that are supported by the main root (site.com/)
var languages languages supported by sub-pages (site.com/fr/, site.com/es/, etc.)
See code (not tested):
(function(){
var defaultsLang = ["en-us","en"];
var languages = {
"fr": true, //enable french pages
"pt": false, //tmp disable portuguese pages
"es": true //enable spanish pages
};
var country = geoip_country_code().toLowerCase(),
currentLocation = String(window.location),
detectCurrent = function(){
var a = currentLocation.replace(/^(http|https)[:]\/\//, "");
var b = a.split("\/");
b = b[1].toLowerCase();
a = null;
return b.length<5 && (/^[a-z\-]+$/).test(b) ? b : false;
};
var currentLang = detectCurrent();
defaultsLang = "|"+defaultsLang.join("|")+"|";
if(currentLang!==country && typeof languages[country] !=="undefined" && languages[country]!==false){
window.location = "http://mydomain.com/" + country + "/";
} else if(
defaultsLang.indexOf("|" + currentLang + "|")===-1 && //current page is not the same as default languague(s)
defaultsLang.indexOf("|" + country + "|")!==-1 && //geoip is in the list of default language(s)
currentLang!==false
){
window.location = "http://mydomain.com/";
}
})();
I initially wrote a small ajax-based settings page for an online support system i developed, using jQuery 1.4.2 and it worked fine. However, after upgrading to 1.6.1, additional executions are being called to the functions that were only ever called once previously.
I have three menu options, each with an onclick event to load a specific page into the #settingsph div. Additional code is then called depending on the page in question. (The apache server automatically assumes .php file ext are to be used if none are defined)
function open_page(name) {
$("#settingsph").load("/includes/support/stg/"+name, function(){
if(name == "managecontacts"){
$("#contactselect").load("/includes/support/stg/contactsel");
}else if(name == "changepw"){
$(change_pw(), "changepw_box");
}else if(name == "editcompany"){
$(company_update(), "#company_update");
}
});
}
Once loaded, a select box is presented to users, to select a contact to edit. Onchange, the following function is called.
function open_contact(id) {
$("#contact_info").load("/includes/support/stg/editcontact?id="+id);
if(id != "NewContact") {
$(contact_update(), "#contact_update");
}else{
$(contact_add(), "#contact_add");
}
}
Let's assume the user has decided to edit their contact information (all 3 update pages use roughly the same function, but with the variables changed to reflect the page it took information from).
function contact_update() {
$('input.text-input').css({backgroundColor:"#ffffe0"});
$('input#ldate').live('focus', function(){
$(this).datepick({dateFormat: 'dd/mm/yy'});
});
$("input.text-input").live('focus', function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$("input.text-input").live('blur', function(){
$(this).css({backgroundColor:"#ffffe0"});
});
$('.error','#contact_info').hide();
$(".buttonupd").live('click', function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var forename = $("input#forename").val();
if (forename == "") {
$("label#forename_error").show();
$("input#forename").focus();
$('input#forename').css({border:"solid #aa0000"});
}else{
$('input#forename').css({border:""});
}
var surname = $("input#surname").val();
if (surname == "") {
$("label#surname_error").show();
$("input#surname").focus();
$('input#surname').css({border:"solid #aa0000"});
}else{
$('input#surname').css({border:""});
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
$('input#phone').css({border:"solid #aa0000"});
}else{
$('input#phone').css({border:""});
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
$('input#email').css({border:"solid #aa0000"});
}else{
$('input#email').css({border:""});
}
if((forename == "") || (surname == "") || (phone == "") || (email == "")){
return false;
}
var contactid = $("input#contactid").val();
var jobtitle = $("input#jobtitle").val();
var site = $("select#site option:selected").val();
var mobile = $("input#mob").val();
var ldate = $("input#ldate").val();
var loginallowed = $("input[name='loginallowed']:checked").val();
var editaddress = $("input[name='editaddress']:checked").val();
var editcontacts = $("input[name='editcontacts']:checked").val();
var editcompany = $("input[name='editcompany']:checked").val();
var lognewissue = $("input[name='lognewissue']:checked").val();
var viewallissues = $("input[name='viewallissues']:checked").val();
var viewchangelog = $("input[name='viewchangelog']:checked").val();
var viewdownloads = $("input[name='viewdownloads']:checked").val();
var newissuenotify = $("input[name='newissuenotify']:checked").val();
var closeissuenotify = $("input[name='closeissuenotify']:checked").val();
var changelognotify = $("input[name='changelognotify']:checked").val();
var viewsitehardware = $("input[name='viewsitehardware']:checked").val();
var viewcompanyhardware = $("input[name='viewcompanyhardware']:checked").val();
var dataString = 'contactid=' + contactid + '&forename=' + forename + '&surname=' + surname + '&jobtitle=' + jobtitle + '&site=' + site + '&email=' + email + '&phone=' + phone + '&mob=' + mobile + '&ldate=' + ldate + '&loginallowed=' + loginallowed + '&editaddress=' + editaddress + '&editcontacts=' + editcontacts + '&editcompany=' + editcompany + '&lognewissue=' + lognewissue + '&viewallissues=' + viewallissues + '&viewsitehardware=' + viewsitehardware + '&viewcompanyhardware=' + viewcompanyhardware + '&viewchangelog=' + viewchangelog + '&viewdownloads=' + viewdownloads + '&newissuenotify=' + newissuenotify + '&closeissuenotify=' + closeissuenotify + '&changelognotify=' + changelognotify;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/includes/support/stg/contactupd",
data: dataString,
success: function() {
$('#contact_update').html("<div id='contact_upd_msg'></div>");
$('#contact_upd_msg').html("<h2>Contact Successfully Updated</h2>")
.append("<p>Thank you.</p>")
.hide()
.fadeIn(1500, function() {
$('#contactselect').html("")
$("#contactselect").load("/includes/support/stg/contactsel");
});
}
});
return false;
});
}
The first time the function is executed, it is called only once and appears to be fine. However, if the above function is called a second time to perhaps update another contact, two requests are sent, updating the information twice and refreshing the select box with a list of contacts in twice. If the above function is called a third time, three requests are sent and so on until the page is completely refreshed. I reverted back to 1.4.2 and these functions are only ever executed once, regardless of how many times they're called without a page refresh.
The .live() method was introduced to me here on SO when i first wrote the system and worked well at the time since the .buttonupd does not exist in the DOM when the settings.php page is loaded, is this my problem?
As was mentioned in the comment, you shouldn't be attaching events within a function which could be called multiple times. Each time you call live within that function you are attaching a new event handler. That's why if that method gets called 3 times, triggering the event will cause the handler to run 3 times.
Here is a stripped down example:
http://jsfiddle.net/N78MX/
Notice that every time you click, the number of words added increases by one. This is because each click calls live and attaches another handler.
You can fix this by simply moving all of your live calls outside of your function. Since you are using live it is fine to call it prior to the elements in question being created. So the stripped down example becomes this:
http://jsfiddle.net/N78MX/1
and it works no matter how many times you click. (obviously if this were a real page I would combine those two live calls, but this is just for illustration).