Change route values of a link with jQuery - javascript

I'd appreciate any help.
I'm trying to change the link href each time with Kendo Grid change() event:
function ContractsGrid_onChange(e) {
var selected = this.select()[0],
item = this.dataItem(selected);
$('#createOnBase').attr('href', function () {
var createLink = document.getElementById("createOnBase");
var route = 'http://' + createLink.hostname + createLink.pathname + "?contractID =" + item.ID;
return route;
});
}
#Ajax.ActionLink("Create", "CreateOnBase",
new { contractID = "_contractID_" },
new AjaxOptions() {... },
new { id="createOnBase" })
I'm not sure with current approach, because i have different hostnames (localhost with port or server domain)
The best way would be:
var route = "#Url.Action('CreateOnBase', new { contractID = ??})";
But I cannot use JS variable (item.ID) in razor.
Also, this.href.replace("_contractID_", item.ID) won't work for several changes.
Can you help me with another solution?
Thanks a lot!

Yeh, that was easy, I found a way:
$('#createOnBase').attr('href', function () {
return "#Url.Action("CreateOnBase")"+ "/?contractID=" +item.ID;
});
maybe it will be helpful for someone.

The first thought that come up to my mind is to store root url in separate variable.Something like this:
function ContractsGrid_onChange(e) {
var selected = this.select()[0],
item = this.dataItem(selected);
var rootUrl = #Url.Action("Create", "CreateOnBase");
$('#createOnBase').attr('href', function () {
var createLink = document.getElementById("createOnBase");
var route = rootUrl + "?contractID =" + item.ID;
return route;
});
}
This is just a workaround, not sure about some advanced way...

Related

Two window.location not working togeather

I have two functions what sets a window.location.href tag in the url, but when I set the first one and then select the other one, the first one disappears. So how should I do? These functions are in a form that makes a selection of 1. project name and 2. package. And then you submit the form (php) the fields adds to the database.
function jsFunction(){
var myselect = document.getElementById("projektnamn");
window.location.href = "?projektnamn=" + myselect.options[myselect.selectedIndex].value;
}
function services(){
var select = document.getElementById("paket");
window.location.href = "?paket=" + select.options[select.selectedIndex].value;
}
I want the result to be like this:
domain.com?projektnamn=Something?paket=Something
What I get today is:
domain.com?projektnamn=Something
Or I get:
domain.com?paket=Something
I would store the link in a variable
let query = "";
function jsFunction(){
var myselect = document.getElementById("projektnamn");
query += "?projektnamn=" + myselect.options[myselect.selectedIndex].value;
}
function services(){
var select = document.getElementById("paket");
query += "?paket=" + select.options[select.selectedIndex].value;
window.location.assign(query);
}
Both of your functions are resetting the URL.
What you can do is use URLSearchParams to generate the query string.
function jsFunction(params) {
var myselect = document.getElementById("projektnamn");
params.set('projektnamn', myselect.options[myselect.selectedIndex].value);
}
function jsFunction2(params) {
var select = document.getElementById("paket");
params.set('paket', select.options[select.selectedIndex].value);
}
const params = new URLSearchParams();
jsFunction(params);
jsFunction2(params);
window.location.href = `${location.pathname}?${params}`;
From what it looks like you are trying to build a single function, not two separate functions. I would replace these 2 functions with one generic.
function jsFunction(params, id, name) {
var myselect = document.getElementById(id);
params.set(name, myselect.options[myselect.selectedIndex].value);
}
const params = new URLSearchParams();
jsFunction(params, "projektnamn", 'projektnamn');
jsFunction(params, "paket", 'paket');
window.location.href = `${location.pathname}?${params}`;

about axios.all(),if I have some likely funs to run,how can i use the Axios.all

function (type) getMember {
var that = this;
var url = "/XXXXX";
return axios.post(url)
}
axios.all().then(axios.spread(function () {
console.log('init finished')
}));
now I have to function GetMember of different type,so I choose
axios.all(),I hope it work,yeah, it can work.
axios.all([getMember(0),getMember(1),getMember(2)]).then(axios.spread(
function () {
console.log('init finished');
console.log(arguments.length)//3
}));
but I think it`s not graceful for coding. I want to write a circulation ,and push arguments into "all(" ")",like this,I try 'eval(str)',it can work and run the function that I want to run,but arguments.length only be one, I can get all the data from all requests.
I found the following method. It is not the best, but it does work:
var requestFun = '[';
for (var i = 0; i < operType.length; i++) {
requestFun += 'this.getMemberInfo(operType[' + i + ']),';
}
requestFun += ']'
axios.all(eval(requestFun)).then(axios.spread(function () {
})

Redefine "this" within a function prototype and run it with new parameters

I have a function prototype that loads data from a path. The trick is that I need to change the path afterward. I tried call, apply, bind and even assign but as I am a novice I did not find the solution.
Here a sample of my code :
Chat.prototype.loadMessages = function() {
this.messagesRef = this.database;
var setMessage = function(data) {
var val = data.val();
this.displayMessage(data.key, val.name, val.text);
}.bind(this);
};
var chat = new Chat
function setPath (newpath) {
chat.loadMessages.messageRef = newpath; // I guess, it is where I'm wrong...
chat.loadMessages(); // It should load messages from the new path in my chat container.
}
As I said I also tried :
chat.loadMessages.call(newpath);
or
var setPath = function(newpath) {
chat.loadMessages(newpath);
}.bind(chat);
setPath();
chat.loadMessages();
But the chat container continues to disclose messages from the old path...
This looks a bit convoluted. Just pass messagesRef as a parameter and make it default to this.database:
Chat.prototype.loadMessages = function(messagesRef = this.database) {
// do whatever is needed with messagesRef
};
chat = new Chat();
chat.loadMessages(); // load from the default location
chat.loadMessages('foobar'); // load from this specific location
It looks like you are creating a function with loadMessages, which is fine but you need to pass in a value to set the new path. Is this more of what you were thinking?
Chat.prototype.loadMessages = function (newPath) {
this.messagesRef = newPath || this.database; // if newPath is empty than default to this.database
var setMessage = function(data) {
var val = data.val();
this.displayMessage(data.key, val.name, val.text);
};
var chat = new Chat
function setPath (newpath) {
chat.loadMessages(newpath);
}

Javascript - copy link

I want to extract a part of a website address and append it to an other link.
Example: website.com/abc123 --> otherwebsite.com/abc123
Is there an easy way to do this?
I'm new to JavaScript
function returnNewAdress(adr, ows) {
return ows + adr.substring(adr.indexOf("/"), adr.length);
}
returnNewAdress("website.com/abc123", "otherwebsite.com");
function OtherURL(What) {
NewURL='otherwebsite.com';
return NewURL+'\/'+What.substring(What.lastIndexOf('\/'));
}
It's unclear in what environment the function should run.
In node.js you could do this:
var transformUrl = function (url, newDomain) {
if (! url.match(/https?:\/\//i)) {
// prepend URL with protocol if missing
url = "http://" + url;
}
return newDomain + require("url").parse(url).path;
};
// can be called like this:
// this will return 'otherwebsite.com/abc123'
transformUrl("website.com/abc123", "otherwebsite.com");
transformUrl("http://website.com/abc123", "otherwebsite.com");

Protractor test hangs when clicking on element

I have been trying to write a protractor test that selects an item from a custom dropdown menu. The only problem is that when it tries to click an element other than the last one in the list it hangs and timesout. When I remove the click() method invocation it seems to work fine. Since all these calls are done asynchronously I also don't see a way of stopping the loop when it finds the element. My code looks like this:
var it = null;
for(var i = 1; i <= totalNumberOfAccounts; i++) {
var listItemLocator = '//div[#id="payment-accounts"]/div/ul/li[' + i + ']/label/div/div[2]/div[2]/span[2]';
var item = browser.driver.findElement(protractor.By.xpath(listItemLocator));
item.getText().then(function(value) {
if(value === accountNumber) {
it = item;
}
console.log(value);
})
.then(function clickOption() {
console.log('Clicking...');
if (it) {
console.log('Clicking desired item');
it.click();
console.log('Clicked..');
}
})
}
I also tried this approach:
this.selectRichSelectOption = function (selector, item) {
var selectList = browser.driver.findElement(selector);
selectList.click();
var desiredOption = '';
var i = 1;
selectList.findElements(protractor.By.tagName('li'))
.then(function findMatchingOption(options) {
console.log(options);
options.some(function (option) {
console.log('Option:');
console.log(option);
var listItemLocator = '//div[#id="payment-accounts"]/div/ul/li[' + i + ']/label/div/div[2]/div[2]/span[2]';
console.log(listItemLocator);
var element = option.findElement(protractor.By.xpath('//label/div/div[2]/div[2]/span[2]'));
console.log('Element:');
console.log(element);
i++;
element.getText().then(function (value) {
console.log('Value: ' + value);
console.log('Item:');
console.log(item);
if (item === value) {
console.log('Found option..');
desiredOption = option;
return true;
}
return false;
});
});
})
.then(function clickOption() {
console.log('Click option');
console.log(desiredOption);
if (desiredOption) {
console.log('About to click..');
desiredOption.click();
}
});
};
The result of this one is even more strange. Now all of a sudden the getText() method invocation returns an empty String. But when I try to retrieve the e.g. the class attribute I get the correct value back. Where did the Text value go?
Can somebody please help me out?
This seems to be an issue with page load. After you select, the page does not load completely.
Try using a browser.sleep(timeInMs);
try using node 8+'s async functions such as await. I went through this headache and it was solved by awaiting for certain things to appear or have certain attributes.
await browser.wait(EC.presenceOf(element(by.xpath('path leading to element based off attribute'))))
Good luck

Categories