I had to extract the 2nd parameter (array) from an onclick attribute on an image, but jQuery just returned a function onclick and not its string value as expected. So I had to use a native method.
A quick search says it may work some browsers like FF, but not IE. I use Chrome.
<img src="path/pic.png" onclick="funcName(123456,[12,34,56,78,890]);" />
I thought this would work, but it does not:
var div = $('div_id');
var onclick_string = $(div).find('img').eq(0).attr('onclick');
var onclick_part = $(onclick_string).match(/funcName\([0-9]+,(\[.*\])/)[1]; // for some reason \d doesnt work (digit)
This works
var div = $('div_id');
var onclick_string = $(div).find('img')[0].getAttributeNode('onclick').value;
var onclick_part = $(onclick_string).match(/funcName\([0-9]+,(\[.*\])/)[1]; // for some reason \d doesnt work (digit)
Is there another way of getting the 2nd parameter ?
Why not store it in the data property?
<img src="path/pic.png" onclick="funcName(123456);" data-mydata='12,34,56,78,890' />
var div_data = $('div_id').data('mydata').split(',');
UPDATE
I used the following code to loop through a collection of span tags and output their onclick strings. it's hacky but it works (firefox 7, JQuery 1.5.1). You can even override the string value.
$("span").each(function(index)
{
alert( $(this)[0].attributes.onclick.nodeValue );
});
Related
I have this JavaScript function:
function Test(isValid) {
var divStart = $get('divDateFrom');
var divEnd = $get('divDateTo');
var txtStartDate = divStart.firstChild;
var txtEndDate = divEnd.firstChild;
var isValidFromForecastStartDate;
txtEndDate.setAttribute('dateInRegionalFormat', txtEndDate.value);
}
This function is working fine in IE but I'm getting "txtEndDate.setattribute is not a function" error in Firefox and Chrome.
Use jquery.attr() like,
$(txtEndDate).attr('dateInRegionalFormat', txtEndDate.value);
Updated there may be multiple elements so use [0] for the first element like,
txtEndDate[0].setAttribute('dateInRegionalFormat', txtEndDate.value);
You should first check whether the elements exists or not before setting attribute in it like,
if(txtEndDate.length)
{
txtEndDate.setAttribute('dateInRegionalFormat', txtEndDate.value);
}
You can do it by this way:
txtEndDate['dateInRegionalFormat'] = txtEndDate.value;
instead of old code:
txtEndDate.setAttribute('dateInRegionalFormat', txtEndDate.value);
I have faced the same kind of issue very recently. Try to get rid of ".value" part. It may work for you.
txtEndDate.setAttribute('dateInRegionalFormat', txtEndDate);
First of all, lets say I have about 10 divs that are hidden and have the ID's as "modal1", "modal2", "modal3", etc... Using an ajax request, the data returned contains an ID number, lets say it is 7.
In previous tasks, I have used the javascript eval function but this does not work. I wish to append the received data to the correct modal div.
var newdataobj = JSON.parse(newdata);
var ResponseDiv = "#modal" + newdataobj.ID;
$(eval(ResponseDiv)).append(newdataobj.DataToAdd);
This doesn't work and the script stops working at this point. I have also tries using the JQuery version of eval, but that did not work either.
You don't need to use eval() here, use just $(ResponseDiv).append(newdataobj.DataToAdd);
ResponseDiv is already a string and that is what you need for the selector.
Try this to confirm you have the right ID:
var newdataobj = JSON.parse(newdata);
var ResponseDiv = "#modal" + newdataobj.ID;
alert(ResponseDiv); // or console.log(ResponseDiv); - to doublecheck you have the right ID
$(ResponseDiv).append(newdataobj.DataToAdd);
ResponseDiv is already a string containing exactly what you want.
You don't want eval at all.
Hi I'm a newbie with javascript and I was wondering how do I strip all the text except the word TB_iframeContent800 . the digits at the end varies.
here is an example string
<iframe frameborder="0" style="width: 670px; height: 401px;" onload="tb_showIframe()" name="TB_iframeContent80" id="TB_iframeContent" src="http://www.gorgeoushentai.com/wp-admin/media-upload.php?post_id=33&" hspace="0">This feature requires inline frames. You have iframes disabled or your browser does not support them.</iframe>
I want to extract TB_iframeContent80 and store it as a variable. So how can you do this using regex with javascript? please note the last 2 digits varies cause the number always changes so it sometimes become a 3 digit number.
var iframeName = document.getElementsByTagName("iframe")[0].name
if you've include jQuery then it could be something like this:
var iframeName = $("iframe:first").attr("name");
If jQuery is an option I think you are looking for something like this
$('iframe[name^="TB_iframeContent"]')
If you wont use DOM (because code analysis etc) just try this regex
var code = '<iframe ... /iframe>';
var result = code.match( /name="([^"]*)"/ );
var extract = result[1];
this selects the content of the name attribute
You could load html youre parsing like this and use DOM to get its name (its easier and more reliable way than using a regex):
var loadhtml = document.createElement('div');
loadhtml.innerHTML = 'yourHtml';
var theName = loadhtml.getElementsByTagName('iframe')[0].name;
If you use Jquery you could consider attr("name") as way to get name
However if you insist using a Regex here is one :
/< *iframe[^>]*name *= *['"]([^'"]*)/
I've got this span:
<span id="inicial"></span>
and this javascript inside a button click:
var pat = /\/\S+\//i;
context = '';
context = $('#cmd').attr('value');
context= context.match(pat);
alert(context); //this gives correctly the string i need
if (context.length){
$('#inicial').text(context); //but it fails to change the text inside the span
}
What could be the problem?
Also i noticed that it affects the whole click function, it just stops working. What could possibly be the cause?
The problem is that .match() returns an array, not a string. But .text(parm) requires parm to be a string.
So after the .match(), you should do something like:
context = context[0];
or use some other methodology to convert at least the first element in the array to a string, if not the full array.
Here's the reference for .match(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match
And the ref for .text(parm): http://api.jquery.com/text/
try -- edited as per #Jonathan M
answer
$('#inicial').html(context[0]);
I have some lines of HTML code that are like this:
<li>Testing jQuery [First Bracket]</li>
<li>Loving jQuery [Second one]</li>
I'm trying to replace what's inside the bracket with nothing onLoad, like this:
var item = $(".lstItem").text();
var match = item.match(/\[(.*?)\]/);
item = item.replace(match[0], "");
But nothing changes. What's wrong and how to correct this?
After using jimbojw's suggestion I'm getting a Uncaught ReferenceError: text is not defined at this particular line:
oldtext = $item.text,
item is a variable containing a string, not a pointer to the literal text. If you want to change the text, you have to set it again, vis a vis $(".listItem").text(item)
edit - predicting next problem
The next problem you're going to have is that all the text gets set to the same thing. So what you really want to do is probably something like this:
$(".lstItem")
.each(function(index, item) {
var
$item = $(item),
oldtext = $item.text(),
match = oldtext.match(/\[(.*?)\]/),
newtext = oldtext.replace(match[0], '');
$item.text(newtext);
});
this will do the job for you:
you are splitting your code in too much lines, also your need to run replace for each individual element separately.
$(".lstItem").each(function() {
$(this).html(
$(this).html().replace(/\[(.*)\]/, "")
);
});
see your example in jsFiddle: http://jsfiddle.net/eKn3Q/7/
Along with jimbojw's answer $(".lstItem").text() will retrieve all the text inside of your <a/> elements. One way to handle this would be to pass a function(i,t){} into the .text() method.
$(".lstItem").text(function(i, text){
var match = text.match(/\[(.*?)\]/);
return text.replace(match[0], "");
});
Simple example on jsfiddle
also your regex could be simpler.
var item = $(".lstItem").text();
var match = /\[(.*?)\]/;
$(".listItem").text(item.replace(match,""));