Native javascript, handle click, change url - javascript

I need to handle click event for element on native js, After click, element url must be change, (i have one of query string parameter from current page url) and next, event handle will be continue (click on element having new link) (sorry I speak english badly).
simply put i want to do changes for element and execute native handle
function handle(e) {
var vin = new URLSearchParams(location.search).get('vin');
var item_url = this.getAttribute('href');
if (!!vin) {
var char = item_url.indexOf('?') != -1 ? '&' : '?';
this.setAttribute('href', item_url + char + 'vin=' + vin);
}
}

You can update href value on DOMContentLoaded. Remove handle function.
document.addEventListener("DOMContentLoaded", function() {
var vin = new URLSearchParams(location.search).get('vin');
if (!!vin) {
var links = document.querySelectorAll('.category_link');
for (i=0; i<links.length; i++) {
var item_url = links[i].getAttribute('href');
var char = item_url.indexOf('?') != -1 ? '&' : '?';
links[i].setAttribute('href', item_url + char + 'vin=' + vin);
}
}
});
EDIT 1
If you want to do with handle then you should replace this.setAttribute('href', item_url + char + 'vin=' + vin); with location.href = item_url + char + 'vin=' + vin. Your handle function will be like below:
function handle(e) {
var vin = new URLSearchParams(location.search).get('vin');
var item_url = this.getAttribute('href');
if (!!vin) {
var char = item_url.indexOf('?') != -1 ? '&' : '?';
location.href = item_url + char + 'vin=' + vin;
}
}

Related

How can i avoid Jquery translate `?` to `%3F`

I have the follwoing Jquery code to open page on button click passing a parameter but ? is translated to %3F is there anyways to fix this?
$("#PrintDocument").click(function () {
var grid = $("#Billings").data("kendoGrid");
var row = $("input:checked", grid.tbody).closest("tr");
var item = grid.dataItem(row);
window.location.pathname = '/invoice/billing/Print' + '?productId=' + item.ProductID + '&' + 'runId=' + item.RunID;
});
You are setting the pathname which does not have a query string.
window.location.href = '/invoice/billing/Print' + '?productId=' + item.ProductID + '&' + 'runId=' + item.RunID;

Removing a string within a string using JavaScript

I am having a string like this:
"welcome country !
and some texts
Keyword1:the value
keyword2: the value2"
I want to remove keyword on undo the corresponding checkbox and also its value using Javascript. Now i could remove the keyword while undo checkbox but not the value they have entered near the keyword.
I have tried substring functions and some other, but i couldn't fix it.
my code below:
$("#txtNote").val(url.replace($(this).attr("data-id") + ":", ""));
I just want to remove the texts immediately after the ":"
here is my entire code:
if ($(this).attr("data-selected1") == "true") {
$("#detailChronic").show();
$(this).attr("data-selected1", "false");
//$(".hjk").remove(":contains('" + $(this).attr("data-id") + "')");
var url = $.trim($("#txtNote").val());
str = $("#txtNote").val();
//var t = str.substring(str.indexOf(":"))
//alert(t);
//url = url.replace(/\s+/g, "\n");
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":", ""));
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":" + $(this).attr("data-id").value(), ""));
//url.replace($(this).attr("data-id") + ":", "");
alert(url);
var temp2 = temp1.replace(/($(this).attr("data-id"))(\:(.*))/, "");
alert(temp2);
var temp1 = url.replace($(this).attr("data-id"), "");
alert(temp1);
$("#txtNote").val(temp1);
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":" + $(this).attr("data-id").value(), ""));
if ($("#selectedList").html() == "") {
$("#detailChronic").hide();
}
}
if you want to remove 'Keyword1:the value', then try
var keyWordToRemove = 'Keyword1';
var rgxStr = keyWordToRemove + ':[a-zA-Z0-9 ]*\n';
var rgx = new RegExp(rgxStr,'g');
var text = `welcome country !
and some texts
Keyword1:the value
keyword2: the value2`;
console.log(text);
text = text.replace(rgx,"");
console.log(text);
Hope it helps :)
You can try it using regex like this
var url = `welcome country !
and some texts
Keyword1:the value
keyword2: the value2`;
console.log(url.replace("Keyword1:", "test key "))
console.log(url.replace(/(Keyword1)(\:(.*))/, "$1 test value"))
you can replace Keyword1 with $(this).attr("data-id") + ":" in your code

Download of excel file is not working in Firefox but works in Chrome

I am trying to download an excel file on onclick event. It allow me to download excel file in chrome but not in Firefox. Not sure what is the issue. I am getting below error.
ReferenceError: event is not defined
Below is my javascript function
function hyperlinkFn(){
var htmlTbl="";
var htmlTbl1="";
var string = event.target.parentElement.name;
var tempString=[];
var temp= new Array();
for(var i=0;i<string.length;i++){
if(string[i]=="|"){
temp.push(tempString);
tempString=[];
}else{
tempString+=string[i];
}
}
userStoryModalRelease = temp[0];
userStoryModalPID = temp[1];
userStoryModalPrjName = encodeURIComponent(temp[2]);
userStoryModalTeam = encodeURIComponent(temp[3]);
userStoryAltId=encodeURIComponent(temp[4]);
userStoryModalStatus = temp[5];
userStoryModalTeam = userStoryModalTeam.replace(", ", ",");
var uri="getUserStoryDetails.htm?release=" + userStoryModalRelease + "&projectId=" + userStoryModalPID + "&projectName=" + userStoryModalPrjName +
"&team=" + userStoryModalTeam + "&alternateId=" + userStoryAltId + "&view=" + storyView;
var encode = encodeURI(uri);
window.location = encode;
}
HTML code where I am calling this function in the datatable
{
title : "Total Points",
data : function(data, type, row, meta) {
return data.totalSum+'<a name="'+ data.releaseNum +'|'+ data.projectId +'|'+ data.projectName +'|'+ data.team + '|'+ data.altId + '|total|'+'" onclick="hyperlinkFn()">'
+ '<i class="fa fa-file-excel-o font-size-15 " title="Click here to export details " aria-hidden="true"></i></a>';
},
className : "center storypoint yellow_fill pos-rel"
} ],
Change your click binding like below so that event will work:
$(document).on('click', '.classname', function(event){
var htmlTbl="";
var htmlTbl1="";
var string = event.target.parentElement.name;
var tempString=[];
var temp= new Array();
for(var i=0;i<string.length;i++){
if(string[i]=="|"){
temp.push(tempString);
tempString=[];
}else{
tempString+=string[i];
}
}
userStoryModalRelease = temp[0];
userStoryModalPID = temp[1];
userStoryModalPrjName = encodeURIComponent(temp[2]);
userStoryModalTeam = encodeURIComponent(temp[3]);
userStoryAltId=encodeURIComponent(temp[4]);
userStoryModalStatus = temp[5];
userStoryModalTeam = userStoryModalTeam.replace(", ", ",");
var uri="getUserStoryDetails.htm?release=" + userStoryModalRelease + "&projectId=" + userStoryModalPID + "&projectName=" + userStoryModalPrjName +
"&team=" + userStoryModalTeam + "&alternateId=" + userStoryAltId + "&view=" + storyView;
var encode = encodeURI(uri);
window.location = encode;
})
Note: remove onclick event from hyperlink and add class on hyperlink and replace that classname with .classname
Looks like this has already been covered here:
ReferenceError: event is not defined error in Firefox
WebKit follows IE's old behavior of using a global symbol for "event", but
Firefox doesn't. When you're using jQuery, that library normalizes the
behavior and ensures that your event handlers are passed the event
parameter.
function hyperlinkFn(){ needs to become function hyperlinkFn( event ){

Javascript window relocating adding unwanted parameter

I've been trying this for a lot of time now. I'm getting a value with the input and I'm trying to redirect the page by adding a new parameter and just passing dummy value 23 for now to the parameter number_range.
However, in the end in the window.location part it adds the parameter myurl/?e=1 always at the start. After that it redirects properly. How do I fix this. Please Help.
Also I'm new to javascript so please forgive my bad code and possible mistakes.
<h3>Price Filter</h3>
<input id="number_range" type="text"/><br>
<button onclick="filter_start(this,'gt'); return true;">Greater or equal</button><br>
<button onclick="filter_start(this,'ltt'); return false;">Less or equal</button>
<script language="javascript" type="text/javascript">
var filter_start = function(el, indicator){
setGetParameter("number_range", 23);
}
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf("?") >= 0)
{
var params = url.substring(url.indexOf("?") + 1).split("&");
var paramFound = false;
params.forEach(function(param, index) {
var p = param.split("=");
if (p[0] == paramName) {
params[index] = paramName + "=" + paramValue;
paramFound = true;
}
});
if (!paramFound) params.push(paramName + "=" + paramValue);
url = url.substring(0, url.indexOf("?")+1) + params.join("&");
}
else
url += "?" + paramName + "=" + paramValue;
window.location.href = url + hash;
}
EDIT: Sorry just ran it in another place and this seems to work. I Think the problem then lies in Django's admin template or jquery.
Seems that you're missing some curly bracers. I've tidied your code very slightly:
var filter_start = function(el, indicator) {
setGetParameter("number_range", 23);
}
function setGetParameter(paramName, paramValue) {
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf("?") >= 0) {
var params = url.substring(url.indexOf("?") + 1).split("&");
var paramFound = false;
params.forEach(function(param, index) {
var p = param.split("=");
if (p[0] == paramName) {
params[index] = paramName + "=" + paramValue;
paramFound = true;
}
});
if (!paramFound) params.push(paramName + "=" + paramValue);
url = url.substring(0, url.indexOf("?") + 1) + params.join("&");
} else {
url += "?" + paramName + "=" + paramValue;
window.location.href = url + hash;
}
}

Replace brackets to span javascript

I want to manipulate the DOM a bit and need some help.
That's my HTML-Markup:
<span class=“content“> This is my content: {#eeeeee}grey text{/#eeeeee} {#f00000}red text{/#f00000}</span>
That's how it should be:
<span class="content">This is my content: <span style="color:#eeeeee;">grey text</span><span style="color:#f00000;">red text</span></span>
The script should replace the brackets with span tags to change the font-color.
The color should the same that is in the bracket.
My approach:
function regcolor(element) {
var text = element.innerText;
var matches = text.match(/\{(#[0-9A-Fa-f]{6})\}([\s\S]*)\{\/\1\}/gim);
if (matches != null) {
var arr = $(matches).map(function (i, val) {
var input = [];
var color = val.slice(1, 8);
var textf = val.slice(9, val.length - 10);
var html = "<span style=\"color: " + color + ";\">" + textf + "</span>";
input.push(html);
return input;
});
var input = $.makeArray(arr);
$(element).html(input.join(''));
};
But it's not working very well and i'm not feeling good with the code, it looks messy.
And the script looses the content that's not in the brackets("This is my content:").
Anyone a idea?
I've used just a touch of jQuery, but it could easily do without. It's just a regular expression string replacement.
$('.content').each(function() {
var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g;
// ^ ^
// $1 $2
this.innerHTML = this.innerHTML.replace(re, function($0, $1, $2) {
return '<span style="color: ' + $1 + '">' + $2 + '</span>';
});
});
I'm using a back-reference to properly match the opening and closing braces.
Update
Could be even shorter:
$('.content').each(function() {
var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g,
repl = '<span style="color: $1">$2</span>';
this.innerHTML = this.innerHTML.replace(re, repl);
});
Look mum, no jQuery
var nodes = document.getElementsByClassName('content');
for (var i = 0, n = nodes.length; i < n; ++i) {
var re = /\{(#[a-z0-9]{3,6})\}(.*?)\{\/\1\}/g,
repl = '<span style="color: $1">$2</span>';
nodes[i].innerHTML = nodes[i].innerHTML.replace(re, repl);
}
Use the regex to replace the matches directly:
function regcolor2(element) {
var text = element.html();
var i = 0;
var places = text.replace(/\{(#[0-9A-Fa-f]{6})\}([\s\S]*)\{\/\1\}/gim, function( match ) {
var color = match.slice(1, 8);
var textf = match.slice(9, match.length - 10);
var html = "<span style=\"color: " + color + ";\">" + textf + "</span>";
return html;
});
$(element).html(places);
}
it can be shorter with jquery and this method or syntax
$(function() {
$('.content').html($('.content').text().replace( new RegExp('{(.*?)}(.*?){\/.*?}','g'), '<span style="color:$1">$2</span>'));
});

Categories