PrePended Button Does Not Appear to be firing - javascript

Added
$('#'+course.code).append('<button class="collapsible">'+course.title+'</button>');
To add a button to each div with an ID of course code. The works fine. When I click the button it won't fire the code below. If I copy and paste this exact code it works fine. Does generating a button list of buttons with prepend effect its functionality?
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
alert('sup');
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
Here is the final generated code
<div id="472101A" class="course_card"><button class="collapsible">AP Calculus BC</button>
<div class="row content">
<div class="col-xs-12 col-sm-3">
<p><b>Course Title:</b> <span class="course_title">AP Calculus BC</span></p>
<p><b>Course Code:</b> <span class="course_code">472101A</span></p>
<p><b>Level:</b> <span class="course_level">AP</span></p>
<p><b>Credit(s):</b> <span class="course_credits">1</span></p>
<p><b>Semester(s):</b> <span class="course_semesters">2</span></p>
<p class="course_fee"><b>Course Fee:</b> <span>N/A</span></p>
<p></p></div>
<div class="col-xs-12 col-sm-9">
<div class="course_desc_wrapper">
<p><b>Description:</b></p>
<p class="course_desc">Suggested Skills: Basic understanding of function behavior, such as polynomials, rationals, rational exponent, trigonometric functions and other transcendental functions. Should be able to solve, graph, evaluate and analyze those functions. Should be able to apply those functions to model real world phenomena. Class covers BOTH Calculus 1 and 2. Accelerated Pace. Students should be able to process and apply information at a very fast pace.</p></div>
<div class="course_requirements_wrapper">
<p><b>Prerequisite Classes & Grades:</b></p>
<p class="course_prerequisites">Honors PreCalculus: Students must earn an A,B both semesters and pass a proficiency exam in May
OR
Regular PreCalculus: Students must earn an A both semesters and pass a proficiency exam in May
OR
ATP: Students must earn an A,B both semesters and pass a proficiency exam in May
</p></div>
<div class="course_typicalGradeLevel_wrapper">
<p><b>Typical Grade Level:</b></p>
<p class="course_typicalGradeLevel">11-12</p></div>
<div class="course_levelOfChallenge_wrapper">
<p><b>Level of Challenge (1-5) 5 is extremely challenging:</b></p>
<p class="course_levelOfChallenge">5</p></div>
<div class="course_homeworkCommitment_wrapper">
<p><b>Typical Homework Commitment:</b></p>
<p class="course_homeworkCommitment">4-6</p></div>
<div class="course_careerAspirations_wrapper">
<p><b>Interests / Career Aspirations:</b></p>
<p class="course_careerAspirations">Engineering, Computer Science, Business</p></div>
<div class="course_requirements_wrapper">
<p><b>Other:</b></p>
<p class="course_notes">Suggested Skills: Basic understanding of function behavior, such as polynomials, rationals, rational exponent, trigonometric functions and other transcendental functions. Should be able to solve, graph, evaluate and analyze those functions. Should be able to apply those functions to model real world phenomena. Class covers BOTH Calculus 1 and 2. Accelerated Pace. Students should be able to process and apply information at a very fast pace.</p></div>
<div class="ap_wrapper">
<p><i>*All AP Courses are expected to have a $100 fee ($25 class fee and $75 exam fee).</i></p>
<p><i>The exact exam fee for testing in May 2016 will be released by the CollegeBoard in October 2015. This exam fee determines the total price that students will owe for each AP Course/exam. The AP exam fee may be fully or partially reduced for students with free/reduced lunch, per funding by district and state grants. The exact fee will be provided as soon as the district and state release their funding statement.</i></p>
<p></p></div>
<p></p></div>
<p></p></div>
<hr></div>

It sounds like you are setting the event listener before the element is created. Make sure you run your for loop after the jQuery append statement.
Just to make sure the elements exist when you are setting the listener you could run console.log(coll[i]) to tell you for certain if the element exists yet at that point in execution.
Another option is to use jQuery's on function. So in your case you could use something like this:
$('body').on('click', '.collapsible', function() {
// do something
})
This gives you the benefit that it will trigger even if you append elements to the page after running this function. This will also work for any .collapsible element, and doesn't have to be applied to each one individually.

Related

how to get a word inside a text html and underline it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a text inside an HTML tag <p>text</p>, then I have a <form> and a <input type="text"> inside and a submit.
The goal of the exercise: when I write characters in the input then I click on button (submit), or any other word, or not a complete word, or (,.!!),it has to be underlined with the red color in the text the space has not to be underlined .here s my code below :example I write "Anyone" then I submit, I mean the first word in the text , all the words "anyone" have to be underlined in red.
var x = document.getElementById('text').innerHTML;
var splt = x.split(/\W+/);
console.log(splt);
var inpt=document.getElementById('input').value;
console.log(inpt);
var lent = splt.length;
console.log(lent);
var myArray =[" "];
for( i = 0; i < splt.length ; i++ ){
myArray.push(splt[i]);
}
console.log(myArray);
for(var j=0;i<myArray.length;i++){
for(var k=0;k<myArray[i].length;k++){
if((myArray[j]==splt)){
}
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
<div class="row">
<div class="col-5">
<form class="form-group" action="index.html" method="post">
<input type="text" name="" value="" id ="input" onkeyup="find()" placeholder="cerca">
<button class ="Btn btn-danger" type="button" name="button">search</button>
</form>
<h1>hello</h1>
<p class="text-justify" id = "text">Anyone who reads Old and Middle English literary texts will be familiar with the mid-brown volumes of the EETS, with the symbol of Alfred's jewel embossed on the front cover. Most of the works attributed to King Alfred or to Aelfric, along with some of those by bishop Wulfstan and much anonymous prose and verse from the pre-Conquest period, are to be found within the Society's three series; all of the surviving medieval drama, most of the Middle English romances, much religious and secular prose and verse including the English works of John Gower, Thomas Hoccleve and most of Caxton's prints all find their place in the publications. Without EETS editions, study of medieval English texts would hardly be possible.</p>
<p class="text-justify" id = "text">As its name states, EETS was begun as a 'club', and it retains certain features of that even now. It has no physical location, or even office, no paid staff or editors, but books in the Original Series are published in the first place to satisfy subscriptions paid by individuals or institutions. This means that there is need for a regular sequence of new editions, normally one or two per year; achieving that sequence can pose problems for the Editorial Secretary, who may have too few or too many texts ready for publication at any one time. Details on a separate sheet explain how individual (but not institutional) members can choose to take certain back volumes in place of the newly published volumes against their subscriptions. On the same sheet are given details about the very advantageous discount available to individual members on all back numbers. In 1970 a Supplementary Series was begun, a series which only appears occasionally (it currently has 24 volumes within it); some of these are new editions of texts earlier appearing in the main series. Again these volumes are available at publication and later at a substantial discount to members. All these advantages can only be obtained through the Membership Secretary (the books are sent by post); they are not available through bookshops, and such bookstores as carry EETS books have only a very limited selection of the many published.</p>
</div>
</div>
</div>
function highLightText(){
var characters = $('#text');
var pageText = characters.text().replace("<span>","").replace("</span>");
var searchedText = $('#input').val();
var theRegEx = new RegExp("("+searchedText+")", "igm");
var newText = pageText.replace(theRegEx ,"<span>$1</span>");
characters.html(newText);
}
#text span
{
text-decoration: underline;
text-decoration-color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SEARCH</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-5">
<input type="text" name="" value="" id ="input" onkeyup="find()" placeholder="cerca">
<button class ="Btn btn-danger" type="button" name="button" onclick="highLightText()">search</button>
<h1>hello</h1>
<p class="text-justify" id = "text">
Anyone who reads Old and Middle English literary texts will be familiar with the mid-brown volumes of the EETS, with the symbol of Alfred's jewel embossed on the front cover. Most of the works attributed to King Alfred or to Aelfric, along with some of those by bishop Wulfstan and much anonymous prose and verse from the pre-Conquest period, are to be found within the Society's three series; all of the surviving medieval drama, most of the Middle English romances, much religious and secular prose and verse including the English works of John Gower, Thomas Hoccleve and most of Caxton's prints all find their place in the publications. Without EETS editions, study of medieval English texts would hardly be possible.
As its name states, EETS was begun as a 'club', and it retains certain features of that even now. It has no physical location, or even office, no paid staff or editors, but books in the Original Series are published in the first place to satisfy subscriptions paid by individuals or institutions. This means that there is need for a regular sequence of new editions, normally one or two per year; achieving that sequence can pose problems for the Editorial Secretary, who may have too few or too many texts ready for publication at any one time. Details on a separate sheet explain how individual (but not institutional) members can choose to take certain back volumes in place of the newly published volumes against their subscriptions. On the same sheet are given details about the very advantageous discount available to individual members on all back numbers. In 1970 a Supplementary Series was begun, a series which only appears occasionally (it currently has 24 volumes within it); some of these are new editions of texts earlier appearing in the main series. Again these volumes are available at publication and later at a substantial discount to members. All these advantages can only be obtained through the Membership Secretary (the books are sent by post); they are not available through bookshops, and such bookstores as carry EETS books have only a very limited selection of the many published.
</p>
</p>
</div>
</div>
</div>
</body>
</html>
Reference
Alright! I tried in Vanilla JS. Have a look https://codepen.io/navdeepsingh/pen/bLjqyy``
const search = document.querySelector('#search');
const wrapper = document.querySelector('#wrapper');
const wrapperText = wrapper.innerHTML;
let newText = '';
search.addEventListener('keyup', function() {
const regex = new RegExp(this.value, 'g');
if (this.value.length > 3) {
if (wrapperText.includes(this.value)) {
newText = wrapperText.replace(regex, `<span class="hl">${this.value}</span>`);
wrapper.innerHTML = newText;
}
} else {
const hlElems = document.querySelectorAll(".hl");
hlElems.forEach(el => {
el.classList.remove('hl');
});
}
});
.hl {
background-color: gold;
}
<input type="text" placeholder="Search.." id="search" name="search" autofocus>
<div id="wrapper">
<p> It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</p>
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p>
</div>

How to insert HTML between 2nd and 3rd paragraph tags in a class?

I have this bit of HTML. I want to insert in the div class content between 2nd and 3rd paragraph tag. I saw .insertAfter() and .insertBefore(). How to do this in plain vanilla JS?
<div class="content">
<div class="lead-image"><img src="/rf/Image-621x414/LiveMint/Period2/2017/10/13/Photos/Processed/bhart-kvpG--621x414#LiveMint.JPG" alt="Vodafone-Idea combine is ahead by a sizeable margin. Photo: Pradeep Gaur/Mint" class="img-responsive">
<div class="img-caption">In a few quarters, Airtel will end up as a clear market leader in terms of revenue market share, even though currently, the Vodafone-Idea combine is ahead by a sizeable margin. Photo: Pradeep Gaur/Mint</div>
</div>
<p xmlns:fn="http://www.w3.org/2005/xpath-functions" class="A5l">After Telenor ASA decided to hand over its India mobile business to Bharti Airtel Ltd for free, the Tata group has done the same. In the June quarter, revenues of these companies together stood at Rs3,202 crore, or nearly $2 billion on an annualized basis. Sure, since Tata’s non-mobile businesses, such as broadband, are being retained, the actual revenue that could potentially accrue to Airtel could be lower.</p>
<p>Still, even using conservative estimates, the Tatas are transferring at least a $1 billion business to Airtel for free. Telenor’s annualized revenues stood at $606 million in the June quarter. </p>
<p>In fact, the Tatas have gone a step further compared to Telenor. For the latter, Airtel agreed to take over outstanding spectrum payments, other operational contracts such as tower leases and employees. But the deal with the Tatas is even sweeter; it will take over only a portion of outstanding spectrum payments and it’s not clear whether operational contracts and employees are part of the deal.</p>
<p>The simple reason Airtel is able to strike such deals is that it is the only buyer in the market. Vodafone India Ltd and Idea Cellular Ltd have enough on their plate with their own merger, and the last thing they would want to engage with is the integration of another telco. Reliance Jio Infocomm Ltd, after having spent Rs2 trillion already in building its network, appears self-sufficient. Of course, these are also distress sales, given the high-cash burn at these companies. For sellers, therefore, one big hope is if Airtel evinces some interest. The only other option is to wind down the business, which entails far higher costs. </p>
<p>A Tata Sons executive told <i>Mint</i> the cost of winding down the business would have been about Rs8,000 crore higher than the current arrangement. Knowing this well, Airtel has stayed shy of rushing into deals, and has waited till sellers agree to its terms.</p>
<div class="mobile-ad">
<div id="div-gpt-ad-1492578481854-0" style="height: 250px; width: 300px; display: none;">
<script>
googletag.cmd.push(function() {
googletag.display('div-gpt-ad-1492578481854-0');
});
</script>
<div id="google_ads_iframe_/3106570/LM_WAP_Story_300x250_Top_0__container__" style="border: 0pt none;">
<iframe id="google_ads_iframe_/3106570/LM_WAP_Story_300x250_Top_0" title="3rd party ad content" name="google_ads_iframe_/3106570/LM_WAP_Story_300x250_Top_0" width="300" height="250" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" srcdoc="" style="border: 0px; vertical-align: bottom;"></iframe>
</div>
</div>
</div>
<p></p>
<p>This puts it in an enviable position; such takeovers help grow market share as well as help plug gaps in its spectrum portfolio at a fairly low cost. In addition, with Vodafone and Idea busy with the merger process, and given the uncertainty among their employees, Airtel can grab market share from its large rivals as well.</p>
<p></p>
<div id="chart-box">
<img class="img-responsive" src="/r/LiveMint/Period2/2017/10/13/Photos/Processed/w_m2m_infratel-kvpG--414x621#LiveMint.jpg" title="">
<div class="zoom_icon"><a class="zoom-icon" href="/r/LiveMint/Period2/2017/10/13/Photos/Processed/w_m2m_infratel-kvpG--414x621#LiveMint.jpg" title="">Click here for enlarge</a></div>
</div>
<link href="/r/PortalConfig/LiveMint/static_content/css/v2/lightbox.css" type="text/css" rel="stylesheet">
<p></p>
<p>However, when things improve—hopefully with Jio’s approval for higher tariffs—Airtel can be expected to be in a fairly strong position as it gobbles up small telcos one after another and also gains share from other companies.</p>
<div class="story-meta"><span>First Published: </span>Fri, Oct 13 2017. 07 16 AM IST
<div class="story-tags">Topics: Airtel Tata Teleservices Airtel Tata Tele acquisition Airtel acquisitions Telenor ASA </div>
</div>
</div>
I am trying to do it in the best possible way. The class name is unique and I can then iterate through. What is the right way?
var myfirstcontent = document.getElementsByClassName('content')[0];
//find paragraphs
var ps = myfirstcontent.getElementsByTagName("p");
// Create a new, plain <div> element
var newdiv1 = document.createElement("div");
// put content etc in the div here...
// Get a reference to the paragraph we want to insert the new div after
var p2 = ps[1];
// Get a reference to the parent element
var parent = p2.parentNode;
// insert after
parent.insertBefore(newdiv1 , p2.nextSibling);
Note if there is no nextSibling it just gets appended to the parent node at the end as that returns null.
How about this?
var div = document.querySelector('div.content');
var thirdP = document.querySelectorAll('div.content > p')[2];
var newDiv = document.createElement('div');
newDiv.innerHTML = '***';
div.insertBefore(newDiv, thirdP);

p paragraph ... in jquery not working?

Hi i'm working with limit text in my p tag but it work only first and third p tag as like this .
How to do apply to all p tag?
$(document).ready(function(){
if('.textSec'){
var p=$('.textSec p');
var divh=$('.textSec').height();
while ($(p).outerHeight()>divh) {
$(p).text(function (index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
}
});
.textSec{border:solid 1px red;display:inline-block;vertical-align:top;height:120px;overflow:hidden; padding:10px; width: 200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="textSec">
<p>LIC's New Children’s Money Back Plan is a participating non-linked money back plan. This plan is
specially designed to meet the educational, marriage and other needs of growing children through
Survival Benefits. In addition, it provides for the risk cover on the life of child during the policy term
and for number of survival benefits on surviving to the end of the specified durations. </p>
</div>
<div class="textSec">
<p>LIC's New Money Back Plan-20 years is a participating
non-linked plan which offers an attractive combination of
protection against death throughout the term of the plan along
with the periodic payment on survival at specified durations
during the term. This unique combination provides financial
support for the family of the deceased policyholder any
time before maturity and lump sum amount at the time of
maturity for the surviving policyholders. This plan also
takes care of liquidity needs through its loan facility.
</p>
</div>
<div class="textSec">
<p>LIC’s Anmol Jeevan - II is a protection plan which provides financial protection to the insured’s family in case of his/her unfortunate demise.
<br >
Benefits:
Death Benefit: In case of unfortunate death of the Life Assured during the policy
term Sum Assured shall be payable.
<br >Maturity Benefit: On survival to the end of the policy term, nothing shall be payable.</p>
</div>
<div class="textSec">
<p>This is an immediate annuity plan, which can be purchased by paying a lump sum amount.
This plan provides for
annuity payments of a stated amount throughout the life time of the annuitant.
Various options are available for the type and mode of payment of annuities. <br />
Premium in this plan is to be paid in a lump sum. Annuity may be paid either at
monthly, quarterly, half yearly or yearly intervals. Annuitant may choose any mode of payment of annuity.</p>
</div>
<div class="textSec">
<p>LIC's Jeevan Arogya is a unique non-participating
non-linked plan which provides health insurance cover
against certain specified health risks and provides you
with timely support in case of medical emergencies and helps
you and your family remain financially independent in difficult
times. Health has been a major concern on everybody’s mind,
including yours. In these days of skyrocketing medical expenses,
when a family member is ill, it is a traumatic time for the rest
of the family. As a caring person, you do not want to let any
unfortunate incident to affect your plans for you and your
family. So why let any medical emergencies shatter your peace
of mind. </p>
</div>
Well you should be setting the height for each paragraph individually and not via the first element.
var p = $('.textSec p'); //grabs all of the paragraphs
var divh=$('.textSec').height(); //we read the height of the first texxtSec element
p.each( function () { //loop over the paragraphs
var para = $(this); //current paragraph
while (para.outerHeight()>divh) { //loop until the height condition is met
para.text(function (index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
});
var p = $('.textsec').find('p') or var p = $('.textsec').children('p') depending on your nested elements.

Javascript code for alphabetizing divs

I'm editing a web page that has a list of doctors names and images wrapped in a div. I'm adding more to that list and my client wants all of the names in alphabetical order now. As apposed to manually doing that (I know my client will also be adding more doctors in the future)I tried writing a script to do the work for me. I wrapped each doctor in a div called "alphabetize," and set a span id of "lastName" around each doctor's last name.
<div class="alphabetize large-6 columns sameheight-wrap">
<div class="large-4 medium-4 columns sameheight PadT20"> <img src="../imgs/dev/crna-staff/John-Doe.jpg" alt=" John Doe, CRNA" class="pictureBottomBorder"> </div>
<div class="large-8 medium-8 columns contenttable sameheight PadT20">
<div class="border vmid text-center bgdblue PadB"> <span class="white medium"><strong>John<span id="lastName">Doe</span></strong><br>
</span> <span class="white PadT5"> MSN, Thomas Jefferson University School of Nurse Anesthesia</span> </div>
</div>
</div>
I placed the following script on that page;
<script>
var $divs = $("div.alphabetize");
$(function() {
var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
return $(a).find("#lastName").text() > $(b).find("#lastName").text();
});
$("#alpha").html(alphabeticallyOrderedDivs);
});
</script>
For some reason, the script is not working correctly. Doctors are out of order and i also need to add a variable to the code that sorts the last names with the first 3 letters. Can anyone help? Javascript is not my strong suit. Not sure if I missed something.
Below is a snippet that will show you how you can easily sort this. The major issue, however, is the following:
return $(a).find("#lastName").text() > $(b).find("#lastName").text();
The sort() function asks to return one of three values, 0 to maintain position, -1 to move it before the current element and 1 to move it after. That means that all you could ever return is after and not before, so your sort fails.
For the solution I would like to suggest using a data-attribute and no more HTML spans and styles that need to be rendered (and probably hidden afterwards), so here is my suggestion:
<div data-alphabetize="John Doe">John Does Content</div>
We can string together a couple of functions to get the correct output. We will need prototype.slice.call to convert the returned-by-querySelector NodeList to an Array, then we need to use sort to sort it alphabetically and finally we can use forEach to go through the array and insert the nodes in the correct position.
I am using vanilla JS - mostly to show how simple things can be done without loading up jQuery. You can, of course, do this with jQuery as well.
// Turn querySelectorAll NodeList into an Array
Array.prototype.slice.call(document.querySelectorAll('[data-alphabetize]'))
// Sort the array by data-alphabetize attribute (reverse order)
.sort(function(a, b){
return a.getAttribute('data-alphabetize') < b.getAttribute('data-alphabetize')
? 1 : -1;
})
// Insert every node in order
.forEach(function(v, i, a){
var parent = v.parentNode;
parent.removeChild(v);
parent.insertBefore(v, parent.childNodes[0]);
});
<div>
<div data-alphabetize="Beta">Joseph Alfred <strong>Beta</strong></div>
<div data-alphabetize="Alpha">Mark Unicode <strong>Alpha</strong></div>
<div data-alphabetize="Gamma">Graham <strong>Gamma</strong>-Python</div>
<div data-alphabetize="Omega">Matthew <strong>Omega</strong></div>
</div>

jQuery UI sortable div's, how to determine the order in place?

Well I have three blocks that I want for the user to be able to sort as he pleased :
<div id="sortable" class="row ui-sortable">
<div class="boxEncar">
<div class="col-md-4 ui-sortable">
<div id="8_5_middle1" class="block block-8">
<div id="editor-container">
<h2 id="title8">Block 8</h2>
<p>Well, the way they make shows is, they make one show. That show's called a pilot. Then they show that show to the people who make shows, and on the strength of that one show they decide if they're going to make more shows. Some pilots get picked and become television programs. Some don't, become nothing. She starred in one of the ones that became nothing.</p>
</div>
</div>
</div>
<div class="col-md-4 ui-sortable">
<div id="7_6_middle2" class="block block-7">
<div id="editor-container">
<h2 id="title7">Block 7</h2>
<p>Do you see any Teletubbies in here? Do you see a slender plastic tag clipped to my shirt with my name printed on it? Do you see a little Asian child with a blank expression on his face sitting outside on a mechanical helicopter that shakes when you put quarters in it? No? Well, that's what you see at a toy store. And you must think you're in a toy store, because you're here shopping for an infant named Jeb.</p>
</div>
</div>
</div>
<div class="col-md-4 ui-sortable">
<div id="9_7_middle3" class="block block-9">
<div id="editor-container">
<h2 id="title9">Block 9</h2>
<p>Your bones don't break, mine do. That's clear. Your cells react to bacteria and viruses differently than mine. You don't get sick, I do. That's also clear. But for some reason, you and I react the exact same way to water. We swallow it too fast, we choke. We get some in our lungs, we drown. However unreal it may seem, we are connected, you and I. We're on the same curve, just on opposite ends.</p>
</div>
</div>
</div>
</div>
</div>
The id 8_5_middle1 for example, show's weight _ block-id _ zone that are stocked on the database like this :
ZONE | bid | weight
---------------------------
middle1 | 8 | 5
---------------------------
middle2 | 7 | 6
---------------------------
middle3 | 9 | 7
So the issue here is this:
jQuery(document).ready(function() {
jQuery('.col-md-4').sortable({
connectWith: ".col-md-4",
items: ".block",
update: function (event, ui) {
var myTable = jQuery(this).sortable('toArray').toString();
alert(myTable);
}
});
});
When I drag a block to another "let's say that I drag the block8 from middle1 to middle2 " here's my alert : 8_5_middle1,7_6_middle2 meaning that it just alert the old position! Is there a way to alert the new zone which the block is positionned ? Much appreciated
Is this what you want?
jQuery('.col-md-4').sortable({
connectWith: ".col-md-4",
items: ".block",
update: function (event, ui) {
var myTable = jQuery(this).sortable('toArray').toString();
//alert(myTable);
alert($(ui.item).index());
}
});
$(ui.item).index(); will return the current item index, the element ids are not changing so how would you get an updated zone?
Edit:
If you want to get the dragged item id or other attributes, you may use $(ui.item).attr('id')
fiddle link
Since you are passing the ui object, there are several things you have available there. It will be very helpful to understand if you console.log(ui) and examine the object contents.

Categories

Resources