- Screen name: Sunny Jain
Sunny Jain's Profile
20 Posts
10 Responses
1
Followers
Show:
- Expanded view
- List view
Private Message
I'm fetching some data through JSON in a container(it is a table), which has previous & next buttons.
In each page, I'm displaying 20 records from the JSON. Now, I need to disable the 'next' button, based on the value of the property 'totalRecords' in the JSON.
Calculation:
So, let say, the value of totalRecords = 238. Which means I should have (238 /20 = 11 pages with 20 records and the last page with 18 records = 12 pages overall). So, how do I ensure that 'next' button is disabled on 12th page in this case? I mean how do I ensure that each time the next button is disabled on the last page based on the similar calculation above?
I tried this :
- if(data.totalRecords%20 > 1) {
- $('#next-btn').addClass('disabled');
- } else {
- $('#next-btn').removeClass('disabled');
- }
- 02-May-2017 01:43 PM
- Forum: Getting Started
I'm working on application which will create dynamic content based on the type of object.The object type can be 'company' or 'employee'.The objects with the type 'employee' are created using bootstrap modal.I'm facing with a small problem when I'm doing that.The dyamic content is getting duplicated when I'm generating that. Also, when I add consecutive objects using modal, the content gets refreshed or lost.How do I fix it?Here's the JSfiddle.- 28-Apr-2017 03:18 AM
- Forum: Getting Started
I'm trying to update an object if it's type="external" with the 'edit' button. On clicking edit, I get a pop-up/modal, wherein I can update the details.I need to fix 2 issues:* I can't see the old values in the update modal while trying to update the data in my actual application.* Also, on clicking update, it is refreshing the entire page content.I guess that's happening due to replaceWith() method.Note: I'd tried using splice earlier, but it causes duplication of updated objects. -- myData.splice(index, 1, upObj)
- 26-Apr-2017 07:38 AM
- Forum: Getting Started
I'm trying to update an object with type="external" by clicking on the edit button.It brings up a pop-up, wherein I can enter the new information and it should then update the user accordingly.But somehow it doesn't seem to work. It just triggers a page refresh and nothing happens at all. Could you please help me fix this?- 22-Apr-2017 01:16 PM
- Forum: Getting Started
I've an array of objects (myData) which has objects with type "internal" and "external".I'm creating divs with class="box" out of the objects in array and displaying some information of the corresponding object.I've an edit button in the div.box, only if my object type ="external".So, on click of the edit, I want to update the information(company or url) of that object in 'myData' array. Also, in the displayed div I'd then like to display the updated information (calling createDisplay() method again).How do I achieve this?- 22-Apr-2017 12:09 PM
- Forum: Getting Started
I've a dynamic div which contains some information and an edit button.But, some of these dynamic divs should be editable.I'm generating all of these dynamic divs from my array of objects, which also holds the data for objects which have type="external".Each dynamic div will have a class called 'box' and each dynamic edit button has a class called 'edit-btn'.So, I've a condition like, if in dynamic div the obj.type="external" then it the edit button should be available else it should be hidden.How do I achieve this?- 21-Apr-2017 06:10 AM
- Forum: Using jQuery
I need to display the name and split path of the path entered by a user dynamically.For that, I had split the path entered by the user and grab only certain part of it. For e.g. if the user enters path as:/content/mypath/myfolder/about/images/abc.jpgThen I am displaying images/abc.jpg.However, let's assume that some of the users do not have a picture, at least the name should be applied & displayed in that case.Please check the function refreshDisplay() for details.But it throws an error- Uncaught TypeError: Cannot read property 'match' of undefined- 17-Apr-2017 08:40 AM
- Forum: Getting Started
I've 2 pop-ups to display the user list & admin list which would display 10 results per page, which is working fine.I'm getting the page nos. from the java servlet in the JSON.Note: There are 2 parameters passed in the url - resType and pageNo.pageIndex returns 0, 10, 20 ...(multiples of 10).result: checks what sort of result I want. You can ignore this part.So my url in the createTable function looks something like this instead -''/abc/myData.json?result="+resType+"&pageIndex="+pageNoIn my case(for the url I'm using), the previous & next buttons are getting hidden completely. But over here, it seems to be working fine.What should I update in my code to make it work perfectly fine for my url as well?How do I save the JSON which I'm receiving through ajax to an existing array? I first need to delete everything in my array savedData and save the JSON into that.
Here's the code :-
- function getArticleOnPageLoad() {
- $.getJSON("http://www.myurl.com/myJSON.json", function(data) {
- savedData = data;
- createData();
- }).fail(function(error) {
- console.log("AJAX ERROR: " + error);
- });
- }
- 14-Apr-2017 02:43 AM
- Forum: Getting Started
I've a function 'refreshDisplay' which will help me create dynamic elements. Now, I've a small condition there. In the 'src' attribute of the image, I'm going to check if the obj.picture.thumbnail starts with '/content' then append '.jpg' to the end of the obj.picture.thumbnail's value , else just use obj.picture.thumbnails' value!
Please check the image with class '.myLink' in the code. How do I achieve this?
Here's the code.
function refreshDisplay() { $('.container').html(''); savedData.forEach(function (obj) { // Reset container, and append collected data (use jQuery for appending) $('.container').append( $('<div>').addClass('parent').append( $('<label>').addClass('dataLabel').text('Name: '), obj.name.first + ' ' + obj.name.last, $('<br>'), // line-break between name & pic $('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'), $('<label>').addClass('dataLabel').text('Date of birth: '), obj.dob, $('<br>'), $('<label>').addClass('dataLabel').text('Address: '), $('<br>'), obj.location.street, $('<br>'), obj.location.city + ' ' + obj.location.postcode, $('<br>'), obj.location.state, $('<br>'), $('<button>').addClass('removeMe').text('Delete'), $('<button>').addClass('top-btn').text('Swap with top'), $('<button>').addClass('down-btn').text('Swap with down') ) ); }) // Clear checkboxes: $('.selectRow').prop('checked', false); handleEvents(); }
- I've a pop-up to display the user list which would display 10 results per page, which is working fine.I'm getting the page nos. from the java servlet in the JSON.How do I disable the previous button, when it is the first page?Likewise, how do I disable the last button, when it is the last page?Here's my code.
- function UserList(pageNo) {
- var resType="userList";
- getResults(resType,pageNo);
- $(document).on('click', '.next-btn', function(){
- var next = 10+pageNo;
- UserList(next);
- });
- $(document).on('click', '.prev-btn', function(){
- var previ = pageNo - 10;
- UserList(previ);
- });
- }
- 11-Apr-2017 07:15 AM
- Forum: Getting Started
I've a table which gets updated based on JSON data.Each row in the table has a checkbox which holds the value of the corresponding JSON object, which is basically the information about any of the users.On selecting any of the rows, and saving to display the selected user profile, I'm also storing the selected JSON object in an array 'savedData'.I also have an option of adding the user externally through a form which pops up on clicking 'Open External form' button. Now, I'm trying to create an object and store it in the same 'savedData' array on submitting that form. At the same time, the 'div.parent' should get generated & get appended to 'div.container' in the same format as it is for the the other users selected from the table.Unfortunately, the 'div.parent' is not getting created, and the external object is not getting added.Could you please help me fix this?- 09-Apr-2017 04:34 AM
- Forum: Getting Started
I've a bootstrap form which has a few fields. By default, the 1st and the 2nd fields are mandatory.
Now, if the 3rd field is filled out, the 4th one becomes mandatory.
Similarily, if the 4th field is filled out, the 3rd one becomes mandatory.
However, if both 3rd & 4th fields are not filled out, they're not mandatory.
I'm also using the HTML5 form validation here.
So, here if you see, the fields Name & Date of Registration are mandatory by default.
However, I'm trying to make Website mandatory when Company is filled out! And similarly, make Company mandatory, when Website is filled out!
If neither company not website are filled out, both of these fields are not mandatory!
Here's my code :- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- <script>
- $(document).ready(function(){
- if(($('#comp').val()!== "") || ($('#weburl').val()!=="")) {
- $('#comp').prop('required',true);
- $('#weburl').prop('required',true);
- }
- else {
- $('#comp').prop('required',false);
- $('#weburl').prop('required',false);
- }
- $("#myForm").submit(function(){
- alert("OK");
- return false;
- })
- });
- </script>
- </head>
- <body>
- <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myFormModal">Add Details</button>
- <div id="myFormModal" class="modal fade" role="dialog">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <button type="button" class="close" data-dismiss="modal">×</button>
- <h4 class="modal-title">Add details</h4>
- </div>
- <div class="modal-body">
- <form class="form-horizontal" id="myForm" name="contact" action="#">
- <div class="form-group">
- <label class="control-label col-sm-3" for="dor">Date of Registeration:</label>
- <div class="col-sm-8">
- <input type="date" class="form-control" id="dor" name="dor" required>
- </div>
- </div>
- <div class="form-group">
- <label class="control-label col-sm-3" for="name">Name:</label>
- <div class="col-sm-8">
- <input type="text" class="form-control" id="name" name="name" required>
- </div>
- </div>
- <div class="form-group">
- <label class="control-label col-sm-3" for="comp">Company:</label>
- <div class="col-sm-8">
- <input type="text" class="form-control" id="comp" name="comp">
- </div>
- </div>
- <div class="form-group">
- <label class="control-label col-sm-3" for="weburl">Website:</label>
- <div class="col-sm-8">
- <input type="url" class="form-control" id="weburl" name="weburl">
- </div>
- </div>
- <hr />
- <div class="form-group">
- <div class="col-sm-offset-3 col-sm-3">
- <button class="btn btn-primary btn-sm">Save</button>
- </div>
- <div class="col-sm-3">
- <button type="reset" class="btn btn-primary btn-sm">Reset</button>
- </div>
- <div class="col-sm-3">
- <button type="button" class="btn btn-primary btn-sm close-external-modal" data-dismiss="modal">Close</button>
- </div>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
- 07-Apr-2017 05:22 AM
- Forum: Getting Started
I need help for creating the JSON of the dynamicallly created dom objects which has exactly the same format, which was while receiving the JSON to create the dynamic element.To simplify thing, I've create a dummy application, which is available in the JSFiddle link provided below.Now, if you see, in the table I'm getting the data through JSON.The checkbox values in the table are JSON objects.When I select any of the checkboxes and click on Save, the corresponding div is generated and displayed.Now, I want to save this dynamically created DOM structure using the "Save displayed data and create json'" button and also create the JSON which will be of the same format (containg all the properties (irrespective of the fact, whether they were displayed or not in the corresponding parent. for e.g., the phone number, images all the data should be available in the JSON, even it is not displayed but is available in the original JSON).How could we achieve this?JS Fiddle: https://jsfiddle.net/Sunny1719/vo5ygomf/- <!doctype html>
- <html>
- <head>
- <style>
- table, th, td {
- border: 1px solid #ddd;
- border-collapse: collapse;
- padding: 10px;
- }
- table {
- margin: auto;
- }
- .parent {
- height: 25%;
- width: 90%;
- padding: 1%;
- margin-left: 1%;
- margin-top: 1%;
- border: 1px solid black;
- }
- .parent:nth-child(odd){
- background: skyblue;
- }
- .parent:nth-child(even){
- background: green;
- }
- </style>
- <body>
- <button onclick="createTable()">Load Table</button>
- <button onclick="saveData()">Save Table data</button>
- <table id="datatable" align="center">
- <tr><th>Select</th><th>Name</th><th>DOB</th></tr>
- </table>
- <br />
- <button onclick="createJson()">Save displayed data & create JSON</button>
- <br />
- <div class="container">
- <
- </div>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
- <script>
- function createTable() {
- $.getJSON("https://api.randomuser.me/?results=5", function(data) {
- // First, clear the table
- $('#datatable tr:has(td)').remove();
- data.results.forEach(function (record) {
- var json = JSON.stringify(record);
- $('#datatable').append(
- $('<tr>').append(
- $('<td>').append(
- $('<input>').attr('type', 'checkbox')
- .addClass('selectRow')
- .val(json)
- ),
- $('<td>').append(
- $('<a>').attr('href', record.picture.thumbnail)
- .addClass('imgurl')
- .attr('target', '_blank')
- .text(record.name.first)
- ),
- $('<td>').append(record.dob)
- )
- );
- })
- }).fail(function(error) {
- console.log("**********AJAX ERROR: " + error);
- });
- }
- function saveData(){
- // Scrape the URLs that were already collected into a Set:
- var used = new Set($('.myLink').map(function () {
- return $(this).attr('href');
- }).get());
- var errors = [];
- $('input.selectRow:checked').each(function(count) {
- // Get the JSON that is stored as value for the checkbox
- var obj = JSON.parse($(this).val());
- // See if this URL was already collected (that's easy with Set)
- if (used.has(obj.weburl)) {
- errors.push(obj.title);
- } else {
- // Append it to the collection (use jQuery for appending)
- $('.container').append(
- $('<div>').addClass('parent').append(
- $('<label>').addClass('dataLabel').text('Name: '),
- obj.name.first + ' ' + obj.name.last,
- $('<br>'), // line-break between name & pic
- $('<img>').attr('src', obj.picture.thumbnail), $('<br>'),
- $('<label>').addClass('dataLabel').text('Date of birth: '),
- obj.dob, $('<br>'),
- $('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
- obj.location.street, $('<br>'),
- obj.location.city + ' ' + obj.location.postcode, $('<br>'),
- obj.location.state, $('<br>')
- )
- );
- }
- // Clear checkbox:
- $('input', this).prop('checked', false)
- });
- if (errors.length)
- alert('The following were already selected:\n' + errors.join('\n'))
- }
- </script>
- </body>
- </head>
- </html>
- 05-Apr-2017 01:24 PM
- Forum: Getting Started
I've a few dynamic elements being generated on click of a button.On click of this button, I get dynamic divs generated which also contain link.I get only the first href attribute value("link0.com") in the array "linkArr".How do I get all of the href attributes stored inside this array?Here's my code.- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
- <style>
- .parent {
- height: 25%;
- width: 90%;
- padding: 1%;
- margin-left: 1%;
- margin-top: 1%;
- border: 1px solid black;
- }
- .parent:nth-child(odd){
- background: skyblue;
- }
- .parent:nth-child(even){
- background: green;
- }
- </style>
- </head>
- <body>
- <button class="btn btn-primary" onclick="getData()">Get data</button>
- <div class="box">
- </div>
- <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- <script>
- var content = "";
- linkArr = new Array();
- function getData(){
- var count = 0;
- for(count=0; count<5; count++) {
- content+= '<div class="container-fluid parent"><div class="row"><div class="col-md-6">Number: '+count+'</div><div class="col-md-6"><a href="link'+count+'.com" class="mylink">Link'+count+'</a></div></div></div>';
- }
- $('.box').html(content);
- $('.box').each(function(){
- linkArr.push($(this).find('.mylink').attr('href'));
- console.log(linkArr);
- });
- }
- </script>
- </body>
- </html>
- 05-Apr-2017 06:47 AM
- Forum: Getting Started
I'm working on an application wherein the data will be displayed here based on some selection.Please note that, the data in the table actually comes in through some JSON.However, here I've hard coded all the data here in the table. Unfortunately, I don't have the JSON to share.- <!doctype html>
- <html>
- <head>
- <style>
- table, th, td {
- border: 1px solid #ddd;
- border-collapse: collapse;
- padding: 10px;
- }
- .parent {
- height: 25%;
- width: 90%;
- padding: 1%;
- margin-left: 1%;
- margin-top: 1%;
- border: 1px solid black;
- }
- .parent:nth-child(odd){
- background: skyblue;
- }
- .parent:nth-child(even){
- background: green;
- }
- </style>
- </head>
- <body>
- <table>
- <tr>
- <th>Select</th>
- <th>Name</th>
- <th>Website</th>
- </tr>
- <tr>
- <td><input type="checkbox" name="selectRow"></td>
- <td class="name">A</td>
- <td class="weburl"><a href="abc.com">ABC</a></td>
- </tr>
- <tr>
- <td><input type="checkbox" name="selectRow"></td>
- <td class="name">D</td>
- <td class="weburl"><a href="def.com">DEF</a></td>
- </tr>
- <tr>
- <td><input type="checkbox" name="selectRow"></td>
- <td class="name">G</td>
- <td class="weburl"><a href="ghi.com">GHI</a></td>
- </tr>
- <tr>
- <td><input type="checkbox" name="selectRow"></td>
- <td class="name">J</td>
- <td class="weburl"><a href="jkl.com">JKL</a></td>
- </tr>
- </table>
- <button onclick="saveData()">Save</button>
- <br />
- <div class="container">
- </div>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
- <script>
- var content = "";
- function saveData(){
- $('input[name="selectRow"]:checked').map(function(count) {
- var myJSON = JSON.parse(decodeURIComponent(this.value));
- var tableDataUrl = myJSON.weburl;
- content += '<div class="parent"><label class="dataLabel">Name:</label>'+myJSON.name+'<label class="dataLabel">Website:</label><a href="'+myJSON.weburl+'" class="dispWebUrl"></div>';
- var dispUrl = $('.container').find('.dispWebUrl').attr('href');
- if(tableDataUrl === dispUrl)
- $('.container').html(articlesResult);
- } else {
- alert("Data already exists!");
- }
- }
- </script>
- </body>
- </html>
So, now I select a row using the checkbox from the table, and click on the 'Save' button which would then append the data to a static div with class="container".However, if a particular div with the same weburl (as shown in the code) already exists inside the display "div.container", it shouldn't add that.1. Select A & D from the table shown in the screenshot and click on 'Save'.2. A & D get appended to "div.container".3. Now, select A,D,G,J from the table.Current situation: Nothing is added, and alert is shown as "Data already exists!"Ideal behaviour: G & J should get appended to "div.box" and alert should be shown as "A already exists!".How do I achieve this?Note: URL(weburl) is going to be unique here. Hence, taking that for comparison.- I'm relatively new to jquery and javascript.The form opens up on clicking the button "Open Modal" in the modal.Next, when I click on 'Save' in the modal, it should validate the HTML5 form and on successful validation should call another function "addDetails()".How do I achieve this using existing jquery form validation plugin or any other method? What CDNs I need to refer to while using?
- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- </head>
- <body>
- <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myFormModal">Add Details</button>
- <div id="myFormModal" class="modal fade" role="dialog">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <button type="button" class="close" data-dismiss="modal">×</button>
- <h4 class="modal-title">Add details</h4>
- </div>
- <div class="modal-body">
- <form class="form-horizontal" id="myForm" name="contact" action="#">
- <div class="form-group">
- <label class="control-label col-sm-3" for="dor">Date of Registeration:</label>
- <div class="col-sm-8">
- <input type="date" class="form-control" id="dor" name="dor" required>
- </div>
- </div>
- <div class="form-group">
- <label class="control-label col-sm-3" for="name">Name:</label>
- <div class="col-sm-8">
- <input type="text" class="form-control" id="name" name="name" required>
- </div>
- </div>
- <div class="form-group">
- <label class="control-label col-sm-3" for="weburl">Website:</label>
- <div class="col-sm-8">
- <input type="url" class="form-control" id="weburl" name="weburl" required>
- </div>
- </div>
- <div class="form-group">
- <label class="control-label col-sm-3" for="myphoto">Image:</label>
- <div class="col-sm-8">
- <input type="text" class="form-control" id="myphoto" name="myphoto" required>
- </div>
- </div>
- <hr />
- <div class="form-group">
- <div class="col-sm-offset-3 col-sm-3">
- <button type="button" class="btn btn-primary btn-sm" onclick="addDetails()">Save</button>
- </div>
- <div class="col-sm-3">
- <button type="reset" class="btn btn-primary btn-sm">Reset</button>
- </div>
- <div class="col-sm-3">
- <button type="button" class="btn btn-primary btn-sm close-external-modal" data-dismiss="modal">Close</button>
- </div>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
- 03-Apr-2017 01:25 PM
- Forum: Getting Started
I'm working on some application wherin the data will be displayed based on some selection. The data will be selected from the table as shown in the screenshot.
It gets populated in the table through some JSON.
Now, lets say, for example,- Select A & C from the table shown in the screenshot and click on 'Save'.
- A & C get appended to "div.box" with ids "parent-0" and "parent-1" respectively.
- Now, select A & B from the table.
Current situation: Nothing is added, and alert is shown as "Data already exists!"
Ideal behaviour: B should get appended to "div.box" with id "parent-2" and alert should be shown as "A already exists!".function showData(){ var count = 0; $('input[name="selectData"]:checked').map(function() { var JSONData = JSON.parse(decodeURIComponent(this.value)); content += '<div class="container parent" id="parent-'+count'"><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Count:</label><div class="col-md-8 article-data">'+JSONData.name+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove-btn">Delete <span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>'; count++; }); if($('#parent-'+count).length==0) { $('.box').html(content); resetEvents(); }else{ alert("Data already exists!"); } }
How do I achieve this?
- I've created a small application to swap divs.
The user can create a div manually by entering a value in the input field or by clicking on the add button.
In both the cases, the following conditions are supposed to be met.
1. All the divs should append to the parent div with class container. - working
2. If a child div with class box is already present under class container, the new div with class box should add after the already available div i.e should act as a sibling to the already available div with class box. - working
3. It should be possible to swap the divs with class box by clicking on top & down. - working
4. The top button for the 1st div with class box should be disabled, since it will not have a top sibling to swap with. - working
5. The down button for the last div with class box should be disabled, since it will not have a down sibling to swap with. - working
6. The content added using the form by entering a value in the input field should also get added to the parent div as mentioned in 1. - not working
7. Delete each of the divs when delete button is clicked on. - not working- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <style>
- .box {
- height: 25%;
- width: 90%;
- padding: 1%;
- margin-left: 1%;
- margin-top: 1%;
- border: 1px solid black;
- }
- .box:nth-child(odd){
- background: skyblue;
- }
- .box:nth-child(even){
- background: green;
- }
- .disabled-btn {
- cursor: not-allowed;
- opacity: 0.25%;
- }
- </style>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
- </head>
- <body>
- <button class="add" onclick="addDiv()">Add</button>
- <form>
- <input type="text" id="myCount">
- <button type="submit" onclick="addDiv2()">Submit</button>
- </form>
- <div class="container">
- </div>
- <script>
- content = "";
- var count=0;
- function addDiv(){
- while(count<5){
- content+= '<div class="box"><p>'+count+'</p><button class="top">Top</button><button class="down">Down</button><button class="removeMe">Delete</button></div>';
- count++;
- }
- $('.container').html(content);
- resetEvents();
- }
- function addDiv2(){
- var count = $("#myCount").val();
- content+= '<div class="box"><p>'+count+'</p><button class="top">Top</button><button class="down">Down</button><button class="removeMe">Delete</button></div>';
- $('.container').html(content);
- resetEvents();
- }
- $(".removeMe").click(function(){
- $(this).parents('.box').remove();
- });
- function handleEvents() {
- $(".top, .down").prop("disabled", false);
- $(".box:first").find(".top").prop("disabled", true);
- $(".box:last").find(".down").prop("disabled", true);
- }
- function resetEvents() {
- $(".top, .down").unbind('click');
- handleEvents();
- $('.down').click(function() {
- var toMove1 = $(this).parents('.box');
- $(toMove1).insertAfter($(toMove1).next());
- handleEvents();
- });
- $('.top').click(function() {
- var toMove1 = $(this).parents('.box');
- $(toMove1).insertBefore($(toMove1).prev());
- handleEvents();
- });
- }
- </script>
- </body>
- </html>
All the conditions mentioned above are met except the 6th & 7th one.
The delete button is not working.
The div disappears as soon as it gets added.
Also, is there anything that needs to be optimized in the code? Do I need to use event delegation to disable the dynamically generated top & down buttons for the first and last divs? If yes, how do I do that?- 11-Feb-2017 12:55 PM
- Forum: Using jQuery
I'm trying to hide/show a user's pop-up which opens up on clicking it's corresponding user.
This works when the users are not sorted alphabetically but do not work after sorting.
HTML:
[CODE]
<body>
<section>
<header></header>
<main></main>
</section>
</body>
</html>
[/CODE]
CSS
[CODE]
body {
padding: 0;
margin: 0;
}
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
main .wrapper {
padding-left:3px;
display: flex;
flex-wrap:wrap;
flex-direction:row;
}
.user-container {
position: relative;
padding: 5px 8px;
border: 1px solid lightgray;
float: left;
width: 33.33%;
margin-left: -1px;
margin-top: -1px;
}
.user-img {
border-radius: 50%;
margin-left: 2px;
vertical-align: middle;
margin-right: 7px;
}
.user-name{
display:inline-block;
vertical-align: middle;
}
.user-lastname, .modal-lastname {
text-transform: uppercase;
color: gray;
font-family: "Times New Roman", Courier, sans-serif;
}
.user-firstname, .modal-firstname {
text-transform: capitalize;
color: gray;
font-family: "Times New Roman", Courier, sans-serif;
}
.modal-name {
text-align: center;
padding: 10px;
display: block;
}
.sort-label {
color: gray;
font-size: 1.2em;
position: absolute;
right: 50px;
top: 30px;
}
.sortasc, .sortdes {
text-decoration: none;
height: 30px;
margin-left: 10px;
color: gray;
}
.user-modal {
position: relative;
left: 30px;
height: 20%;
width: 30%;
border: 2px solid lightgray;
border-radius: 7px;
margin-top: 0;
background: linear-gradient(180deg, white, 90%, lightgray);
box-shadow: 2px -5px 5px lightgray;
z-index: 1;
}
.modal-img {
border: 2px solid lightgray;
border-radius: 50%;
display: block;
margin: auto;
margin-top: 10px;
}
.model-label {
display: inline-block;
color: gray;
margin-left: 20%;
font-family: Calibri, "Times New Roman", sans-serif;
font-weight: bold;
text-shadow: 1px 1px lightgray;
min-width: 50px;
}
.user-info {
line-height: 1.5em;
text-align: left;
}
.user-badge {
position: absolute;
left: -80px;
top: 100px;
height: 60px;
width: 190px;
border: 1px solid lightgray;
border-radius: 3px;
background: linear-gradient(180deg, coral, 50%, orangered);
box-shadow: 2px 2px 3px lightgray;
padding: 7px 12px;
transform: rotate(90deg);
text-align: right;
}
.user-badge p {
margin: 0;
}
.badge-name {
font-weight: bold;
text-shadow: 1px 1px lightgray;
}
.badge-name-value {
color: #F2F2F2;
text-shadow: 1px 1px lightgray;
}
.close-btn {
position: absolute;
right: 25px;
top: 15px;
color: gray;
text-decoration: none;
font-weight: bold;
font-size: 1.4em;
}
.active {
background-color: #F0F0F0;
}
[/CODE]
jQuery
[CODE]
$(document).ready(function(){
$.getJSON("https://api.randomuser.me/?results=25", function(data){
var heading = $("header").append("<h1>Contact List</h1>").css({"text-align":"center", "color":"gray", "text-shadow":"1px 1px lightgray"});
var sortlabel = $("<label class='sort-label'>sort</label>").appendTo(heading).addClass("sort-label");
var sortasc = $("<a href='#' class='sortasc' id='btn-asc'>↑</a>").appendTo(sortlabel);
var sortdes = $("<a href='#' class='sortdes' id='btn-des'>↓</a>").appendTo(sortlabel);
var dataLength = data.results.length;
var wrapper = $("<div class='wrapper'></div>").appendTo("main");
for(var i=0; i<dataLength; i++)
{
/*User data/div container */
var modalId = "mod-"+i;
user = $("<div class='user-container' data-mod-id='"+modalId+"'/>").appendTo(wrapper);
img = $("<img class='user-img' src='" + data.results[i].picture.thumbnail + "'/>").appendTo(user);
userName = $("<span />").appendTo(user).addClass('user-name');
lastName = $("<strong>" + data.results[i].name.last + ", " + "</strong>").appendTo(userName).addClass('user-lastname');
firstName = $("<strong>" + data.results[i].name.first + "</strong>").appendTo(userName).addClass('user-firstname');
/*User Modal or Pop-up starts here*/
userModal = $("<div id='"+modalId+"' class='user-modal' />").appendTo(wrapper);
closeBtn = $("<a href='#' class='close-btn'>×</a>").appendTo(userModal);
modalImg = $("<img class='modal-img' src='" + data.results[i].picture.large + "'/>").appendTo(userModal).addClass('modal-img');
userBadge = $("<div class='user-badge' />").appendTo(userModal);
badgeName = $("<p class='badge-name'>username</p><p class='badge-name-value'>" + data.results[i].login.username + "</p>").appendTo(userBadge);
modalName = $("<div/>").appendTo(userModal).addClass('modal-name');
modalLastName = $("<strong>" + data.results[i].name.last + ", " + "</strong>").appendTo(modalName).addClass('modal-lastname');
modalFirstName = $("<strong>" + data.results[i].name.first + "</strong>").appendTo(modalName).addClass('modal-firstname');
modalInfo = $("<div />").appendTo(userModal).addClass('modal-info');
email = $("<label class='model-label'><em>email</em></label> <span class='user-info'> " + data.results[i].email + "</span><br />").appendTo(modalInfo);
phone = $("<label class='model-label'><em>phone</em></label> <span class='user-info'> " + data.results[i].phone + "</span><br />").appendTo(modalInfo);
street = $("<label class='model-label'><em>street</em></label> <span class='user-info'> " + data.results[i].location.street + "</span><br />").appendTo(modalInfo);
city = $("<label class='model-label'><em>city</em></label> <span class='user-info'> " + data.results[i].location.city + "</span><br />").appendTo(modalInfo);
state = $("<label class='model-label'><em>state</em></label> <span class='user-info'> " + data.results[i].location.state + "</span><br />").appendTo(modalInfo);
zip = $("<label class='model-label'><em>zip</em></label> <span class='user-info'> " + data.results[i].location.postcode + "</span><br />").appendTo(modalInfo);
/*User Modal or Pop-up ends here*/
}
/* Sort function */
allUsers = $(".user-container");
$("#btn-des").on('click',function(){
var desc = allUsers.sort(function(a,b){
return $(a).find(".user-name").text() > $(b).find(".user-name").text();
});
$(".wrapper").html(desc);
});
$("#btn-asc").on('click',function(){
var asc = allUsers.sort(function(a,b){
return $(a).find(".user-name").text() < $(b).find(".user-name").text();
});
$(".wrapper").html(asc);
});
/* User pop-up Hide/Show */
$('.user-modal').hide(); //for hiding all modals on load
$('.close-btn').click(function(){
$(this).parent().hide();
});
$('.user-container').click(function(){
$('.user-modal').hide();
$("#"+$(this).attr("data-mod-id")).show();
});
/* User pop-up Hide/Show */
});
});
[/CODE]- «Prev
- Next »
Moderate user : Sunny Jain
© 2013 jQuery Foundation
Sponsored by
and others.