How to define $var only if parents('.class').attr('id') exists? - javascript

Here is my code:
<div class="superBlock" id="blabla">
<a class="watch"><img src="images/blabla.png"/></a>
</br>
<div class="btn-group-xs" role="group">
<a type="button" class="btn btn-info info" data-toggle="modal" data-target="#myModal">Information</a>
</div>
</div>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-footer">
<a type="button" class="btn btn-success watch" data-dismiss="modal">Watch</a>
</div>
</div>
</div>
</div>
$('.info').click(function() {
var $watchID = $(this).parents('.superBlock').attr('id');
});
$('.watch').click(function() {
if($(this).parents('.superBlock').attr('id') != "") {
var $watchID = $(this).parents('.superBlock').attr('id');
}
alert($watchID);
});
What I'd like to do is to set the $watchID to the .superBlock's ID whether I click on the .watch button or on the .info button.
And I get $watchID is "undefined" when I click on the modal watch button after clicking on the info button.
And I'd like the $watchID to keep on being set to the .superBlock's ID if the $(this).parents('.superBlock').attr('id') is undefined. So the $watchID not to change to the undefined $(this).parents('.superBlock').attr('id').
What should I do? Is this only about syntax? If so, how should I change this?
This HTML divs are repeating with different IDs, that's why I can't just set the ID to "blabla".

To tell if a selector matches anything, check the length of the jQuery object.
var superblock = $(this).closest(".superBlock");
if (superblock.length > 0) {
$watchID = superblock.attr('id');
}
Also, if you want the $watchID variable to persist between calls, it should be declared outside the functions. Your variable is local to each function, so it gets discarded when the function returns.
And since you just want the closest parent with that class, use .closest() rather than .parents(), which searches the entire DOM hierarchy for multiple matches.

Related

jquery read keys from type object

I am trying to implement Modal in bootstrap 5. I am following the link http://jsfiddle.net/341tfz8j/1/ . I have changed all his bootstrap 4 references such as data-toggle to data-bs-toggle and data-target to data-bs-target.
Below is my function:
$(function(){
$('#myModal').modal({
keyboard: true,
backdrop: "static",
show:false,
}).on('show.bs.modal', function(){
Line 1 console.dir($(this).data()); //see the image below
Line 2 console.log('Type of variable '+ typeof mydata); /this is object
console.log($(this).data('myrow')); //this is undefined
});
$(".table-bordered").find('tr[data-bs-target]').on('click', function(){
$('#myModal').data('myrow', $(this));
Line 3 console.dir($('#myModal').data('myrow')); // I am able to get the row here
});
});
When I click on the row of my table, I am able to read the entire row and store it inside the modal.data. as 'myrow'. I am even able to read the key back and get the output (Line 3)
Now i am trying to access the same data inside show method. Below is the image for Line 1
Line 2 : shows that the variable is of type object
Line 3: When I try to read it, I get undefined even though i am able to see 'myrow' key as shown in the fig.
I want to know how can i access they 'myrow' key which is stored inside the object. I have tried below and both are undefined.
$(this).data('myrow')
$(this).data.myrow
My html
<div id="myModal" class="modal hide fade " >
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal Title</h5>
<button type="button" class="close" data-bs-dismiss="modal">×</button>
</div>
<div class="modal-body">
<h1> content goes here</h1>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">cancel</button>
</div>
</div>
</div>
</div>
Since $(this).data() returns an object, you may access myrow property using
$(this).data().myrow

Modal won't close and prevent default on no click, and won't execute func on yes click

I have a modal with two buttons. One is a yes button and one is a no button. If yes button is pressed, I would like the remainder of the function to execute. If no btn clicked, I would like the page to prevent default and not execute. However, it seems that regardless of which button is clicked, nothing happens besides the modal closing. I am using a modal example I found elsewhere, so this may be the issue. After glancing at it for some time I cannot seem to find where the issue is. Am I missing something small? Or perhaps my Jquery is wrong? Below is my code:
Modal:
<!-- Modal for delete-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content border-primary mb-3 box-shadow-none img-responsive">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="card-body bg-light">
<div id="del" class="center">
<label>Are you sure you want to delete?</label>
</div>
</div>
<div class="modal-footer">
<div id="deleteYes">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteYes">Yes</button>
</div>
<div id="deleteNo">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteNo">No</button>
</div>
</div>
</div>
</div>
</div>
And here is my Jquery:
$(".btnDeleteTerminalCommand").click(function (e) {
$("#deleteModal").modal('toggle');
if ($("#deleteNo").click) {
return e.preventDefault();
}
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
var termId = row.find(".tdTermId").html().trim();
var cmdId = row.find(".tdCmdId").html().trim();
var cmdVal = row.find(".tdCmdVal").html().trim();
var cmdID = row.find(".cmdID").html().trim();
var data = {
TerminalID: termId,
CommandID: cmdId,
CommandValue: cmdVal,
ID: cmdID
};
$.ajax({
url: '#Url.Action("DeleteTerminalCommand", "TerminalCommand")',
type: "POST",
data: data,
success: function (response) {
console.log("Success");
window.location.href = response.Url;
}
});
});
Any advice helps! Thank you!
Your click handler will toggle the modal and immediately continue to execute the rest of the function before the user can click anything. If your modal has two buttons, create a click handler for each button. Perhaps the No button just closes the modal. The Yes button handler can execute the actions required to accomplish the task.
$(".btnDeleteTerminalCommand").click(function(e){
$("#deleteModal").modal('toggle');
}
$("#deleteNo").click(function(e){
$("#deleteModal").modal('hide');
}
$("#deleteYes").click(function(e){
// build data object
// ajax post
}

Changing data in bootstrap modal

I'm working on jeopardy game where I pass questions into a bootstrap modal based on the button clicked. The button has an attribute data-num, (the index in the array of questions), which is used to to change the title in the modal. It also passes this index as an attribute data-num to the reveal answer button, which, when clicked, will change modal title to the answer.
This works for the first question, but when I click on the second question, the proper question loads, but the answer to the first question loads when I click the getanswer button, even though the proper index shows up in inspect element under button data-num.
What am I doing wrong?
var questions = [{
prompt: "What generic data type should we use when we want to use varying data types for a variable?",
correctAnswer: "Object",
},
{
prompt: "Rewrite the following Javascript statment in C#: var flag = true ",
correctAnswer: "bool flag = true"
},
{
prompt: "double num1 = 9.34534910;\n int num2= (int)num1;\nSystem.Console.WriteLine(num2);",
correctAnswer: "9"
}
];
function showQuestion(event, $modal) {
var button = $(event.relatedTarget);
var num = parseInt(button.data('num'));
var question = questions[num];
$modal.find('.modal-title').text(question.prompt);
$modal.find('.modal-body button').attr('data-num', num)
}
$("#myModal").on('show.bs.modal', function(event) {
showQuestion(event, $(this));
}
);
$("#myModal").on('hidden.bs.modal', function() {
$('#myModal').removeData('bs.modal');
}
);
$("#getanswer").click(function() {
var num = ($(this).data('num'));
console.log(num)
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bs-example">
<!-- Modal HTML -->
<div id="myModal" class="modal fade">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<p class="modal-title" data-answer="">Modal Window</p>
<button id="getanswer" type="button" data-num="" class="btn btn-primary clickable">Reveal answer</button>
</div>
</div>
</div>
</div>
<div class="question">
<button type="button" class="btn btn-info gridbtn ten" data-toggle="modal" data-target="#myModal" data-num="0">$10</button>
</div>
<div class="question">
<button type="button" class="btn btn-info gridbtn fifty" data-toggle="modal" data-target="#myModal" data-num="1">$50</button>
</div>
</div>
Use this (on the #getAnswer click event):
var num = ($(this).attr('data-num'));
instead of
var num = ($(this).data('num'));
Perhaps since you set the value with attr, it also works to retrieve it that way.
It DOES seem like your way should work, but this is what I found through trying stuff.

Why is my button propagating event to its parent?

I've made a small trick in a div where I put my own "data" precising what to do if the user clicks on it.
My JavaScript code looks like (lot of code omitted for sake of clarity):
$('[data-hqf-switch]').click(function() {
var t = $(this).attr('data-hqf-switch').split('/'),
i = 0;
if (t % 2) {
alert('Burn the dev. Its the dev. himself who wrote that.');
return;
}
while (i < t.length) {
var ev = sw(t[i++], '$')+'.'+sw(t[i++], 'd')+';';
eval(ev);
}
});
Now in my HTML I have something like that:
<div class="col-lg-12" data-hqf-switch="$.pt().pv()/Xd/$.pt()/Xu">
<h4>25 mars 2016 22:07 - You wrote...</h4>
<p>J'ai refusé votre invitation</p>
<button type="button" class="btn btn-default"
data-toggle="modal"
data-target="#modal-msg-7-24" title="Répondre">
<i class="fa fa-envelope-o"></i> Répondre
</button>
<div class="modal fade" id="modal-msg-7-24" tabindex="-1"
role="dialog"
aria-labelledby="Envoyer un message" aria-hidden="true"
style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
<button class="btn btn-warning"
data-hqf-switch="$.pt().pt().pv()/Xd/$.pt().pt()/Xu">
Fermer
</button>
</div>
The most important is the first button: when clicked it shows the modal dialog box which is declared just after the button.
Everything should work fine except that when you click on the button it's like you click on the button and on the "surrounding" div because the event of the div is launched too.
What am I missing?
Event propagation means the event is handled for the clicked element and all ancestors.
You may want to look into event.stopPropagation().
I believe your small trick will eventually make you regret the day you invented it if you're doing anything moderately complicated.
The solution is here. And it's not a duplicate, even though it's close to.
I just test if the element the user "has pushed" has actually the "switch data". If not, I return instantaneously because I suppose (and I dont imagine a case where it's not) that it's one of the children of this element, not the element itself.
$('[data-hqf-switch]').click(function(e) {
if ($(e.target).filter(':not([data-hqf-switch])').length) {
return;
}
/* ok the target contains a 'data-hqf-switch' attribute */
/* ... blabla ...*/
}

How to get value of data-id and place it into a twitter bootstrap modal?

Im trying to get the value of the data-id which contains and id in my database. I need to get the admin_id and place it into a twitter bootstrap modal. How am I going to get that value using java script?
<a data-toggle="modal" data-id="<?=$row['ADMIN_ID'];?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
here is my modal
<div class="modal fade" id="view_contact" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4>Admin modal!!</h4>
</div>
<div class="modal-body">
Admin Id:<p id="showid"></p>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
here is my java script
<script type="text/javascript">
$(document).on("click", ".view-admin", function () {
var adminid = $(this).data('id');
$(".modal-body #showid").val( adminid );
$('#view_contact').modal('show');
});
</script>
its not showing in my modal. They are all in the same page. How do I do this? Kinda new at this.
Problem is, you are trying to assign the value to a p tag. p tag does not have value property. Use text() or html()
$(document).on("click", ".view-admin", function() {
var adminid = $(this).data('id');
$(".modal-body #showid").text(adminid);
$('#view_contact').modal('show');
});
You can just replace
$(".modal-body #showid").val( adminid );
with
$("#showid").text( adminid );
You don't need to reference class name .modal-body for the id #showid as there must be only one id name in a page according to W3C Validation. And referencing with the id is the fastest way to access any html elements.

Categories