Change href value using jQuery - javascript

How do I rewrite an href value, using jQuery?
I have links with a default city
parks
malls
If the user enters a value into a #city textbox I want to replace Paris with the user-entered value.
So far I have
var newCity = $("#city").val();

Given you have unique href values (?what=parks, and ?what=malls) I would suggest not writing a path into the $.attr() method; you would have to have one call to $.attr() for each unique href, and that would grow to be very redundant, very quickly - not to mention difficult to manage.
Below I'm making one call to $.attr() and using a function to replace only the &city= portion with the new city. The good thing about this method is that these 5 lines of code can update hundreds of links without destroying the rest of the href values on each link.
$("#city").change(function(o){
$("a.malls").attr('href', function(i,a){
return a.replace( /(city=)[a-z]+/ig, '$1'+o.target.value );
});
});
One thing you may want to watch out for would be spaces, and casing. You could convert everything to lower case using the .toLowerCase() JavaScript method, and you can replace the spaces with another call to .replace() as I've down below:
'$1'+o.target.value.replace(/\s+/, '');
Online Demo: http://jsbin.com/ohejez/

$('a').attr("href", "/search/?what=parks&city=" + newCity);

As soon as a key is released within the #city input field, the href will be updated.
$('#city').keyup(function(){
$('a').attr('href','/search/?what=parks&city='+$(this).val());
});

Like this:
var newCity = $("#city").val();
$('a').attr('href', '/search/?what=parks&city=' + newCity);
EDIT: Added the search string

Related

How to find a specific link from an href using JavaScript?

This is my first experience with JS, so please forgive the noob question.
I'm trying to make a userscript for a phpBB forum that'll allow me to automatically bookmark every topic I create.
My approach is to add an onclick listener to the submit button.
I'll use the code found in another question:
var submit = document.getElementsByTagName('input')[0];
submit.onclick = function() {
;
}
Before that though I want to find a link to bookmarking the topic in one of the hrefs on the page and store it as a variable.
I know that it will always take the form of
<a href="./viewtopic.php?f=FORUM_NUMBER&t=TOPIC_NUMBER&bookmark=1&hash=HASH"
The final code should look something like (hopefully it's the correct form)
var link = THE LINK EXTRACTED FROM THE MATCHED HREF
var submit = document.getElementsByTagName('input')[0];
submit.onclick = function() {
setTimeout(function(){ window.location.href = 'link'; }, 1000);
}
My issue is I don't know how to approach locating the href that I need and getting the link from it. Haven't found any similar questions about this.
Thanks in advance for any help
Maybe something like this?
var anchors = document.getElementsByTagName('a'); // get all <a> tags
var link = '';
if (anchors) {
// getAttribute(attributeName) gets the value of attributeName (in your case, the value of 'href' attribute
// .map(), .find() and .filter() are available methods for arrays in JS
// .startsWith() is an available method for matching strings in JS.
// You can even experiment with other regex-based string matching methods like .match()
// Use one of the following lines, based on what you require:
// to get the first matching href value
link = anchors.map(anchor => anchor.getAttribute('href')).find(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
// to get all matching href values as an array
link = anchors.map(anchor => anchor.getAttribute('href')).filter(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
}
Since you're not new to coding, check out this documentation if you're new to JS :)
Happy coding!
You can try document.getElementsByTagName("a"); which returns a collection of all the <a></a> loaded in the dom.
Then you can find it in the list and and use .href to get it's href attribute.

Is there a way to remove a specific value from an attribute using jquery?

I have a page that displays products. In the encompassing <ul> I have some jQuery that adds values to attributes (such as <ul id="products" subcategorynavids="someValue">).
When a user clicks a filtering link, the jQuery checks the contents of subcategorynavids and then only displays products below that have a navid that is listed.
What I'm having an issue with is when the attribute has more than one value listed, and the user clicks the filter link a second time (to disable it), I need to remove ONLY the value that is being disabled...
For example, if the page is set to <ul id="products" subcategorynavids="9007 8019 7365"> and the user clicks the filter that enables/disables navid="8019", how do I remove the '8019' and leave the '9007' and '7365'?
I know there is .removeAttr(), .removeProp(), but those only remove the attribute ENTIRELY (right?).
I tried the following (which, as expected, didn't work)...
$("#products").attr('subcategorynavids').remove('8019');
There's no built-in jQuery way to do this, you'll have to do it manually.
$('#products').attr('subcategorynavids', function (_, val) {
return jQuery.grep(val.split(' '), function (val) {
return val !== '8019';
}).join(' ');
});
Here we use the callback way of using attr() to update an attribute. Inside the function, we split the current value val by ' ', and then filter the resulting array for those that aren't 8019 using jQuery'sgrep() function*, and the join the array back together and return it to be the new value of subcategorynavids.
* I'd want to use Array's filter() method, but it's not supported in all modern browsers, so you might as well use grep().
In this case, you could just use .replace()
var $attrs = $("#products").attr('subcategorynavids');
$("#products").attr( 'subcategorynavids', $attrs.replace( '8019', '' ));
use .replace()
$("#products").attr('subcategorynavids',$("#products").attr('subcategorynavids').replace('8019 ',''));
http://jsfiddle.net/laupkram/fg3dn/
Try this
var attr = $("#products").attr('subcategorynavids');
$("#products").attr('subcategorynavids', attr.replace('8019',''));
First get the values in that attribute and filter out the key word and again set the new attribute.. simple as that

Extracting values from Array with Javascript

I am having issues with getting exactly values with Javascript.
Following is working version of when we have class on single item.
http://jsfiddle.net/rtnNd/
Actually when code block has more items with same class (see this: http://jsfiddle.net/rtnNd/3), it picks up only the first item which use the class name.
My issue is that I would like to pick up only the last item which use the class name. So I used following code:
var item = $('.itemAnchor')[6];
var href = $($('.hidden_elem')[1].innerHTML.replace('<!--', '').replace('-->', '')).find(item).attr('href');
But it doesn't work though. I don't really know why.
The code that may contains items are using same class, class may be use in 2 items, 3 items, or 6th times. That's why, I want to pick up only the last item to extract.
Can you explain, thank you all for reading my question.
"My issue is that I would like to pick up only the last item which use the class name."
OK, so in a general sense you would use the .last() method:
var lastItem = $('.itemAnchor').last();
Except that there are no elements in the DOM with that class because (in your fiddles) they're all commented out. This is also the reason why the code you showed in your question didn't work. The first line:
var item = $('.itemAnchor')[6];
...sets the item variable to undefined. The selector '.itemAnchor' returns no elements, so $('.itemAnchor') is an empty jQuery object and it has no element at index 6.
You need to use the '.itemAnchor' selector on the html that you get after removing the opening and closing comments with your .replace() statements, so:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor').last().attr('href');
Demo: http://jsfiddle.net/rtnNd/4/
EDIT in response to comment:
"How can we pick up the itemElement before that last one."
If you know you always want the second-last item use .slice(-2,-1) instead of .last(), as shown here: http://jsfiddle.net/rtnNd/5/
Or if you know you want whichever one has an href that contains a parameter h= then you can use a selector like '.itemAnchor[href*="h="]' with .find(), in which case you don't need .last() or .slice():
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor[href*="h="]').attr('href');
Demo: http://jsfiddle.net/rtnNd/6/
Note though that this last method using the attribute-contains selector is picking up elements where the href has the text "h=" anywhere, so it works for your case but would also pick up hh=something or math=easy or whatever. You could avoid this and test for just h= as follows:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor')
.filter(function() {
return /(\?|&)h=/.test(this.href);
}).attr('href');
Demo: http://jsfiddle.net/rtnNd/7/

How do I concatenate a string with a variable?

So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!

Locating text and performing operation based on its existence

I'm trying to learn jQuery, but it's coming slowly as I really don't know any JavaScript.
My site is in VB.NET and I'm putting jQuery code on both my actual .ascx UserControl and in a separate file (something like myscripts.js). This is because I'm using webforms as I still don't know MVC well enough to implement it, so I have to get the clientID's on the page.
What I would like to do is the following:
Grab text from a textbox and make it all lowercase
Get the username from the login info. I've done this like so on my actual page:
var userName = "<%=Split(System.Web.HttpContext.Current.User.Identity.Name.ToLowerInvariant, '|')%>";
Check to see if the username is in the text. If it IS in the text, I want to set a variable to "false", othewise to true.
How do I do this?
I am completely ignorant of the ASP.NET side of it, but as far as jQuery and Javascript....
To get the value of a text field, you use the jQuery function val():
var value = $('#mytextbox').val();
To turn a string to lower case, you use the string method toLowerCase():
var value = $('#mytextbox').val().toLowerCase();
Since val() returns a string we can throw that at the end.
To check if a string is within another string, you use the string method indexOf():
var needle = 'Hello';
var haystack = 'Hello World';
var match = haystack.indexOf(needle); // -1 if no matches, 0 in this case
Another thing to remember is that ASP.NET renames all your control ID's. To access your controls in JavaScript, you should use the following in place of the Control ID <%= txtUserName.ClientID %>.
In jQuery, here is what my selector would look like for a textbox with the ID "txtUserName".
$('#<%= txtUserName.ClientID %>')
Enjoy,
Zach
var userName = "username as it comes out of your web app";
// stuff happens
var $myTextbox = $('#ID_of_textbox');
var userNameIsContained = $myTextbox.val().toLowerCase().indexOf(userName) >= 0;
Short explanation:
$('#ID_of_textbox') // fetches the jQuery object corresponding to your textbox
.val() // the jQuery function that gets the textbox value
.toLowerCase() // self explanatory
.indexOf() // returns the position of a string in a string (or -1)
See the JavaScript String object reference at w3schools.
Alternative (to check if the textbox value equals the username):
var userNameIsEqual = $myTextbox.val().toLowerCase() == userName;
The basics of JQuery are like so: Find a list of dom elements, and perform actions on them.
In your case, you should start off by finding the dom element that is your testbox. For example's sake, we'll choose $('#userName'). The selector # means "id" and together with the name "userName" it finds all elements with the id of "userName". (Ids on a page should be unique if you're following best practices.)
Once you have that list (in this case, a list of one element), you can ask it what the value is.
$('#userName').val()
This gets you the value of the value="" attribute of the input tag.
You can then assign it to a variable and use standard javascript String functions to do the rest!
function checkLogin(userName){
return $('#mytextbox').val().toLowerCase() == userName
}
if ($("#textBoxID").val()) != "") { /*Do stuff*/ }

Categories