How to extract a part of a value inside an attribute - javascript

I have many hyperlinks with a onclick function which have differents values on this way:
<a onclick="Utils.decideOffer('', {'unlockFeature': 'cars'});">cars text</a>
<a onclick="Utils.decideOffer('', {'unlockFeature': 'bikes'});">bikes whatever</a>
<a onclick="Utils.decideOffer('', {'unlockFeature': 'motorcycles'});">another motor</a>
Now when this element is clicked I need to get the values of that array, example: "cars", or "bikes" or "motorcycles".
Don't suggest to get them from the Utils.decideOffer function because I need to get them without edit that file/function. This is how I intend to extract it.
$('a').click(function() {
onclickValue = $(this).attr('onclick');
if (onclickValue.length) {
var optionSelectedValue = ??? ;
}
});
I was thinking on use Regex so can you please help me on the Regex to use on this case?, or if you have another good idea to achieve this it is also welcome!

Try split() like :
$('a').click(function() {
onclickValue = $(this).attr('onclick');
if (onclickValue.length) {
var optionSelectedValue = onclickValue.split(":")[1].split("}")[0];
}
});
it will return the 'cars' or 'bikes' or 'motorcycles' including the quotes
See JSFIDDLE
... or to get the value without quotes as suggested :
optionSelectedValue = onclickValue.split(":")[1].split("}")[0].split("'")[1];
See updated JSFIDDLE

$('a').click(function() {
onclickValue = $(this).attr('onclick');
if (onclickValue.length) {
var re = /(?!: ')+(\w)+(?='})/;
var found = onclickValue.match(re);
var optionSelectedValue = found[0] ;
alert(optionSelectedValue);
}
});
Demo: http://jsfiddle.net/wpjh1ma7/

Related

Parse a string in jquery, change something and get the modified string back

I have a string containing html code, something like this: http://jsbin.com/ocoteg/1.
I want to parse this string, make some changes (just for example: change all links to a span), and then get the modified html string back.
Here is a jsbin, where I started this, but I can't make it work: http://jsbin.com/okireb/1/edit.
I get the html string, I parse it with jquery, but I can't replace the links, and get the modified html string back.
UPDATE
Why the downvote? What is the problem with this question?
You can do it in a loop also
dom.each(function(i,v){
if(v.tagName == "A"){
dom[i] = $('<span/>').html($(v).html())[0]; // replace it right away with new span element
}
});
var newString = $('<div>').append(dom.clone()).html(); //<-- to get new string http://stackoverflow.com/a/652771/1385672
console.log(newString);​
EDIT:
Here's how you can do it keeping the other tags
var dom = $(text.split('\n'));
$(dom).each(function(i,v){
var ele = $(v)[0];
if($(ele).is('a')){
dom[i] = $('<div>').append($('<span/>').html($(v).html())).html();
}
});
var newString = dom.get().join('\n');
http://jsbin.com/okireb/32/edit
Use find instead of filter :
var dom = $('<div>'+text+'</div>');
dom.find('a').each(function() {
var el = $(this);
var html = el.html();
var span = $('<span/>').html(html);
el.replaceWith(span);
});
console.log(dom.children()); ​
Note that I wrap everything for the case where the initial dom isn't one element.
Demonstration
To get the html back as a string use
var html = dom.html();
This should be what you want (can be improved)
var text = '<!DOCTYPE html><html><head><meta charset=utf-8 /><title>JS Bin</title></head><body>Link 1Link 2Link 3</body></html>';
var body_content = text.substring(text.indexOf('<body>') + 6, text.indexOf('</body>'));
var $dom = $('<div/>').html(body_content);
$('a', $dom).each(function() {
$('<span>' + $(this).html() + '</span>').insertAfter($(this));
$(this).remove();
});
var text_new = text.replace(body_content, $dom.html());
// text_new contains the entire HTML document with the links changed into spans
You could do it with .replace.
Probably not the nicest way of doing it though.
dom = dom.replace(/<a /g,'<span');
dom = dom.replace(/<\/a>/g,'</span>');
Demo: http://jsbin.com/okireb/14/edit

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");

How to get div text also with it's input's values

I was wondering how to obtain the text inside a given div, with also the input's values as text.
<div id="example">This is a <input type="text" value="right"/> test.</div>
If I just try to get text like this with jQuery :
$("#example").text();
The result would be This is a test. and I'd want : This is a right test.
The number of input would be unknow. As well as the order of the elements...
EDIT :
I finally resolved my own problem :
var finalText="";
$("#example").contents().filter(function() {
if(this.nodeType==3){ finalText =finalText+ this.nodeValue;}
else if(this.nodeName=="INPUT"){ finalText=finalText+this.value;}
return finalText
})
The living example
But #Jonathan Lonowski answer is more clear and simpler than mine !
Here is a quick plugin that will do this for you:
$(document).ready(function() {
$.fn.extend({
getContentText: function() {
var t = '';
this.contents().each(function(i,c) {
var method = $(c).is("input") ? "val" : "text";
t += $(c)[method]();
});
return t;
}
});
alert($("#example").getContentText());
});
Try it out here:
http://jsfiddle.net/wQpHM/
You might try cloning so you can replaceWith the inputs with their values. Then grab the text as you were:
var clone = $('#example').clone();
clone.find(':input').replaceWith(function () {
return $(this).val();
});
alert(clone.text());
You can loop though all children of the <div> and replace then with their values. Something like this:
$.fn.allText = function(){
var $this = this.clone();
$this.children().each(function(){
$(this, $this).replaceWith(this.value);
});
return $this.text();
};
alert($('#example').allText());
Demo: http://jsfiddle.net/4mGmH/
get html and strip html tags
$('#example')[0].innerHTML.replace(/(<([^>]+)>)/ig, '').replace(/(\s+)/g, ' ')
Using innerText
document.getElementbyId('example').innerText;
To get HTML tags:-
document.getElementbyId('example').innerHTML;
Refer this URL element.innerHTML

javascript unobtrusive

i have an html page, which is consist of many hyperlink like this inside body tag...
User Name
then i decide to use unobtrusive javascript ... then i'd like to change all the "a" tag to be...
<a id="354313" href=#>User Name</a>
when i click the second link above, i want that it'll call a function like the first link does,...
my question is how to get all the "a" element inside body tag then apply a function depend it's id...
With jQuery, something like this:
$('a').click(function() {
var id = this.getAttribute('id');
// Do something...
});
If you want it to work on all elements ever created, use this:
$('a').live('click', function() {
var id = this.getAttribute('id');
// Do something...
});
I hope this is what you are trying.
<script type='text/javascript'>
var alA = document.getElementsByTagName("a");
for(var aCounter=0;aCounter<alA.length;aCounter++) {
var singleA = alA[aCounter];
singleA.onclick = function () {
window.open = "http://www.example.com/?id="+singleA.id;
}
}
<script>
What you're after is this code:
<script type="text/javascript">
window.onload = function WindowLoad() {
var arrLinks = document.getElementsByTagName("a");
for (var i = 0; i < arrLinks.length; i++) {
var oLink = arrLinks[i];
var sCurHref = oLink.href;
if (sCurHref.indexOf("?id=") >= 0) {
var ID = sCurHref.split("?id=")[1];
if (ID.length > 0) {
oLink.id = ID;
oLink.href = "#";
oLink.onclick = function() {
document.location.href = sCurHref;
return false;
}
}
}
}
}
</script>
This will iterate all the links, changing the visible HREF to "#" and preserving their functionality, applying the proper ID. (Though you didn't say what's the use of that ID)
Feel free to mess around with the live test case: http://jsfiddle.net/yahavbr/uMbEY/
Something like:
<script language="javascript">
function myFunction(id)
{
alert(id);
}
</script>
<a id="354313" onclick="myFunction(this.id);" href="#">;User Name<;/a>
Not sure though Test it :)
I will rather say that add class to the links u want to handle this way
<a class="mylink" ... >User Name </a>
Now read the elements by class name. If you are using new browsers or any JS library like JQuery its great.
var links = document.getElementsByClassName("mylink") //Method in Mozilla Browser
Above are the links that you can process nicely without getting into trouble.
// Function that you want to call
function fake(id)
{
// Your content
}
// Get all "a" elements and put it in an Array
var links = window.document.getElementsByTagName("a");
for (var i=0; i<links.length; ++i)
{
fake(links[i].id);
}

Categories