Do someone know what is the best way to replace some string inside a onclick attribute ?
I need to get the current value and replace some text inside parameters.
Exemple, I have this link:
My link
And I want this:
My link
In other words, I want something like this:
$('a').attr('onclick', $(this).attr('onclick').replace('1', '2'));
And I know I can do this, but I need something dynamic retreiving the values of current element:
$("a").attr('onClick', "myfunction('parameter2a','parameter2b')");
Finally it working when I made a simple demo: http://jsfiddle.net/GkWhh/4/
Thank you for your solutions !
$('a[onclick]').attr('onclick', function(i, v){
return v.replace(/1/g, '2');
});
http://jsfiddle.net/cj9j7/
If you need something more dynamic do not use onclick attributes, changing onclick attributes is hackish, you can use click method instead.
var param = 1;
$('a').click(function(){
// ...
if ('wildguess') {
param = 1;
} else {
param++;
}
})
sounds like a really bad idea but anyway - you can access the string value of the onlick attribute using something like that:
$('a').each(function() { this.attributes.onclick.nodeValue = this.attributes.onclick.nodeValue.replace('1', '2'); })
You can do this: http://jsfiddle.net/SJP7k/
var atr = $('a').attr('onclick');
var str = atr.split('1');
var natr = str.join('2');
$('a').attr('onclick',natr);
Related
I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});
Basically I have this kind of tag (just for example)
<div type="text" onclick="event();" onblur="event();">this div has onclick and onblur functions</div>
and I want to remove some attributes to that tag using a reference variable.
var refAttribs = ['onclick', 'onblur'];
So it should strip out all attributes from refAttribs.
Be careful not to strip out the content of the div. Because it also contains a string from the refAttribs variable.
How do I get rid of them using a regex?
Thanks in advance
As you've stated the tag is a string then you could santise it with the following javascript.
var refAttribs = ['onclick', 'onblur'];
function remove(tagToClean)
{
var result = tagToClean;
for(var i=0; i<refAttribs.length; i++)
{
regex = new RegExp(refAttribs[i] + "=\"[a-zA-Z\(\);]*?\"", "g");
result = result.replace(regex, "");
}
return result;
}
You can call the method by passing in your string.
remove('<div type="text" onclick="event();" onblur="event();">this div has onclick and onblur functions</div>');
I'm not 100% sure what you're trying to do here. Are you trying to modify the DOM? If so you will need to modify the method to accept a handle to a DOM node. A little more information would help.
Well, try this:
To remove onclick, the regex will be:
(<[^>]+)\s+onclick\s*=[\'"].*?[\'"]
Debuggex Demo
The removeAttr function:
function removeAttr(html, attr) {
return html.replace(new RegExp('(<[^>]+)\\s+' + attr + '\\s*=[\'"].*?[\'"]', 'gi'), '$1');
}
http://jsfiddle.net/rooseve/pC4aH/1/
If I have this line and I'm wondering if there's better way to do it.
var TheID = $(this).parent().parent().parent().parent().parent().attr('id');
Note that the div for which I'm looking for the ID has class "MyClass", if that can help.
Thanks.
you can also try closest for get attribute like this :
$(this).closest('div.Myclass').attr('id');
or second way is
$(this).parents('div.Myclass').attr('id')
see here : http://jsfiddle.net/sKqBL/10/
Get all the .parents(), and use .eq()...
$(this).parents().eq(5).attr('id');
...or the :eq() selector...
$(this).parents(':eq(5)').attr('id');
...or make a function...
function up(el, n) {
while(n-- && (el = el.parentNode)) ;
return el;
}
...and use it like this...
up(this, 5).id
What is your definition of better?
//POJS, fastest
var TheID = this.parentNode.parentNode.parentNode.parentNode.parentNode.id;
//jQuery, terse
var TheID = $(this).closest(".MyClass").prop("id");
var TheID = $('.MyClass').attr('id');
or
var TheID = $('#MyClass').attr('id');
is this what you mean? that will get the ID of .MyClass
you can use .parents
var TheID = $(this).parents(".MyClass").attr('id');
Is the id that you are trying to retrieve dynamically generated and so therefore you don't know what it is?
If so, consider assigning a unique CSS class name to the great-great-great grandparent. Then you should be able to do something like this:
$(".MyGreatGreatGreatGrandparentCssClass").attr("id");
Of course, if you do this you may not need the great-great-great grandparent's id.
is there a way to reset/update an after() element? Not add another after() text. Thank you
Maybe this will helpful.
(Controller function for Emptiness of Form to be sent Server Input parameter ID of Form Parent DIV, output is 1-true, 0 false)
function emptynessCntrl(elementosForControl){
var controlResult=1;
$(elementosForControl).find('input').each(function() {
if($(this).val().trim()===""){
controlResult=0;
console.log($(this).attr('id')+' Element is empty');
$(this).nextAll().remove();
$(this).after('<div class="err-label">'+$(this).attr('placeholder')+' is empty</div>');
return controlResult;
}
else{
$(this).nextAll().remove();
}
});
return controlResult;
}
Your question is not clear. I'll asume you want to modify an element added with .after()
Instead of doing this:
$("#elem1").after('<div id="after />");
You could do this (use insertAfter)
$('<div id="after" />').insertAfter("#elem1").attr("width", 200).html("hi") ...;
Hope this helps.
Cheers.
When you add the element, give it a name
var newElement = $('<span>Some new stuff</span>');
$('.whatever').after(newElement);
Then, when you want to change it, simply remove the previous one first
newElement.remove();
newElement = $('<div>And now for something completely different</div>');
$('.whatever').after(newElement);
You can write a function that uses .data() to remember the new element as such: (I would change the names a bit though)
$.fn.addUniqueSomething = function (content) {
var existing = this.data('something-that-was-already-added');
if (existing) {
existing.remove();
}
var something = $(content);
this.after(something);
this.data('something-that-was-already-added', something);
};
Then you can use
$('.whatever').addUniqueSomething('<span>Some new stuff</span>');
// and later...
$('.whatever').addUniqueSomething('<div>And now for something completely different</div>');
And the second one will replace the first
Is there a way to me do this?
<img id="example" src="anything.jpg" title="something" class="abc" />
$('.abc').each(function(){
//test if this result is something
if( $(this)...(???)...('[src^=anything]')) == 'anything.jpg'){
}
//another Jquery selector test for this one
if( $(this)...(???)...('#example').size() > 0){
}
});
This is just an example, what I need is pretty more complex.. But I would like to know if there is a way to make other jQuery selector test in the result of a first selector.. since "find" will find the children of $(this).. and .parent() get alot of brothers..
See what I mean?
Do you have any idea?
So sorry.. let me try again..
$('div').each();
get all "div", right?
But now in that function I need to make another "test" check if div class is "red" or "blue"..
See?
I need to test something else of the result based in Jquery selector..
I know I could do:
class = $(this).attr('class'); and then if(class=="blue"){} .. But I would like to do $('this[class=blue]').size()>0){}
The jQuery is() filter operates on a found set to detect if something is true or not.
The jQuery filter() method will further pare down a found set based on criteria.
var allDivs = $('div');
var greenOnes = allDivs.filter('.green');
var redOnes = allDivs.filter('.red' );
I think you need the is method:
$('.abc').each(function() {
$(this).is('[src^=anything]')
});
This is fairly simple though, but I can't really tell what you are trying to do by the description. Maybe this is enough to get you started though.
You can use the filter and is methods to filter/search within a jQuery object.
if( $(this).is('[src^="anything"]') ) {
}
elseif( $("#example").size() > 0) {
}
You could put $("#example") in a variable outside of the loop and then reference it inside the loop as well.
if(this.src.indexOf("anything") === 0) {
// source starts with 'anything'
}
if($("#example").length) {
// since there can be only one #example
// in a *valid* document
}
Based on your edit:
if($(this).hasClass("blue")) {
...
}
?