Reputation: 5017
I have a list of buttons and and respective dialog box messages that I want to show when each of these buttons are clicked.
I have the following HTML:
<a class="btn dialogbtn dialogbtn-save" href="#">Save</a>
<a class="btn dialogbtn dialogbtn-delete" href="#">Delete</a>
<div class="dialogstack">
<div class="dialog-save">
<p class="header">Save Header Text</p>
<p class="message">Save Message Text</p>
<p class="footer">
<span>OK</span>
</p>
</div>
<div class="dialog-delete">
<p class="header">Delete Header Text</p>
<p class="message">Delete Message Text</p>
<p class="footer">
<span>Save</span>
<span>Cancel</span>
</p>
</div>
</div>
I am trying to match the "save" and "delete" part when a button is clicked and have the related messages show up.
$(document).ready(function(){
var dialogMessages = $("[class|='dialog']");
$(".dialogbtn").on('click', function(){
var index = this.className.indexOf('-');
if(index) {
var dd = this.className.substring(index+1);
var lastIndex = dd.indexOf(' ');
var dialogFunction = dd.substring(0,(lastIndex>0)?lastIndex:dd.length);
}
if(dialogMessages.hasClass('dialog-'+dialogFunction)){
var currentDialog = dialogMessages.find('.dialog-'+dialogFunction);
alert($(currentDialog).find('p').text()); //This doesn't work
}
});
});
I am unable to access the HTML stored in the jquery objects. How can I fix this?
Upvotes: 0
Views: 37
Reputation: 7991
I really wish I could tell you why this works, but I don't actually know.
If you replace find with filter, it works fine.
$(document).ready(function(){
var dialogMessages = $("[class|='dialog']");
$(".dialogbtn").on('click', function(){
var index = this.className.indexOf('-');
if(index) {
var dd = this.className.substring(index+1);
var lastIndex = dd.indexOf(' ');
var dialogFunction = dd.substring(0,(lastIndex>0)?lastIndex:dd.length);
}
if(dialogMessages.hasClass('dialog-'+dialogFunction)){
var currentDialog = dialogMessages.filter('.dialog-'+dialogFunction);
alert($(currentDialog).find('p').text());
}
});
});
What is really odd about this is that your code works, with find, if dialogMessages is defined as:
var dialogMessages = $('div');
Upvotes: 1
Reputation: 482
Try this function to print/alert HTML from div.
$(document).ready(function(){
var dialogMessages = $("[class|='dialog']");
$(".dialogbtn").on('click', function(){
var index = this.className.indexOf('-');
var dd = this.className.substring(index+1);
alert($(".dialog-"+dd).html()); //This doesn't work
}); });
https://jsfiddle.net/rohitbatta/gynh4nwb/3/
Upvotes: 1