How to dynamically change a text from URL input? - javascript

I want something like that..
https://pl.sports-streams-online.best/?st=nbastream.tv&plcm=db&q=Raptors+vs+Lakers
See that URL part q=Raptors+vs+Lakers, If i input any text on this section it will automatically change on website body. I want to know how i can do this. I will input a text in URL and it will display on website body.
Thanks for advance.

You can parse window.location and put that into a div on your page. I can't show you in a code snippet because the snippets use an iframe but if your html has <div id='uText'></div> then you can use javascript (after the page has loaded) to set the value of that div with results of the query param. lets say your url ends in ?st=nbastream.tv&plcm=db&q=Raptors+vs+Lakers, then you want the value for parameter 'q':
function getQueryStringParam(param) {
var url = window.location.toString();
url.match(/\?(.+)$/);
var params = RegExp.$1;
params = params.split("&");
var queryStringList = {};
for(var i = 0; i < params.length; i++) {
var tmp = params[i].split("=");
queryStringList[tmp[0]] = unescape(tmp[1]);
}
return decodeURIComponent(queryStringList[param]);
}
let qParam = getQueryStringParam('q').split('+').join(' ');
const div = document.getElementById('uText');
div.innerHTML = qParam;
Check out the codepen here.

Related

i have problem with multiple form with the same id with google tag manager

Hi i have many forms inside multiple pages all of them the with the same id (success message) after submitted and same class names when i'm sending the form which e.g inside home page i put element selector through id with Page PATH with match regex something like that \/(en|es)\/ it works good without problem ... but when i'm going to page www.something.com/send-something/233?search=profile the form submitted through old id which was for home page i tried to inject custom javascript something like :
function() {
var els = document.querySelectorAll('#sendReqSurgyForm1');
for (var i = 0; i < els.length; i += 1) {
if (els[i] === {{Page URL}}) {
return i;
}
}
return '(nothing sent)';
}
with adding matching Page URL with match regex something like that to https:\/\/www\.something\.com\/(ar|en)\/send-something\/[0-9]+\?source=[a-zA-Z]+\_?[a-zA-Z]+
to matching the url: www.something.com/send-something/233?search=profile
the trigger always works with home page but trigger which located in www.something.com/send-something/233?search=profile not success and the result of javascript always returns nothing sent .. please help to fix this problem
Hi the Answer is SPA Angular using SPA so it can be multiple form with the same component so i solved this problem through setting id for every form with different urls
for example if you have multiple forms in angular inside multiple routing page as i explained in the main topic question .. to fix this problem you can setting id for every form submissions through js by setting new id for every form submission by setting Attribute for id based different urls.
main_id = exampleForm
function(){
var ids = document.getElementById("exampleForm");//main id
var current_url = window.location.href;//current url of visitor
var dir_match = location.pathname+location.search;//the path of website after .com
var send_req = 'https://www.example.com/'+dir_match.match(/[ar][r]|[en]n/)+'/surgery-request/'+dir_match.match(/[0-9]+/)+'?source=profile';//link1 which have form1
var send_req2 = 'https://www.example.com/'+dir_match.match(/[ar][r]|[en]n/)+'/surgery-request/'+dir_match.match(/[0-9]+/)+'?source=profile2';//link2 which have form2
var home_url = 'https://www.example.com/'+dir_match.match(/[ar][r]|[en][n]/)+'/';//link3 which have form3
if(current_url == send_req){
/* if current_url equal to link1 set new id e.g = `forms_req_surgery` */
last_send_req = ids.setAttribute("id", "forms_req_surgery");
var elm = document.getElementById('forms_req_surgery');
var last_var = elm.id;/* get the name of id */
return last_var; // return the name of id after changed set
}else if(current_url == home_url){
last_home_url = ids.setAttribute("id", "home_req");
var elm2 = document.getElementById('home_req');
var last2_var = elm2.id;
return last2_var;
}else if(current_url == send_req2){
last_send_req2 = ids.setAttribute("id", "forms_req_surgery2");
var elm3 = document.getElementById('forms_req_surgery2');
var last3_var = elm3.id;
return last3_var;
}
}

JS exstract part of URL from multiple form fields

I have a form that has multiple fields all with the same class. These are populated with URL's that follow the same structure. I am trying to extract the same section from each URL. So far var res = x.split('/')[5]; will achieve this but only for the first URL. I can also use var x = document.querySelectorAll(".example") to change all the url's but I cannot find the correct way to combine both of these function. so far my code looks like this:
script>
function myFunction() {
var x = document.querySelectorAll(".example").innerHTML;
var res = x.split('/')[5];
var i;
for (i = 0; i < x.length; i++) {
x[i].innerHTML = res;
}
}
</script>
I have looked around but can't find a solution that fits. Thanks in advance for your help.
So loop over the HTML Collection, this is making assumptions based on code.
// Find all the elements
var elems = document.querySelectorAll(".example")
// loop over the collection
elems.forEach(function (elem) {
// reference the text of the element and split it
var txt = elem.innerHTML.split("/")[5]
// replace the text
elem.innerHTML = txt
})
<div class="example">1/2/3/4/5/a</div>
<div class="example">1/2/3/4/5/b</div>
<div class="example">1/2/3/4/5/c</div>
<div class="example">1/2/3/4/5/d</div>
<div class="example">1/2/3/4/5/e</div>
<div class="example">1/2/3/4/5/f</div>

Javascript-Using Parsed Data From a Query String as a Heading

I am wondering how to take the information from a parsed query string and use it to display on the top of my page. Ignore the window.alert part of the code, I was just using that to verify that the function worked.
For example: If the user had choices of Spring, Summer, Winter, and Fall, whichever they chose would display a a header on the next page. So if (seasonArray[i]) = Fall, I want to transfer that information into the form and display it as a element. I'm sure this is easily done, but I can't figure it out. Thanks, in advance.
function seasonDisplay() {
var seasonVariable = location.search;
seasonVariable = seasonVariable.substring(1, seasonVariable.length);
while (seasonVariable.indexOf("+") != -1) {
seasonVariable = seasonVariable.replace("+", " ");
}
seasonVariable = unescape(seasonVariable);
var seasonArray = seasonVariable.split("&");
for (var i = 0; i < seasonArray.length; ++i) {
window.alert(seasonArray[i]);
}
if (window != top)
top.location.href = location.href
}
<h1 id="DynamicHeader"></h1>
Replace the alert line with:
document.getElementById("DynamicHeader").insertAdjacentHTML('beforeend',seasonArray[i]);

jQuery insert/remove text at specific position in input field/textarea

I am trying to do similar thing as YouTube has when you are embeding a video and you want to get a code. You can click on checkboxes or select size and it dynamically changes the value of input field.
Does somebody have idea how to do it?
I managed to write a code that is replacing the width correctly, but I dont know how to make a code that would add &scheme=XXX at the end of the link or remove it if user selects no color scheme.
This is the code for width,I dont think its best one, but works:
$("#width").on("change keyup", function(){
var width = $(this).val();
if (width){
$("#embed-text").val($("#embed-text").val().replace(/ (width\s*=\s*["'])[0-9]+(["'])/ig, ' width=\''+width+'\''));
}
});
Here is textarea which I am trying to change and inputs I'm using for it:
The ID is taken from PHP, in actual textarea that jQuery sees the ".$id." is actual number
<textarea class='clean' id='embed-text'><iframe src='http://my.url/embed/?r=".$id."' width='600' height='".$height."' frameborder='0' marginwidth='0' marginheight='0' allowtransparency='true'></iframe></textarea>
<div style='padding-right: 10px; display: inline-block;'>
Color scheme:
<select id='schemes' class='clean'>
<option value='-'>None</option>
<option value='xxx'>Xxx</option>
</select>
</div>
<div style='padding-right: 10px; display: inline-block;'>
Width: <input type='number' min='250' max='725' value='600' id='width' class='clean'>
</div>
When user does not select any scheme (or changes from XXX to None), I want link in textarea (iframes src) to be like this:
http://my.url/embed/?r=X
But when he selects any scheme, i would like it to look like this:
http://my.url/embed/?r=X&scheme=XXX
I actually have no idea how to do this. Tried googling for more than hour, but I don't know what the ID will be (to identify position where to add the string), thats PHP value and I cant pass it to external script file, so I tried to find if I can insert something at specific position (ie.: 15th character from start) with JS, but could not find anything.
Thanks.
I separate some functions in order to keep the code clean check this I think that is what you were looking for JsFiddle
var generateUrl = function(id,colorScheme) {
var baseUrl = "http://my.url/embed/?";
var url = baseUrl.concat("r="+id);
if (colorScheme != null && colorScheme != '')
url = url.concat("&scheme="+colorScheme);
return url;
};
var changeUrl = function(id, colorScheme) {
var url = generateUrl(id, colorScheme);
var srcPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(srcPattern),"src='"+url+"'");
$("#embed-text").val(newEmbedText);
};
var changeWidth = function(newWidth) {
var widthPattern = "width='([0-9]*)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(widthPattern),"width='"+newWidth+"'");
$("#embed-text").val(newEmbedText);
};
var getURLParameter = function(url,parameterName) {
return decodeURIComponent((new RegExp('[?|&]' + parameterName + '=' + '([^&;]+?)(&|#|;|$)').exec(url)||[,""])[1].replace(/\+/g, '%20'))||null
};
var getId = function() {
var urlPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var url = embedText.match(new RegExp(urlPattern))[1];
var id = getURLParameter(url, 'r');
return id;
};
$("#width").on("change keyup", function(){
var width = $(this).val();
var colorScheme = $(schemes).val();
changeWidth(width);
changeUrl(getId(),colorScheme);
});
And i removed the value '-' for the first option just leave it in blank.

write GET URL variable to page using javascript

I have a form which contains a wysiwyg editor. The form data is sent to a page using a GET method in the form.
How would i decode(to keep the DIV and BR tags) in the variable and print it out on the page using Javascript?
Any help would be appreciated
The equivalent of decode would be unescape(), you should be able to something like this:
(function(){
document.$_GET = [];
var urlHalves = String(document.location).split('?');
if(urlHalves[1]){
var urlVars = urlHalves[1].split('&');
for(var i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
var urlVarPair = urlVars[i].split('=');
document.$_GET[urlVarPair[0]] = urlVarPair[1];
}
}
}
})();
document.write(unescape(document.$_GET['varname']));
Maybe you should try this script: http://www.webtoolkit.info/javascript-url-decode-encode.html
It encodes decodes everything.

Categories