java script function and variable based windows.location - javascript

One more silly question. How do I open user profile with click on name of user.
test1.php page is common profile page for all users. I use $ui for check user id in data base and display value as required.
test1.php contains
function user_link(user_id) {
var ui=user_id;
window.location = "test1.php?ui=ui";
}
user name link:
<span id="user_link" onclick="user_link(21)">'Samantha Dove'</span>

Use:
function user_link(user_id){
var ui = user_id;
window.location = "test1.php?ui=" + ui;
}
You need to do concatenation here to append your variable in the URL.
Or shorter:
function user_link(user_id){
window.location = "test1.php?ui=" + user_id;
}
Or even shorter, after all:
<a id="user_link" href="test1.php?ui=21">'Samantha Dove'</a>

Related

Drive Traffic to New Href Link when A Tag is Clicked

I am working to pull the entire URL from the inbound traffic source of a page and extract a single query string value from it, and then use this value as part of a new URL.
The new URL will be used to send traffic to another page when it is clicked.
My code below I checked does go into the fnView function but I can't get the new url to be navigated to when the a tag is clicked.
JavaScript
document.addEventListener('DOMContentLoaded', pEvents);
function pEvents() {
function fnView() {
var queryString = window.location.search;
var utm_content;
if (queryString !== null) {
utm_content = queryString.match(/utm_content=([^&]+)/)[1];
var itemId = utm_content.toString();
snaptr('track', 'VIEW_CONTENT', {
'item_ids': itemId
});
} else {
snaptr('track', 'VIEW_CONTENT');
}
document.getElementById('link').href = "https://www.sitedomain.com/m-pr.cfm?m=91020&u=2346350&p=" + itemId;
};
document.getElementById('link').addEventListener('click', fnView);
};
HTML
<a id="link" href="#">Click me</a>
Try forcing the click after setting the href value. Just add this line:
document.getElementById('link').click();

Remove query string on page reload

I have a hyperlink which i am redirecting to a page.
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
window.location = '/Merging/Index/?workItemID=' + id;
});
My action in the controller page is
public ActionResult Index(int? workItemID)
{
MergingVM mergingVM = new MergingVM();
mergingVM.SourceList = GetSourceDropdownList();
mergingVM.WorkItem = (workItemID==null? 0: workItemID.Value) ;
mergingVM.MergeActionSelectList =
GetMergeProcessActionDropdownList();
PopulateDropDowns(mergingVM);
return View(mergingVM);
}
So what it does is when i click on the hyperlink it redirects me to the merging page.
After redirecting to Merge page, the drop down fills with id(selected in home page) and correspondingly triggers the button click.
My issue When i reload the merge page the value in the drop down doesn't get clear. I.e if i have redirected from home page to merge page , then the drop down has some value. but when i refreshes it the selected value should go. I understand that the query string still holds the value. But is there any alternative to send parameter to action without using windows.location.href in jquery.
If you are using hyperlink then also you can try it
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
$(this).attr('href','/Merging/Index/?workItemID=' + id)
});
In order to clean the query string you should use redirect to another view.
public ActionResult Index(int? workItemID)
{
MergingVM mergingVM = new MergingVM();
mergingVM.SourceList = GetSourceDropdownList();
mergingVM.WorkItem = (workItemID == null ? 0 : workItemID.Value);
mergingVM.MergeActionSelectList =
GetMergeProcessActionDropdownList();
PopulateDropDowns(mergingVM);
//to send this model to the redirected one.
TempData["model"] = mergingVM;
return RedirectToAction("CleanIndex");
}
public ActionResult CleanIndex()
{
var model = (MergingVM)TempData["model"] ?? new MergingVM();
// Do something
return View("Index", model);
}
To find alternatives to an send parameter to a method you first need to understand the model Bindding action.
The model bidding searches a value in:
Form Data
Route Data
Query String
Files
Custom (cookies for example)
If your action must need to be HttpGet you lose the Form Data which would be a nice alternative for you.
If I understand correctly... the below worked for me.
If there's an ID appended to the URL, it gets logged to the console as the variable "param". The URL is then replaced (so that if you refresh the page, the ID is removed from the URL).
$(document).ready(function() {
var url = window.location.toString;
var hostname = window.location.hostname;
var pathname = window.location.pathname;
var param = window.location.search;
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
window.location = '/new-page.php?' + id;
});
if ( pathname == "/new-page.php" && param ) {
console.log(param);
window.history.pushState("string", "Title", "http://yourURL.com/new-page.php");
//Do something with param...
}
});
This assumes that if there is no ID appended to the URL, the drop-down won't do anything. You also would need to update the URLs to the correct ones (I ran this on my local server).
I think you should use POST where you don't want to presist workItemID.
I mean all places where you have links you should use somethink like this:
<form action="/Merging/Index" method="POST">
<input type="hidden" name="workItemID" value="1" /> <-- your Id
<input type="submit" value="Link to workItemID 1!" /> <-- your link
</form>
This way you will get your View but without workItemID in URL. But you should change css to make your POST link look like <a> tags.
Here is with your table:
#if (#Model.DataSetList[i].StateID == 43)
{
<td>
<form action="/Merging/Index" method="POST">
<input type="hidden" name="workItemID" value="#Model.DataSetList[i].Workitem_ID" />
<input class="lnkMerging" type="submit" value="Merging" />
</form>
</td>
}
else
{
<td>
<text style="color:darkgrey" contenteditable="false">Merging</text>
</td>
}
You can save the parameter in local storage api of html5, and then use those parameters in Page load of index page.
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
localStorage.setItem("workItemID",id);
window.location = '/Merging/Index/;
});
On page load of index you can retrieve it using getItem
localStorage.getItem("workItemID"); and use it as per your requirement.
On page load of Merge page, you have to explicitly set the selected option like below and then remove the value from local storage.
$(document).ready(function(){
if(localStorage.getItem("workItemID")!=null){
$("#mydropdownlist").val(localStorage.getItem("workItemID"));
localStorage.removeItem('workItemID');
}
});
Make sure in var id = $(this).attr('data-id'); id should get same value as you have in the options on the merge page.

Javascript - Remove query string from current url

I need to remove query string value from the url once submit button is clicked. Can i able to do this with jquery?
Current Url:
siteUrl/page.php?key=value
After Page submit:
siteUrl/page.php
Actually i have landing to current page from another one with query string. I need query string value when page loads first time to prefill some details. But once i submitted the form, i need to remove query string value.
I have tried like this.
$('#submit').click(function(){
var newUrl = window.location.href.replace(window.location.search,'');
window.location.href = newUrl;
return false;
});
It makes changes in url as expected. but cant able to get the posted values.
Thanks in advance :)
How about this one. Hope it helps :)
$('#myform').submit(function(event){
event.preventDefault();
var currentURL = window.location.href ;
location.href = currentURL.substring(0, currentURL.indexOf('?'));
});
index.html
<form id = "myform">
<input type = "text">
<input type = "submit" id = "submit" value = "Send">
</form>
function getQueryString(url) {
return url.split("?")[0];
}
var Url=getQueryString("siteUrl/page.php?key=value");
console.log(Url);
You may try this for getting url
Unfortunately i cant able to do it with javascript or jquery. So i go through with php redirection, now it works.
<?php
if(isset($_POST['Submit'])) {
// actions
if(isset($_REQUEST['key']) && ($_REQUEST['key'] != "")) {
header('Refresh: 1;url='.$_SERVER['PHP_SELF']);
}
}
?>
Thanks all :)

global site variable js

I am new to javascript, i am trying to make a small site with two HTML pages (A and B) and a global js file.
So lets say i have selected certain items in page A, the list-preview on Page A gets updated.
But if i want to see the list in detail i have to go to page B.
Page A and B bith use the same .js file, the selected items are saved in a array.
How do i make sure the selected items still stay in the array, and the array doesn't get flushed when i go from page A to page B ?
what i thought of was ...
var selectedProductsName = new Array();
in OwnJS.js
the adding items to the preview list works.
i'm only struggling to keep the array unflushed when i go to page B from page A.
HTML5 introduces a new thing called localStorage. It's basically some kind of storage that is persistent between all pages of your website as well as between user sessions. It can be accessed as a simple key/value store:
var selectedProductsName = localStorage.getItem("selectedProductsName");
And to set:
localStorage.setItem("selectedProductsName", []);
Here's an article about getting started with localStorage, if you want to be able to do more things like checking browser compatibility for localStorage and watching the storage event, among others.
You could use the HTML5 local storage. It lets you tell the browser to save data on the user's machine. (There's also session storage, valid only for the current session.)
Save (in Apply.html)
IN.API.Profile("me")
.fields(["id", "firstName", "lastName", "pictureUrl","headline","industry","location:(name)","positions:(title)","emailAddress"])
.result(function(result) {
profile = result.values[0];
// save all keys to local storage
for (f in profile) localStorage[f] = fields[f];
// more stuff ...
});
to Retrieve (in personal_Info.html)
// retrieve first name from local storage
var firstName = localStorage["firstName"];
if (firstName !== undefined) {
$("#textfield1").attr(value, firstName);
}
Source Page
The Source Page has an HTML Button with a jQuery Click event handler. When the Button is clicked, the values of the Name TextBox and the Technology DropDownList is set as QueryString Parameter and then the page is redirected to the Destination page (Page2.htm).
<input type="button" id="btnQueryString" value="Send" />
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
Destination Page
On the Destination page (Page2.htm), inside the jQuery Page Load event handler the URL of the page is first checked to determine whether it has some QueryString Parameters being received, this is done by checking the window.location.search property. If it has some QueryString Parameters then loop is executed and each QueryString Key and Value Pair is inserted in an Array and finally the values are displayed on the page using the HTML span.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null && queryString["technology"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"] + " <b>Technology:</b> " + queryString["technology"];
$("#lblData").html(data);
}
});
</script>

using jquery to create array of elements in a given class then selecting a random link within that class and opening it

var linksInCategory = document.id($('.CategoryTreeLabel').href);
var randomLinkArray = new Array(linksInCategory);
//CategoryTreeLabel is the class all the anchor tags have that contain the href with the link to the page I want
function goThere(link)
{
var the_url = function pickRandomURL () {
var random_url = randomLinkArray[Math.floor(Math.random()*randomLinkArray.length)];
the_url = random_url;
}
var good_url = fixURL(the_url);
var new_window = window.open(good_url,"new_window","menubar, resizeable. location, toolbar, status, scrollbars");
}
function fixURL(the_url) {
var the_first_seven = the_url.substring(0,7);
the_first_seven = the_first_seven.toLowerCase();
if (the_first_seven != 'http://')
{
the_url = "http://" + the_url;
}
return the_url;
}
</script>
</head>
<body>
<form name="the_form">
<input type="button" name="the_url" class="broadGroups" onClick="goThere(this)" src="the_url" value="Sports"></input>
<input type="button" name="the_url" class="broadGroups" onClick="goThere(this)" src="the_url" value="Film"></input>
Basically I want to create an array of all the href links within the same tag as the class="CategoryTreeLabel" Then I want to create a function goThere () that will open a new window with the URL of good_url. the_url needs to be randomly selected from the list of links we grabbed from the tags with a class of "CategoryTreeLabel" in the document.
Each of the buttons should call the goThere(this) function and pick a random URL out of the array we created, check if it has http:// (it always will redirect to a page without it, but i left it in for fun), then open that page
The return from the jQuery function is an array-like object, that is to say that it has a .length property and can be accessed with array-style [] bracket notation, so you don't really need to create a separate array variable too.
I notice that your buttons seem to be for different categories of links, like sports or film, so perhaps your intention is that the "Sports" button will select a random sports-related link while the "Film" button will select a random film-related link? If so you could have each button pass the category through to your goThere() function and select a random link from within that category. Something like this:
function goThere(category)
{
// assume that the parameter is the class name for links
// in the desired category
var $myLinks = $("a." + category);
// check if there are any matching links
if ($myLinks.length === 0) {
alert("Sorry, no links in the " + category + " category.");
return;
}
var url = fixURL($myLinks[ Math.floor(Math.random()*$myLinks.length) ].href);
var new_window = window.open(url,"new_window",
"menubar, resizeable. location, toolbar, status, scrollbars");
}
You'd then set up your anchor tags to have class names with appropriate categories, something like this:
<a class="sports" href="http://somesportssite.com">Super sports</a>
<a class="film" href="http://moviesRus.com">Movies</a>
<a class="film" href="http://animationplus.com">All about animation</a>
<a class="sports" href="http://football.com">Football site</a>
<a class="sports" href="http://skydiving.com">Let's jump!</a>
And the associated buttons would be:
<input type="button" value="Sports">
<input type="button" value="Film">
And you could set inline handlers like you had, onclick="sports", or you could do something like the following in your document.ready handler to set them all up with a single jQuery .click() call that assumes the appropriate classname/category is a lowercase version of the button label:
$('input[type="button"]').click(function() {
goThere(this.value.toLowerCase());
});

Categories

Resources