Trouble getting index of class with jQuery - javascript

I have a few hidden modals on a page that I want to control with a single block of javascript code.
I'm trying to test to see if I'm getting the correct close button with class close, but my console.log is currently printing -1.
HTML
<span class="open">Button A</span>
<span class="open">Button B</span>
<!--modal-->
<div class="modal">
<!--modal content-->
<div class="modal-content">
<!--close button-->
<span class="close">×</span>
<!--content A-->
</div>
</div>
<!--modal-->
<div class="modal">
<!--modal content-->
<div class="modal-content">
<!--close button-->
<span class="close">×</span>
<!--content B-->
</div>
</div>
JS
$(document).ready( function() {
//when a class '.open' is clicked
$('.open').click(function(){
//store the index of the clicked span in a variable
var indexer = $('.open').index(this);
//test output - working
console.log("open. " + indexer);
//store all classes '.close' in a variable
var close = $('.close');
//store '.close' with same index as clicked button
var closeindex = $('.close').index(indexer);
console.log(closeindex);
});
});
I'm trying to walk through this click function and assign each class with the correct index to a variable, and I'm using console.log to print the indexes to the console.
With console.log(closeindex), I'm trying to get the index of the close button that has a matching index of span .open that was clicked, but currently it's returning -1.
I want to eventually do something like:
close.click = function() {
$('.modal').index(indexer).style.display = "none";
}

var closeindex = $('.close').eq(indexer);
Ok, so if you have a relationship between open and close such that the 3rd open related to the 3rd close, then you can get the related close by using the eq() method as above.
eq() will get you the element at that index, keeping it as a jQuery object.

If you're trying to open and close modal dialogs based on the buttons, I'd like to suggest an alternative method to indexes. With indexes, any refactoring/reordering of your elements is liable to throwing your code off entirely.
Consider using data attributes to keep track of what modal each open button is referring to. That way, no matter where your button/modals are, they are permanently linked.
If you give each modal an ID, and then add that ID to a data attribute on your open button...
<span class="open" data-modal="modal1">Open Modal 1</span>
<div class="modal" id="modal1"></div>
...then you can easily relate open buttons to their proper modals.
The close buttons can simply say "Close my parent modal" when clicked. We can do this using .closest( selector ) which traverses upwards in the DOM to find the first matching ancestor.
Working Example:
$(".open").on("click", function() {
$(".modal").hide(); //Hide all open modals
var modalId = $(this).data("modal"); //Get the Modal ID from the data-modal attribute
var $modal = $("#" + modalId); //Select the modal with that ID
$modal.show(); //Show it
});
$(".close").on("click", function() {
$(this).closest(".modal").hide(); //Close the closest modal (ancestry-wise)
});
div.modal {
display: none;
padding: 50px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="open" data-modal="modal1">Button A</span>
<span class="open" data-modal="modal2">Button B</span>
<!--modal-->
<div class="modal" id="modal1">
<!--modal content-->
<div class="modal-content">
I'm modal 1!
<!--close button-->
<span class="close">×</span>
<!--content A-->
</div>
</div>
<!--modal-->
<div class="modal" id="modal2">
<!--modal content-->
<div class="modal-content">
I'm modal 2!
<!--close button-->
<span class="close">×</span>
<!--content B-->
</div>
</div>
<!-- -->

Related

Getting the id of the anchor tag which was clicked

This is a list representation of data which is coming from a php database.The list is fetched using a foreach php loop and the data inside the achor tag is populated accordingly.
<?php foreach($array as $iterate):?>
<div class="col-sm-3">
<div class="panel panel-default">
**<a onClick='theFunction();' id="hello" href="#myModal" style="text-decoration:none;">**
<div class="panel-heading">
<img src ="audi_sillhouete.jpg" style="height:100%; width:100%;">
<p id="10" style="position:absolute; top:10%; padding-left:5%; padding-right:15%;"><?php echo $iterate->test_name ?></p>
</div>
</a>
</div>
</div>
<?php endforeach;?>
As you can see here, inside the anchor tag i have href-ed it to a modal box which will show a message whenever the user clicks on any of the link. There is a button in the modal window which will take the user to a different page.
The issue is that i want to pass certain value along with the url, but cannot do so as the link to the next page is defined in the modal window specification part.
So i came up with this solution. I thought of using the id attribute of the anchor tag, I tried to get the id attribute of the anchor which was clicked using javascript.
<script type="text/javascript">
function theFunction()
{
var id = $('a', this).attr('id');
alert(id);
}</script>
From this i wanted to initialize a php variable and then use that php variable to pass as value in the href of the modal window button. But the value i am getting in the alert box is 'undefined' for some reason. I have tried all possible combinations of this.
$('a',this).attr('id');
$this.id;
Everything return 'undefined'.
Reference-This is the code for the modal window part.
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Instructions</h4>
</div>
<div class="modal-body">
Your test is about to commence. A timer will be initiated after the moment you start the test. You may choose to answer a question, or leave it empty. You can also attempt the questions in any order that you find suitable.<br><br>Upon completion of the test, click on "Submit" to see your performance statistics.<br><br><br>Good luck!
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Continue</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Please try this
$(document).on('click', 'a', function () {
alert(this.id);
});
DEMO
You can use other attribute in anchor like :
<a href='' id='hello' para-id='somevalue'></a>
alert($("#hello").attr("para-id"));
The below jQuery function runs through all the a tags on page load and adds id to the end of the link.
$(function(){
$('a').each(function(){
var id = $(this).attr('id');
var url = $(this).attr('href') + '?id=' + id;
$(this).attr('href',url);
});
});
https://jsfiddle.net/yc1hswet/

Clicking sub menu pop up a modal in wordpress plugin

I am working on a Wordpress plugin where I want to open a pop-up modal when I click on one of my plugin sub-menus. I can trigger the modal using a link or a button, but I want to load the modal at the time I click on the submenu.
Code for menu and submenu:
<div class="wp-menu-name">Smart Form Builder</div>
<ul class="wp-submenu wp-submenu-wrap">
<li class="wp-submenu-head">Smart Form Builder</li>
<li class="wp-first-item">
<a class="wp-first-item" href="admin.php?page=smart-form-builder">Create New Form</a>
</li>
<li>
Form List
</li>
<li>
Support
</li>
</ul>
</div>
Code for my model:
<div class="modal fade" id="modal_choose_ur_form" tabindex="-1" role="dialog" aria-labelledby="modal_choose_ur_formLabel">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><h3>Choose Your Form</h3></h4>
</div>
<div class="modal-body">
Click
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Now i want to pop up the modal when i click on Create New Form submenu. So what i have code in my sfb_create_form_page function?
I tried using various way of using javascript like
<script type="text/javascript">
$(document).ready(function () {
$('#modal_choose_ur_form').modal('show');
});
</script>
this is working for a simple HTML page quite well but not for my plugin. What can do can anyone help?
Here you go. Link
You need to fire click event on ul li . And open popup when click event is generated.
$(document).ready(function () {
$(".ulLiOuter ul li").click(function(e){
e.preventDefault();
$('#modal_choose_ur_form').modal('show');
});
});
I am using like this.
Go to wp-admin/nav-menus.php page and open the "Show Settings" from top, Check the (XFN) checkbox then write to xfn input some rel value "like a modal" than add your .js file this code
$('a[rel="modal"]').click(function () {
$("#modal-id").modal();
});

Bootstrap Modal Not Displaying, outputs JS

I have a bootstrap modal setup with the following code:
<div class="modal hide fade" id="myModal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Testimonials</h3>
</div>
<div class="modal-body">
<p>Test Text Here</p>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal">Close</a>
</div>
</div>
<button class="btns btn-3 btn-3g btnsx" data-toggle="modal" href="#myModal">More</button>
However, I am getting only a black background when clicking the button.
I am also seeing some of my js appearing at the bottom of my page (only when the modal code is inserted):
.on('submit', function() { var form = $(this); var post_data = form.serialize(); //Serialized the form data for process.php $('#loader').html('loadng Please Wait...'); $.ajax({ type: 'POST', url: 'http://shazconstruction.com/test/process.php', // Your form script data: post_data, success: function(msg) { $('#loader').html(''); // We know this is the form that needs fading in/out $('form#contactUs').fadeOut(500, function(){ $('form#contactUs').html(msg).fadeIn(); }); } }); return false; }); });
Here is the site where everything exists:
http://bit.ly/1dbf4Rz
For reference, this is the section with the modal setup:
http://i.imgur.com/1SlNR1s.png
Check out the source of your page. However it's being generated has a pretty clear error: http://screencast.com/t/GZv0KwPktoO
Look at line 762. There is no opening script tag, so that would explain why you're seeing your JS appearing at the bottom of the page.
As for the rest of it, BaBL86 is right, you will want to fix the issue with your mousewheel script as it's throwing errors that cause the page to stop rendering JS.
Once those two issues are fixed, let us know if there are still problems.
Edit: You also have incorrect HTML for your modal window (based off the bootstrap 3 documentation). Try using this instead, and moving your modal window to right after the body tag:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Test Header</h3>
</div>
<div class="modal-body">
<p>Test Text Here</p>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
You have an error in your mousewheel function. Check this answer, it's about this problem:
function handler(event) {
< ---- >
return $.event.handle.apply(this, args); // error here
}
Edit your function to:
return $.event.dispatch.apply(this, args);
You have given !important to .hide. Remove the imporant
From this
display: none!important;
To
display: none;
I can also see that you are not giving any background-color. Use the same code from bootstrap

Passing Data to Bootstrap Modals

I am trying to create a simple modal using twitter bootstrap. The function of that modal is to take the name of the link clicked on, and use that name as a header. Each of the names are in a Django Database. I followed this link for reference: Passing data to a bootstrap modal
#Button to toggle modal
<a data-toggle="modal" data-id="{{ name }}" title="Add this item" class="open- AddBookDialog " href="#addBookDialog">{{ name }}</a><br />
#Modal
<div class="modal hide fade" id="addBookDialog">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<input type="text" name="nameId" id="nameId" />
<p>some content</p>
</div>
</div>
#JavaScript
<script type="text/javascript">
$(document).on("click", ".open-AddBookDialog", function () {
var myNameId = $(this).data('id');
$("modal-body #nameId").val( myNameId );
});
</script>
What the above does is displays a text box with the characters name in the box. What I would like is to have the name as the header, not in a text box. When I remove the textbox, and place a header tag with the same id and name, nothing will show. Is there a way to complete this task.
the header is the first h3 in the modal.
So you need to add a h3 element under ".modal-header" with an id and set the .html() of that element. :)
Look here for reference: http://twitter.github.io/bootstrap/javascript.html#modals
Here's the code:
#Modal
<div class="modal hide fade" id="addBookDialog">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3 class="hdrtitle">This is the header</h3>
</div>
<div class="modal-body">
<input type="text" name="nameId" id="nameId" />
<p>some content</p>
</div>
</div>
Using a code like:
$('.modal .hdrtitle').html('This is the header');
and then showing it with:
$('.modal').modal('toggle');
works.
The one-off way
If this is the only time you'll ever need to do a UI-binding behavior in your site/app, do something like this:
$('.header-link').click(function(e) {
$('.modal-header h4').html($(e.target).html())
})
CodePen Demo
This will just take the text (actually the HTML) in the link itself and put that in the header.
Using a library
If you plan to do these sorts of cool tricks in more parts of your app, consider using a UI-binding library like Angular JS or Knockout. This way you can data-bind parts of your UI with events.
I found the answer. Thanks to #PaoloCasciello for a layout.
Instead of an .on function in javascript, it really needed to be .html. So here is what the final code will look like.
<!-- Modal -->
<div class="modal hide fade" id="addBookDialog">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3 id="nameId" />
</div>
<div class="modal-body">
<p>some content</p>
</div>
</div>
<script type="text/javascript">
$(document).on("click", ".open-AddBookDialog", function () {
var myNameId = $(this).data('id');
var myNameDescription = $(this).data('description');
$(".modal-header #nameId").html( myNameId );

Jquery multiple modals plugin

I'm using this simple jquery plugin for modal popups but it doesn't have a function for multiple popups so I'm trying to make my own.
First I added unique indexes to the buttons that open the modal and the modal divs. The HTML is created dynamically.
<button class="my_modal_open" id="1">Open modal</button>
<div id="my_modal" class="1" style="display:none;margin:1em;">
×
Modal Content
</div>
<button class="my_modal_open" id="2">Open modal</button>
<div id="my_modal" class="2" style="display:none;margin:1em;">
×
Modal Content
</div>
<button class="my_modal_open" id="3">Open modal</button>
<div id="my_modal" class="3" style="display:none;margin:1em;">
×
Modal Content
</div>
And then I modified the js to open modals by appropriate index.
$(document).ready(function() {
$('.my_modal_open').click( function() {
$('#my_modal').css('display','none'); //added
var open_id = $(this).attr('id'); //added
$('#my_modal.' + open_id).popup(); //changed to get div id and class
});
});
This works but the modals open only once. As a fix I tried adding
$('#my_modal').css('display','block');
after the popup() function which works but the modal doesn't display in the right position, the second time.
Please share any suggestions. Hopefully someone used this plugin before.
You might want to look at other libraries like jQuery UI or Twitter Bootstrap, since they have already solved this problem. If you want to roll your own, I would change your approach slightly.
Add an attribute to the buttons which stores the ID of the modal dialog you want to show. In the example below I called it "data-modal-id". When you click the button, get the value of that attribute and look up the modal with that ID and show it:
HTML
<button class="my_modal_open" data-modal-id="1">Open modal</button>
<div id="1" style="display:none;margin:1em;">
×
Modal Content
</div>
<button class="my_modal_open" data-modal-id="2">Open modal</button>
<div id="2"style="display:none;margin:1em;">
×
Modal Content
</div>
<button class="my_modal_open" data-modal-id="3">Open modal</button>
<div id="3" style="display:none;margin:1em;">
×
Modal Content
</div>
jQuery
$(document).ready(function () {
$('.my_modal_open').click(function () {
$('#' + $(this).data("modal-id")).popup()
});
});
Working Demo
You can use fadeIn() and fadeOut().
Example
Create something like
<div class="my_modal_background"></div>
where in css
.my_modal_background{ background:#000; position:fixed; width:100%; height:100%; z-indez:0 }
.my_modal_open div{ z-index:1; }
And your Jquery must be like this
$(document).ready(function () {
$('.my_modal_open').click(function () {
$(this).children('div').fadeIn();
$('.my_modal_background').fadeIn();
});
});

Categories

Resources