Empty Quotes In jQuery Variable - javascript

I'm trying to add a link after a black of text. I can get them to render just fine, but the link href tag just disappears.
var eventstuff = data.text;
var eventElement = $("<div class='well well-sm eventsWells'>");
var deleteButton = $("<div class='panel'><a style='float:right; color:#348CD9; margin-top:3px;' href='' ng-click='deleteEvent("+key+")'>DELETE</a></div>");
eventElement.html(eventstuff).append(deleteButton);
eventsList.append(eventElement);
But the html just shows:
<a style="float:right; color:#348CD9; margin-top:3px;" href ng-click="deleteEvent(-KAY7j7_deUWLjhDbaQ5)">DELETE</a>
and clicking the link takes me to /# (using Angular).
I've tried using href='#' and putting return false at the end, which also didn't work, it still redirected to /#.
I've also tried escaping the quotation marks, and removing the href, both of which don't work. Any ideas?

This might because of deleteEvent(-KAY7j7_deUWLjhDbaQ5).
Correct onclick when you are passing string type parameter should be like this:
deleteEvent('-KAY7j7_deUWLjhDbaQ5')
^ ^ // ==>quotes are requried
This you can achieve by using following like:
var deleteButton = $("<div class='panel'><a style='float:right; color:#348CD9; margin-top:3px;' href='' ng-click='deleteEvent(\'"+key+"\')'>DELETE</a></div>");
Updates
You need to add $compile service here, that will bind the angular directives like ng-click to your controller scope. See following:
var eventstuff = data.text;
var eventElement = $("<div class='well well-sm eventsWells'>");
var deleteButton = $("<div class='panel'><a style='float:right; color:#348CD9; margin-top:3px;' href='' ng-click='deleteEvent(\'"+key+"\')'>DELETE</a></div>");
$compile(deleteButton)($scope); //here
$compile(eventElement)($scope); //here
eventElement.html(eventstuff).append(deleteButton);
eventsList.append(eventElement);

You can try like this
href='javascript:void(0);' ng-click='deleteEvent(\""+key+\"")'

Related

jQuery replaceWith() for HTML string

I am using filter() to select a list of elements then trying to replacing them by use of replaceWith(). The html is saved as string on a variable. It seem the replaceWith() is not working for me. When I log the variable content it shows the original string.
Is I know js objects are references. So, I was under the impression that replacing the selection will also replace element inside the string.
Here is the code
var content = '<div class="feature-box" contenteditable="false" data-sh-attr="%20title%3D%22jhk%22%20width%3D%224%22%20icon%3D%22thumbs-up%22" data-sh-content="kj"><div class="btn-panel"><a class="delete" href="#"><i class="fa fa-trash"> </i></a> <a class="edit" href="#"><i class="fa fa-pencil"> </i></a></div><div class="feature-icon-container"><i class="fa fa-thumbs-up main-icon"> </i></div><div class="feature-content"><h3>jhk</h3><div class="content">kj</div></div><div> </div></div><p>[block background_color="red" color="white"]Content of the block[/block]</p><p>This is an example page. It\'s different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this:</p><blockquote><p>Hi there! I\'m a bike messenger by day, aspiring actor by night, and this is my blog. I live in Los Angeles, have a great dog named Jack, and I like piƱa coladas. (And gettin\' caught in the rain.)</p></blockquote><p>...or something like this:</p><div class="feature-box" contenteditable="false" data-sh-attr="%20title%3D%22kk%22%20width%3D%224%22%20icon%3D%22thumbs-up%22" data-sh-content="kk"><div class="btn-panel"><a class="delete" href="#"><i class="fa fa-trash"> </i></a> <a class="edit" href="#"><i class="fa fa-pencil"> </i></a></div><div class="feature-icon-container"><i class="fa fa-thumbs-up main-icon"> </i></div><div class="feature-content"><h3>kk</h3><div class="content">kk</div></div><div> </div></div><blockquote><p>The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickeys to the public ever since. Located in Gotham City, XYZ employs over 2,000 people and does all kinds of awesome things for the Gotham community.</p></blockquote><p>As a new WordPress user, you should go to your dashboard to delete this page and create new pages for your content. Have fun!</p>';
jQuery(content).filter('.feature-box').each(function(){
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
var shortcode = '[feature' + attr + ']' + content + '[/feature]';
$this.replaceWith(shortcode);
});
console.log(content);
jsFiddle to play with
http://jsfiddle.net/du8d45tt/
You are creating an dom structure and is modifying that dom structure, which won't modify the original string
To get the updated html, you need to get the updated content of the dom structure.
var $tmp = $('<div />', {
html: content
})
$tmp.find('.feature-box').each(function () {
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
var shortcode = '[feature' + attr + ']' + content + '[/feature]';
$this.replaceWith(shortcode);
});
var replaced = $tmp.html()
console.log(replaced);
Demo: Fiddle
You don't actually assign the updated html anywhere. $this.replaceWith(shortCode); updates $this not content.
You can use .html() to get the updated content and assign it back.
content = $this.replaceWith(shortcode).html();
Due to the asynchronous nature of the jQuery each method, it runs a callback, you should also have the console.log within the each function.
jQuery(content).filter('.feature-box').each(function(){
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
var shortcode = '[feature' + attr + ']' + content + '[/feature]';
content = $this.replaceWith(shortcode).html();
console.log(content);
});
Strings are immutable objects in JavaScript, so you need to overwrite it with another value:
content = jQuery('<div>', {html: content})
.find('.feature-box')
.replaceWith(function() {
var $this = jQuery(this);
var attr = decodeURIComponent($this.data('sh-attr'));
var content = decodeURIComponent($this.data('sh-content'));
return '[feature' + attr + ']' + content + '[/feature]';
})
.end()
.html();
This also uses .replaceWith(fn) syntax as a handy shortcut for .each() and using .replaceWith() inside.

add dynamic id to links using Javascript?

I have many links on a page generated dynamically. Now I want to attach ids to them based on a link just before them.
I have written the following function to return me the value I want to add as id to the href I want.
<script>
function movingid(){
var res = location.href.replace(/.*student\/(.*)\/subject/, '$1');
var subjectid = res.split("/")[2];
var classid = res.split("/")[1];
var sectionid = res.split("/")[0];
return classid+"-"+sectionid+"-"+subjectid;
}
</script>
So what I did is
<a href="javascript:void(0);" id= "javascript:movingid();" >Move To</a>
But the HTML thus generated is not calling the function. Instead its adding the id as plain text form like this id= "javascript:movingid();". How can I call the function?
Please help
Create the links this way:
<a href="javascript:void(0);" id= "" >Move To</a>
Maybe wrapping the links with a div, which gets the id "mylinks". After this call a function adding the id with this code:
i = "1";
$( "div#mylinks a" ).each(function( index ) {
$(this).attr("id",i);
i++;
});
Instead of i take your code from the movingid function you already posted.

setting new href value to link tag

i'm trying to set new value to link href attribute..
<a title="main-picture" class="modal" href="test">
<?php echo $this->product->images[0]->displayMediaFull('class="product-image"',false,true); ?>
</a>
var mainImageLink = jQuery(".product-image").attr('src');
jQuery("a[title='main-picture']").attr("href") = mainImageLink;
It doesnt works, i dont see any errors in console. I tried to alert jQuery("a[title='main-picture']").attr("href") - it alerted "test"
Any tips?
var mainImageLink = jQuery(".product-image").attr('src');
jQuery("a[title='main-picture']").attr("href",mainImageLink);
Try instead:
jQuery("a[title='main-picture']").attr("href",mainImageLink);
To give the value to that attribute you need to use .attr(attrName, attrValue).
Read more here: .attr()
You can easily do it using simple javascript code like this.Let the links ID is link1
function changeLink(){
var ele = document.getElementById("link1");
ele.href = "newpage.html";
}
and now if you will click on that link you will be redirected at newpage.html

Get attr(id) with a known href variable

I want to get the id name thanks to a href value that is set in a variable.
To do this, I want to:
get the attr('href') of a clicked element (that works).
put it in a variable (OK).
search this href in a every class called ".link" (not in #prev-ajax, #next-ajax id) (problem)
Get the parent id.
I tried this :
$('#prev-ajax,#next-ajax').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
$(".link[href*= href ]:not('#prev-ajax,#next-ajax')");
var ajax = $(this).parents('.element').attr('id');
alert(ajax);
});
As you're using a JavaScript variable, you need to escape the quotes. Also, don't wrap items in the :not selector in quotes.
Try this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
Edit: Looking at your fiddle, you're also not doing anything with that selector. See this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = $(this).parents('.element').attr('id');
It should be:
var link = $(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = link.parents('.element').attr('id');
Demo: http://fiddle.jshell.net/UKyT4/1/

remove outer div

In my JavaScript code I have a string that contains something like:
var html = "<div class='outer'><div id='inner'>lots more html in here</div></div>";
I need to convert this to the string
var html = "<div id='inner'>lots more html in here</div>";
I'm already using using jQuery in my project, so I can use this to do it if necessary.
Why all these needlessly complex answers?
//get a reference to the outer div
var outerDiv = document.getElementById('outerDivId');//or $('#outerDivId')[0];
outerDiv.outerHTML = outerDiv.innerHTML;
And that's it. Just set the outerHTML to the inner, and the element is no more.
Since I had overlooked that you're dealing with an HTML string, it needs to be parsed, first:
var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
var outerDiv = tempDiv.getElementsByTagName('div')[0];//will be the outer div
outerDiv.outerHTML = outerDiv.innerHTML;
And you're done.
Try:
var html = "<div class='outer'>"
+ "<div id='inner'>lots more html in here</div></div>";
html = $(html).html();
alert(html);
http://jsfiddle.net/TTEwm/
Try .unwrap() -
$("#inner").unwrap();
If html string always look like in your example you can use this simple code
var html = "<div class='outer'><div class='inner'>lots more html in here</div></div>";
html = html.slice(19,-6)
You can do something like this:
var html = "<div id='inner'>" + html.split("<div id='inner'>")[1].split("</div>")[0] + "</div>";
But you may want to add more protection for variations (in case you have the bad habit of not writing code using the same conventions), e.g "inner" or <DIV>
Demo

Categories

Resources