url formatting using jquery and codeigniter - javascript

I have xxx.com and six input fields in a page. If user enter values in the input field I want the URL to be like xxx.com/1st value-2nd value-3rd value-etc
Now I am getting the input values in jQuery and passing those values to the URL but I could pass a single value and not all. Here's my code.
$(".search").on("click",function(e){
// var action = $(this).attr("id");
var skill = $(":input[name='searchskill']").val();
var location = $("#searchlocation").val();
action = skill + "-" + location;
location.href = action;
e.preventDefault();
});

use '/' instead of '-' and get the url parameters in php function like
function($skill='',$location=''){
}
and now script will be like
$(".search").on("click",function(e){
var skill = $(":input[name='searchskill']").val();
var location = $("#searchlocation").val();
action = skill + "/" + location;
location.href = action;
e.preventDefault();
})

Try this one
$(".search").on("click",function(e){
// var action = $(this).attr("id");
var skill = $(":input[name='searchskill']").val();
var location = $("#searchlocation").val();
action = skill + "/" + location;
window.location.href = action;
e.preventDefault();
});
EDIT
Now I have created plunker for you please edit or suggest what you not getting in it, you also edit that plunker and give me new link to it
here is DEMO

Related

Appending current URL parameters onto anchor link

At a page like
https://www.example.com/?firstname=Steven&lastname=Smith&email=steve%40gmail.com&phone=0404555555
I have a button (anchor link) #ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell that links to https://www.example.com/form
I'd like to append the URL parameters from the current URL to the button's URL, so that the button's href is now https://www.example.com/form/?firstname=Steven&lastname=Doig&email=steve%40gmail.com&phone=0404555555
How can I do this with JavaScript please?
Use window.location.search:
var url = "https://exmaple.com";
var newurl = url + window.location.search;
newurl will contain all the get (ex. ?something=something&something2=something5) data.
To change the href of a:
var button = document.getElementById('#ptsBlock_553944');
button.href = button.href + window.location.search;
If you don't care about supporting older browsers you can use the URL API and URLSearchParams.
function appendCurrentUrlSearchParams(anchorElement) {
const currUrlSearchParams = new URL(window.location.href).searchParams;
const link = new URL(anchorElement.href);
// uncomment this line if you want to clear query parameters already present in the anchor url
// link.search = '';
for (const entry of currUrlSearchParams.entries()) {
link.searchParams.append(entry[ 0 ], entry[ 1 ]);
}
anchorElement.href = link.href;
}
Usage in your case:
appendCurrentUrlSearchParams(document.querySelector('#ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell'));
Read Html select using select to change the link of a button with Javascript
specifically the section on
Get the element with something like document.getElement MDN getElement Link
Change the .href of that element to what you want.
function selectFunction() {
var x = document.getElementById("selectopt").value;
document.getElementById("mylink").innerHTML = x;
document.getElementById("mylink").href = "http://www." + x + ".com";
}
document.location.pathname = '/questions/69240453/appending-
current-url-parameters-onto-anchor-link/69240510';
//get the document pathname I chose from document.location
let data = document.location.pathname;
let preUrlString = 'www.example.com/form';
let newString = preUrlString + data;
console.log(newString);
'www.example.com/form/questions/69240453/appending-
current-url-parameters-onto-anchor-link/69240510'
document.getElementById("mylink").href = newString;

How to remove last url location hash using javascript

Am using bootstrap modal on my site, everything a modal is open it will add url has using the modal element id and a data i passed.
My problem is how do i remove the last added hash when a button is clicked just like when browser back button is click window will navigate back removing last hash.
How do i remove last url location has accordingly using javascript, i want every time a button is clicked the last hash from the list of url hash will be removed.
function ensureHash(newHash){
var lochash = location.hash;
if(lochash || lochash != ""){newHash = lochash + "&" + newHash;}
if (window.location.hash) {
return window.location.href.substring(0, window.location.href.lastIndexOf(window.location.hash)) + newHash;
}
return window.location.hash + newHash;
}
window.location.href = ensureHash("modalElementId=modalAction");
https://example.com/app?#mElem1=mAcct1&#mElem2=mAcct2&#mElem4=mAcct5
I tried doing this but it doesn't work well
function ensureRemoveHash(){
var gethash = location.hash;
gethash = gethash.slice(0, gethash.lastIndexOf('&'));
return gethash;
}
window.location.href = ensureRemoveHash();
Something like this?
var str = "https://example.com/app?#mElem1=mAcct1&#mElem2=mAcct2&#mElem4=mAcct5"
function dropHash(str) {
if (str.indexOf("#") ==-1) return str;
var arr = str.split("#");
arr.pop();
return arr.join("#");
}
console.log(str);
str = dropHash(str)
console.log(str);
str = dropHash(str)
console.log(str);
str = dropHash(str)
console.log(str);
Or do you just have the button replace the hash?
var url = new URL("https://example.com/app")
console.log(url);
url.hash="mElem2=mAcct2"
console.log(url);
url.hash="mElem3=mAcct3"
console.log(url);

Replace elements in a link using javascript

I have a link to add event to google calendar which is populated from a database, but the date is formatted yyyy-mm-dd, and the time hh:mm, and i cannot alter this, but google calendar will not accept.
Can anyone please help me use javascript and the 'replace' function to remove the'-' and ':' from the html please?
<a href="http://www.google.com/calendar/event?
action=TEMPLATE
&text=Tester12
&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z
&details=Oranges
&location=Newquay
&trp=false
&sprop=
&sprop=name:"
target="_blank" rel="nofollow">Add to my calendar</a>
many thanks.
Fetch the href link from tag and store it in a variable.
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Tester12&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z&details=Oranges&location=Newquay&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
This will remove all the '-' and ':' from dates parameter string and will store that link in 'finalLink' var.
Hope it helps.
I have been on the sniff for the whole code solution, and witha bit of mix and match, came up with this, AND IT SEEMS TO WORK!!!!!! But please feel free to edit into perfection!
<script>
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Example Event&dates=2018-12-16T10:3500Z/2018-12-16T12:0000Z&details=Trip to town&location=No mans land&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
</script>
Add Event
<script>
(function() {
Array.prototype.forEach.call(document.querySelectorAll("a.finalLink"), function(link) {
link.href = finalLink;
});
})();
</script>

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.

Using the parameter passed by URL in JavaScript

I need to add a 'Send Message' button which takes the username of the user that message will be sent to, goes to a link and put this username to the 'To' field of the message form.
This is my code
function sendmessage() {
var x;
//geting the username
x = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
var x = x.substring(x.indexOf(":") + 1);
//passing the username parameter by URL
window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;
//to get the username parameter from URL on new page
var z=window.location.search.substr(1);
//to get rid of some part of the username parameter
var a = z.substring(z.indexOf("0") + 1);
a = a.substring(0, a.length - 8)
//to put the username to 'To' field
document.getElementById("search-q").value= a;
}
Now the problem is that the new page is opened with the parameter. And as a seperate case I can get a parameter from a URL then put it in a field. But I cannot do these two together.
Thanks for the answers!
What you are trying to do is impossible.
As I said in my comment you are navigating away from the page when you set the location. The code after that will not run on the next page. That code needs to live on the next page. That code would have to be executed on page load or document ready.
ok. thanks for the answers. I solve the issue and it works. I am posting the code to help anyone struggling on this problem like me.
The code is divided into two pieces.
<script>
function sendmessage() {
var y;
//geting the username
y = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
var x = y.substring(y.indexOf(":") + 1);
//passing the username parameter by URL
window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;
}
</script>
<script>
//code running after page-load
window.onload = function() {
var z=window.location.search.substr(1);
var a = z.substring(z.indexOf("0") + 1);
a = a.substring(0, a.length - 8)
document.getElementById("search-q").value= a;
}
</script>

Categories