Jquery replace link with new value - javascript

I am reading data from a database and adding each link in a new table row.
I wrote a jquery function to replace the href of the link with a new value, but it is not working.
Also I have to mention that each time a new link is added to the table, I want the replacement to be done instantly, without click event or something.
$(document).ready(function() {
$("a").show(function() {
var before = $(this).href;
var replacewith = "https://www.google.com"
var after = before.replace(before, replacewith);
$(this).attr("href", after);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
Link1
</td>
</tr>

Your code has unnecessary lines. However fix is done
$(document).ready(function () {
$("a").show(function () {
var before = $(this).attr('href');
var replacewith = "https://www.google.com";
var after = before.replace(before, replacewith);
$(this).attr("href", after);
});
});

[edited: removed original comment for clarity]
See the second comment for answer.

Related

Trim partial link in jQuery

I am trying to remove the start of a link in jQuery. I have tried to inject the following function but it doesn't work. What am I doing wrong?
JS
$(function() {
$('link-active').each(function() {
$(this).attr('href').remove('http://www.linkplus.com/xQWE=');
});
});
HTML
<td class="block">
<a class="link-active"
href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
</td>
When you're trying to search for classes, make use of dot (.), $('link-active') should be $('.link-active').
About .remove(): this one will remove one element of the DOM; not applicable in this case.
Solution: You will need to use .attr() to return AND update the href attribute of your tag, .replace() method should help.
$(function() {
$('.link-active').each(function() {
let href = $(this).attr('href'); //returns href value
let removableUrl = 'http://www.linkplus.com/xQWE=';
href = href.replace(removableUrl, ''); //replace the url you don't want with ''
$(this).attr('href', href); //update href value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="block">
<a class="link-active"
href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
</td>
Note: There's other methods to separate the url you don't want (if the url stay in the same format), check for:
.substring(): href = href.substring(removableUrl.length);
.split(): href = href.split('=')[1];
.replace() with regex: href = href.replace(/.*\=/,'');
Amend $('link-active') to $('.link-active').
First thing is While representing a class in jQuery try using dot notation..
$(function() {
$('.link-active').each(function() {
$(this).attr('href').remove('http://www.linkplus.com/xQWE=');
});
});
It's convenient to use attr method like this:
$(function() {
$('.link-active').attr('href', function(i, href) {
return href.replace('http://www.linkplus.com/xQWE=', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link-active" href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
Change your code on line 3 to
$(this).attr('href', $(this).attr('href').replace('http://www.linkplus.com/xQWE=', ''));
Full code should be
$(function() {
$('link-active').each(function() {
$(this).attr('href', $(this).attr('href').replace('http://www.linkplus.com/xQWE=', ''));
});
});
remove is not being used correctly here, as that method is meant to remove elements from the DOM and accepts a selector string as its argument.
Try something like this instead:
$(function() {
$('.link-active').each(function() {
var href = $(this).attr('href');
var strToReplace = 'http://www.linkplus.com/xQWE=';
$(this).attr('href', href.replace(strToReplace, ""));
});
});
Above we use replace to replace the start of the link with an empty string.
You have to get the string, replace it and then set it again.
Something like this:
$(function() {
$('link-active').each(function() {
replacement = 'http://www.linkplus.com/xQWE=';
url = $(this).attr('href');
$(this).attr('href', url.replace(replacement, ''));
});
});

How to empty href queries

I would like to know how to clear my href queries after a click event.
All what I need is if I click my button again it should clear old queries and add new ones to href.
click(function() {
//adds some queries to href
var a_href = $('.link').attr('href');
myArray.forEach(function(index){
a_href = a_href + index;
$('.link').attr('href', a_href)
});
});
example:-
default status: href="www.example.com/_size-"
old href: href="www.example.com/_size-xs.m.l"
new href should overwrite the old one: href="www.example.com/_size-l.xl.xxl
If I understand correctly you're looking for something like this:
var myArray = ["xs.m.l", "l.xl.xxl"];
var currentIndex = 0;
$('#btn').click(function() {
var a_href = $('.link').attr('href');
a_href = a_href.replace(/(size\-)(.*)$/,"$1"); // remove previous "query"
a_href = a_href + myArray[currentIndex % myArray.length]; // add the new "query"
$('.link').attr('href', a_href);
$('.link').text(a_href)
currentIndex++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Change Link</button><a class="link" href="www.example.com/_size-">www.example.com/_size-</a>
Maybe this will help?
Click Me!
<script>
$('.my_link').click(function (e)
{
e.preventDefault();
$(this).attr('href', '#another_link');
});
</script>

Append to a.href id from input field

I am trying to append to a link with id a value that is entered from the input text field. I came this far searching stackoverflow but id doesn't work!
<script type="text/javascript">
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
});
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code='.text(value);
});
});
</script>
and this is how the html looks like
<form>
<fieldset>
<input id="txt_name" type="text" value="discount" />
</fieldset>
</form>
<a id="coupon_link" href="https://www.e-junkie.com/ecom/gb.php?c=cart&i=XXXXXX&cl=YYYYYY&ejc=2" target="ej_ejc" class="ec_ejc_thkbx" onClick="javascript:return EJEJC_lc(this);"><img src="http://www.e-junkie.com/ej/ej_add_to_cart.gif" border="0" alt="Add to Cart"/></a>
You probably meant this:
$(function() {
$("#coupon_link").on('click', function(e) {
e.preventDefault(); // apparently not needed
location.href = $(this).attr('href') + '&discount_code=' + encodeURIComponent($('#txt_name').val());
});
});
You don't have to update the value of #txt_name on keypress; you only have to use the value when the link is pressed.
Fix your code like this :
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
var link = $("#coupon_link");
var originalHref = link.attr('originalHref');
if (!originalHref) {
originalHref = link.attr("href");
link.attr("originalHref", originalHref)
}
link.attr("href", originalHref + '&discount_code='+value);
});
});
A few things to note :
never add anything to a selector when you're targeting an element by ID
your value variable wasn't in the same scope
the return of val can be directly concatenated, you don't need to try to change it to text
you don't need to pass a function to attr in your case
you're trying to make the href grow with every key stroke. This is a bad idea. The solution I propose is to keep the original href
if you're not sure the original href has yet some parameters (i.e. has '?') you should test it (I let you do that)
Overall a much cleaner solution wouldn't be to change the link but to build the href on click on the link :
$("#coupon_link").click(function(e) {
location = this.href + '&discount_code=' + $('#txt_name').val();
});
Not sure to understand, but it looks like a scope issue try this javascript :
<script type="text/javascript">
jQuery(function(){
var value = 0;
$("#txt_name").keypress(function() {
value = $("#txt_name").val();
$("a#coupon_link").attr("href", function(i) {
return href + '&discount_code=' + encodeURIComponent(value);
});
});
});
</script>
Try this:
jQuery(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href", '&discount_code=' + String(value));
});
});
This isnt working because the href isnt being changed as the function is called before a keypress event is triggered. Look into replacing keypress with blur and update the href when blur() is called
i think you need this:
<script type="text/javascript">
$(function(){
$("#txt_name").keypress(function() {
var value = $("#txt_name").val();
$("a#coupon_link").attr("href",href+'&discount_code='+value.toString);
});
});
</script>
look at href don't know where you have that var, if it is needed ok else remove that
You probably need to change the href when a key has been pressed, not only on page load. To do so you will have to do the replacing of the href inside the keyup function, like so:
$(function(){
var link = $("a#coupon_link");
link.data('href', link.attr("href"));
$("#txt_name").on('keyup', function() {
link.attr("href", link.data('href') + '&discount_code='+ this.value);
});
});
So as to not append the &discount_code=*** several times, you need to store the original href somewhere, like in a data attribute.
this one worked for me getting value from input field and append it to the existing link using jquery.
$('#qty').on('keyup', function() {
var theQty = 0;
theQty = $("#qty").val();
var oldHref=$("a#buybtn").attr("href");
$("a#buybtn").attr("href",oldHref+ '&qty=' + String(theQty));
});

Replace text with jQuery

I'm trying to replace text on a site using this code:
<script type="text/javascript">
$(document).ready(function () {
$(function() {
$(document.body).find('*').each(function() {
var tmp = $(this).children().remove();
var text = $(this).text();
text = text.replace(/Vorname/g, "Firstname");
$(this).text(text);
$(this).append(tmp);
});
});
});
</script>
HTML (snippet) is like this (generated by SharePoint):
<td style="padding:4px;">
<div>
<label for="ctl00_IWS_WH_CPH_Content_ContactUsControl1_firstName">
<span><font color='red'>*</font> Vorname (erforderlich):</span>
</label>
</div>
The above jQuery code is not being executed...
Reference to jQuery has been placed in the master page.
Any clue why this is not working?
Regards,
Thomas
I have found you are using two doc ready functions you have to use only one:
Either : $(document).ready(function () {
or : $(function() {
and see if this works.
Thanks
working demo
check the jsfiddle link for the working code
$(document).ready(function () {
$(document.body).find('*').each(function() {
var tmp = $(this).children().remove();
var text = $(this).text();
text = text.replace(/Vorname/g, "Firstname");
$(this).text(text);
$(this).append(tmp);
});
});
$('.element').text("sometext");
i think this is not right
var text = $(this).text();
text = text.replace(/Vorname/g, "Firstname");
you should use:
var text = $(this).text();
text.replace("Vorname", "Firstname");
then you should document better your question, i don't understand your real problem.
In your code, you are stripping off some elements style. If you want to keep layout you better have to use html not text, but it really depends of what you are looking for.
$(document).ready(function () {
$('body').find('*').each(function() {
var html= $(this).html().replace(/Vorname/g, "Firstname");
$(this).html(html);
});
});

A part of script in js file worked correctly with firebug console but not worked in page

I am really confusing, I have a js file with a lot of scripts, all of them worked correctly and I just add new lines:
$('.RemoveE').click(function () {
alert('yap');
});
but that not worked, I test it with firebug and every things is OK, also I try another browsers that not worked either, I must mention that I add new button with CSS class ="ReomoveE button red" by script, this is a part of my js include new lines and add button:
// <reference path="../jquery-1.7.1.js" />
$(document).ready(function() {
$('.RemoveE').click(function() {
alert('yap');
});
//Add new Addable div
$('.AddNewE').click(function() {
var Target = $('.Addable:first');
var TargetId = $(Target).attr('id');
var Count = $('.Addable#' + TargetId).size();
var CloneTarget = $(Target).clone();
CloneTarget.find('input').val('');
CloneTarget.insertAfter('.Addable:last');
var TargetName = $(Target).find('input').attr('name');
var CloneName = TargetName + '[1]';
TargetName = TargetName + '[0]';
$(Target).find('input').attr('name', TargetName);
$(Target).find('span[class*="field-validation"]').attr('data-valmsg-for', TargetName);
$(CloneTarget).find('input').attr('name', CloneName);
$(CloneTarget).append($('<input type="button" class="RemoveE button red" value="remove" />'));
(function($) {
$.fn.updateValidation = function() {
var form = this.closest("form").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
return this;
};
})(jQuery);
$(Target).updateValidation();
$(CloneTarget).updateValidation();
});
...
});​
So what do you think? Where is the problem, why all functions worked correctly, but this new one no?
You added the handler before the element existed:
$('.RemoveE').click(function() {
alert('yap');
});
//then later
$(CloneTarget).append($('<input type="button" class="RemoveE button red" value="remove" />'));
Try:
Adding the handler on creation:
var newInput = $('<input type="button" class="RemoveE button red" value="remove" />')
newInput.click(function(){
alert('yap');
});
$(CloneTarget).append(newInput)
or delegation with on()
$(parent_of_RemoveE).on('click','.RemoveE',function() {
alert('yap');
});
You need to use .on() or .delegate() so it can listen to any new button that you created dynamically
See the sample code here
HTML
​<div id='test'></div>​​​​​​​​​​​​​​​​​
JQUERY
​$(document).ready(function() {
$('#test').on('click','.removeE', function() {
alert('yap');
});
$('#test').append('<input type="button" class="removeE" value="test"/>');
});​
you can see the example here
What #Joseph said basically. I commented your code bit to point out some things worth noting.
$(document).ready(function () {
$('.RemoveE').click(function () {
alert('yap');
});
//Add new Addable div
$('.AddNewE').click(function () {
var Target = $('.Addable:first');
var TargetId = $(Target).attr('id'); // Double wrapping in jQuery
// ID are unique, selector makes little sense,
// and `length` is preferable to `size()`
var Count = $('.Addable#' + TargetId).size();
var CloneTarget = $(Target).clone(); // Double wrapping in jQuery
CloneTarget.find('input').val('');
CloneTarget.insertAfter('.Addable:last');
var TargetName = $(Target).find('input').attr('name'); // Double wrapping in jQuery
// This seems a bit verbose...
var CloneName = TargetName + '[1]';
TargetName = TargetName + '[0]';
$(Target).find('input').attr('name', TargetName); // Double wrapping in jQuery
$(Target).find('span[class*="field-validation"]').attr('data-valmsg-for', TargetName); // Double wrapping in jQuery
$(CloneTarget).find('input').attr('name', CloneName); // Double wrapping in jQuery
$(CloneTarget).append($('<input type="button" class="RemoveE button red" value="remove" />')); // Double wrapping in jQuery
// end verbosity
(function ($) {
$.fn.updateValidation = function () {
// Don't need to chain `removeData()` twice,
// as of jQuery 1.7 you can pass a list
var form = this.closest("form").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
return this;
};
})(jQuery);
$(Target).updateValidation(); // Double wrapping in jQuery
$(CloneTarget).updateValidation(); // Double wrapping in jQuery
});
});

Categories

Resources