Extract characters after ?= in link - javascript

Can anyone see where I going wrong here, I'm trying to get the last characters after the ?p= in a link and put in a varaible, but the code I'm using returns /.
My code is:
$("#dvPartial").on('click', '.dvPagerCities a', function (event) {
alert('click detected');
var city = ($('input#hdnCountry').val());
alert(city);
var link = $('a').attr('href');
//var getEqualPosition = link.indexOf('?p='); //Get the position of '='
var getEqualPosition = link.indexOf('='); //Get the position of '='
var number = link.substring(getEqualPosition + 1); //Split the string and get the number.
My link is
»
I think what is happening is its picking up the 1st = .
My theory is this.
1) Detect the click event
2) Get the link that caused the event
3) Extract the value of p,
p can be 1 diget, 2 digets or 3 digets.
Any help would be appreciated, as it seems no sooner do I solve 1 problem then another arises.
Thanks
George

Assuming that p is the only parameter in the URL you can simply split by the = sign:
$("#dvPartial").on('click', '.dvPagerCities a', function (event) {
var city = $('input#hdnCountry').val();
var number = $(this).attr('href').split('=')[1];
});

The problem is this part:
var link = $('a').attr('href');
That does not select the link that was clicked, unless you happen to be clicking the very first link present in the HTML of the page. What that will do is select all <a> elements, then return the href attribute of the first one.
Inside your event handler, you want to use this to refer to the link that was clicked:
var link = $(this).attr('href');
// or simply
var link = this.href;

Try with this:
link.split('?p=')[1]

String s = "Jecy penny ? like sears";
String[] arr = s.split("\\?");
Added \\ before ?, as ? has a special meaning
String res = arr[0];
May be you are wrong at escape character for ' ? '
check this link Remove all characters after a particular character

Try this: http://jsfiddle.net/7atyG/1/
$(document).on('click', '.dvPagerCities a', function (ev) {
ev.preventDefault();
var link = $(this).attr('href');
var Linkval = link.substr(link.indexOf('=') + 1);
alert(Linkval);
});

Related

Passing a variable inside a Set attribute value

Can someone please let me know if it is possible to pass a variable inside a "setAttribute" to make an input value appear in an href link?
For example I have :
var inputNumber = document.getElementById('inputNumber').value;
var validateBtn = document.getElementsByTagName("a"); //a surrounding n button
var linkValidation = validateBtn[0].href = ("https://checkyournumber.com.action?inputNumber=" + inputNumber );
so far so good, if i console.log linkValidation, i do have the full link with the input number at the end as intended.
However when i try to set the href attribute to the a tag in the html using the below :
document.getElementsByTagName("a")[0].setAttribute("href", "https://checkyournumber.com.action?inputNumber=" + inputNumber );
Then the link the user is taken to is : https://checkyournumber.com.action?inputNumber=
I have tried entering inputNumber inside the "" but then of course it is displayed as such in the URL. I have tried with '' instead... no luck.
Would someone know if it is possible at all?
Thank you very much for your support in advance!
Try as follows
(function() {
var inputNumber = document.getElementById('inputNumber').value;
var validateBtn = document.getElementsByTagName("a"); //a surrounding n button
var linkValidation = validateBtn[0].href = ("https://checkyournumber.com.action?inputNumber=" + inputNumber );
});

How to change a URL parameter on a link that has # as href and is submitted inside a form

I'm working on a drupal module and it gets images from an API, adds selectable search-filters and generates pagination. If I go to e.g. the 7th pagination page and add a filter that only spans 3 pages it will result in not showing anything at all.
Solution: on upon adding a filter, go back to the 1st page. Now is my problem that that page is an url parameter and the links made by the filter are set to href='#' so basically this page yes.
So I try to debug the javascript that handles the on click:
$('#blabla .filter-url').click(function(e) {
e.preventDefault();
var link = $(e.currentTarget);
console.log(link);
var filter_key = link.data('filter-key');
var filter_value = link.data('filter-value');
// var active = link.hasClass('active');
var filters_input = $('#blabla input[name="filters"]');
var current_filters = JSON.parse(filters_input.val() || '{}');
current_filters.filters = current_filters.filters || [];
var exists = ($.grep(current_filters.filters, function(e, i){
return e.key == filter_key;
}).length);
if (exists) {
//Remove current filter from list
current_filters.filters = $.grep(current_filters.filters, function(e, i){
return e.key != filter_key;
});
link.removeClass('active');
}
// Add current filter to list
current_filters.filters.push({
key: filter_key,
value: filter_value,
});
link.addClass('active');
filters_input.val(JSON.stringify(current_filters));
$('#formname').submit();
});
the link object:
The link object has a {0, context and length} object in which both 0 and context contain multiple instances of the url, which one should I edit?
I just want to manipulate the URL / get parameter page=xxx to be page=0, so it goes back to the 1st page. How to achieve this?
I was searching in the wrong place. At the end of the onclick-function it submits the form. I had to change the action of this form like this:
var old_form_action = $('#formname').attr('action');
var new_form_action = old_form_action.replace(/(page=)[^\&]+/, '$1' + '0');
$('#formname').attr('action', new_form_action);

How to get the text after the # symbol in a link?

I have a simple link with a hashtag in it. ie:
<a class="page_navigation" href="#something">click</a>
On clicking this, I would like to just end up with the 'something' part (minus the hash) in a var.
So far I have
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
});
Obviously I just end up with '#something' in my href var with the above code, and I understand I could do some kind of regex (not sure how yet) to strip the #, but I wonder if there is an easier way to access this part of the href I'm unaware of, without having to go through some find and replace code.
Any ideas?
Note: I also know I could store the 'something' in a data tag, but I'm trying to keep this code as DRY as possible.
If you know it has a # in it, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = this.href.replace(/^.*#/, "");
});
If you don't know whether it has one it it or not, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = "";
if (this.href.indexOf("#") {
hash = this.href.replace(/^.*#/, "");
}
});
In HTML5, you could use:
this.hash
but that is only for the latest browsers.
var theHash = $(this).prop("hash").substr(1);
Related answer to another question
Demo http://jsfiddle.net/UR3XN/
code
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
var equalPosition = href.indexOf('#'); //Get the position of '#'
var withouthash = href.substring(equalPosition + 1);
alert(withouthash);
});​
You don't need regular expressions for this. You can simply do
var fragment;
if (window.location.hash) {
fragment = window.location.hash;
}
Note that this will pick up the # symbol as well. So,
fragment = "#something"
If you don't want the # symbol, use substring like this:
fragment = window.location.hash.substring(1)
If you want to pick out the hash fragment from an anchor tag, you can do this:
var link = $('#yourAnchor').attr('href');
var fragment;
if (link.indexOf("#") !== -1) {
fragment = link.substr(link.indexOf("#") + 1);
}

Javascript Error: this.replace($foo, "");

My sixth line of code does not work. Please help.
function ajax() {
$('a[class="ajax-cw"]').click( function() {
$('#cw').load( this + "?ajax" );
$('#nav li.current').removeClass('current');
var $base = $("base").attr("href"),
$link = this.replace($base, ""); //Line does not work
alert ($link);
return false;
});
};
if you were trying to replace parts of the href contents of the currently clicked link with that of the base object, you have to access the href contents via
var currenthref = $(this).attr('href');
and then use currenthref in the replace line.
$link = currenthref.replace($base, "");
Thre replace function on this will not properly work because it is not a string but rather an object (most likly jquery) that represents the link element you klicked on.
try this:
this.href.replace($base, '');
this in line 6 is the <a /> tag, not the href of that tag. $(this).attr('href').replace($base,"") will perform better.
You need to end the previous line with a semi-colon. You have ended it with a comma.
var $base = $("base").attr("href");

The first letter of each <h3> into a hyperlink

Using javascript I'm looping through my H3 elements like this:
$('h3').each(function(){ });
I'm then generating an anchor for that tag formatted like this: "section-x" where x increments for each H3 on the page. The problem I have is that I'd like the first letter of the header to be an anchor link, like this:
*H*eading
.. where H is underlined, representing a link. I can format the anchors however I don't know how to wrap a hyperlink tag around the first letter in each heading. Some help would be greatly appreciated.
Regards,
kvanberendonck
Something like this?
$('h3').each(function(){
var currentHeading = $(this).text();
$(this).html("<a href='link'>" + currentHeading.substr(0,1) + "</a>" + currentHeading.substr(1, currentHeading.length - 1));
});
Let's throw some plain javascript into the mix:
$('h3').html(function(i){
var self = $(this)
, html = self.html()
return html[0].anchor('section-'+i) + html.substring(1)
})
html (and most other setter functions) accepts a function as an argument and uses the return value for each element
"string".link(target) creates the code string. A nice vintage useful method
edit: switched from .link to .anchor. Anchors are deprecated though, you should start using IDs for that:
$('h3').html(function(i){
var self = $(this)
, text = self.text()
// give the H3 an id and link to it
// ideally the headers should already have an id
this.id = 'section-'+i
return text[0].link('#section-'+i) + text.substring(1)
})
$('h3').each(function(i){
var firstLetter = $(this).text()[0];
$(this).html('' + firstLetter + '' + $(this).text().substr(1));
});
Not sure where you'd like to put section-x in that heading, but you can use i inside that each() to get the current iteration index.

Categories