Auto increment with javascript to open Multiple instances of jQuery Modal Window dynamically

I am using a jQuery UI Modal Box.

I have a sidebar which has different controls like button, selectbox etc. I am dragging a control from my side bar which adds a BUTTON on my CMS page. When user click on that button then a jQuery Modal window open which is fine. But issue arises when user repeat this process and drag the code snippet again. In that case the Modal window cannot open second time due to the ID MisMatch.

I found a solution on same website at this link:
https://www.experts-exchange.com/questions/28631603/Auto-increment-in-jQuery-script.html

Open in new window


See the accepted solution. It works fine for me also but I need one change to make it dynamic according to my application:
That example uses two button controls
  <button id='create-explanation1' class='btndialog' data-target="dialog-message1">Explanation</button>
  <button id='create-explanation2' class='btndialog' data-target="dialog-message2">Explanation</button>

Open in new window


Whereas I want to use above button code one time and add an auto-increment variable with data-target value, so that I will get
dialog-message1, dialog-message2, dialog-message3 etc whenever user drag a code snippet from sidebar.

Means: If user drag a BUTTON first time then I need data-target="dialog-message1", if user drag a button second time then I need data-target="dialog-message-2" etc

Need urgent help

Thanks
Shano KhanSoftware EngineerAsked:
Who is Participating?
 
Julian HansenCommented:
I have put together code that should do what you want. I don't have the time to explain everything I have done but here is a short synopsis.

I took the JavaScript out of the snippets and put it in final.html - it does not belong in snippets because that is run each time you drag and drop an item - which results in multiple binding of events.

I took the dialog message out of snippets as well - you were creating a dialog per button - all with the same ID - rather use one dialog

I added the table that is to receive the result to the dialog when the dialog is opened - that way when you click save it uses the attached table object to update the returned HTML from the save.

The rest you should be able to see with a simple compare of the files below and your originals

You can see it working here
final.html
snippets.html
0
 
Julian HansenCommented:
Where is your drag / drop code?

In your drop event you simply need to set the data element of the dialog. How to do this

1. Get the number of dialogs on the page
var total = $('.btndialog').length;

Open in new window

2. Add 1 for the next one
total++;

Open in new window

3. Set the data attribute for the target element
$(e).data('target','dialog-message-' + total);

Open in new window

The above assumes the following

1. Only buttons that have been dropped have the class .btndialog - if this is not the case then you need to amend the selector to target only the dropped buttons (using a parent element or adding a class to the dropped button when it is dropped)
2. In your drop event handler e is the element passed to the function for the target element - if this is not the case then amend and change $(e) to refer to the dropped button.

If that is not working for you post your drag / drop code.
0
 
Shano KhanSoftware EngineerAuthor Commented:
Not Works for me. Let me send complete code.


<!DOCTYPE html>
<html>
<head>
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<!--//the 1st message works with jQuery dialog-->

<div id='dialog-message' class='dialogmsg' title='Explanation'>Some information for the 1st message</div>
<button id='create-explanation1' class='btndialog' data-target='dialog-message'>Explanation1</button>

<!--//as you can see the 2nd, 3rd, 4th messages will not work as I have the script above. -->
<div id='dialog-message2' class='dialogmsg' title='Explanation'>Some information for the 2nd message</div>
  <button id='create-explanation1' class='btndialog' data-target="dialog-message2">Explanation 2</button>

  <div id='dialog-message2' class='dialogmsg' title='Explanation'>Some information for the 3rd message</div>
    <button id='create-explanation1' class='btndialog' data-target="dialog-message3">Explanation 3</button>

    <div id='dialog-message2' class='dialogmsg' title='Explanation'>Some information for the 4th message</div>
      <button id='create-explanation1' class='btndialog' data-target="dialog-message4">Explanation 4</button>

      <div id='dialog-message2' class='dialogmsg' title='Explanation'>Some information for the 5th message</div>
        <button id='create-explanation1' class='btndialog' data-target="dialog-message5">Explanation 5</button>

        <div id='dialog-message2' class='dialogmsg' title='Explanation'>Some information for the 6th message</div>
          <button id='create-explanation1' class='btndialog' data-target="dialog-message6">Explanation 6</button>
</body>
</html>

<script>

jQuery(function() {
  jQuery( '.dialogmsg' ).dialog({
    autoOpen: false,
    height: 300,
    width: 350,
    modal: true,
    buttons: {
      Cancel: function() {
        jQuery(this).dialog( 'close' );
      }
    },
    close: function() {
    }
  });


  jQuery( 'button.btndialog' ).button().on( 'click', function() {
    var target = jQuery(this).data('target');
    var counter_inc = 10;
    jQuery('.dialogmsg').data(target,counter_inc);
    alert(target);
    jQuery("#"+target).dialog( 'open' );
  });
});
</script>

Open in new window


PROBLEM: See line 14. Which has attribute data-target='dialog-message' and this repeats in every button with a different data-target attribute. I want to add 1,2,3,4,5 with data-target with jquery to make it dynamic according to my application.

thanks
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
Julian HansenCommented:
PROBLEM: See line 14. Which has attribute data-target='dialog-message' and this repeats in every button with a different data-target attribute. I want to add 1,2,3,4,5 with data-target with jquery to make it dynamic according to my application.

Explain the dynamic bit again - how are those buttons dynamic? The code you have shown me does not match with your original problem statement. You mentioned dragging and dropping - which is not in the sample code you showed me.

I cannot show you how to do what you want if you don't show me code that matches your use case.
0
 
Shano KhanSoftware EngineerAuthor Commented:
I am using JS library due to that I have a sidebar and some snippets in it. It allows me to drag a snippet on my CMS page.
You can see a demo of JS library here:
http://innovastudio.com/builderdemo/example1.html

Open in new window


 By using above library I have added my custom snippet in sidebar so that when user drag it on cms page he will get a button control.
 When user click on that button, it will open a modal window which must have unique id. If user drop a control 5 times then 5 modal Windows must have different id's so that I will save data in db accordingly.

 Everything goes well, but when user drag the button control second time then there is a conflict of modal Window (id's).

Here is my complete code:
<div  id="mydiv2" data-num="93" data-thumb="assets/minimalist-basic/thumbnails/x14.png" data-cat="0,17,22" data-title="Embed" data-module="data-mpin">
	<div class="section vimeo-section" style="margin-bottom: 30px;">
		<figure class="module-image module-image-full module-video">
		  <div class="row">
		    <div class="col-md-8 col-md-push-2 col-md-12" id="embed-slected">
		      <div class="module-image-full-wrap">
						<p></p>
            <div href="#" class="btn btn-inline pagebg-color" data-toggle="modal" data-target="#Modal">Add Pin</div>


<!-- FORM  for MODAL WINDOW 1 - Add Pin Information -->

<div id="dialog-form" title="Create new Pin">
<div id='dialog-message' class='dialogmsg'title="Add Pin for ">
<p class="validateTips_map">All form fields are required.</p>

 <form>
<fieldset>
<label for="name">Longitude:</label>
<input type="text" name="name" id="long_map_val" value="Jane Smith" class="text ui-widget-content ui-corner-all">
<label for="email">Latitude:</label>
<input type="text" name="email" id="lat_map_val" value="jane@smith.com" class="text ui-widget-content ui-corner-all">

<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>

<button id='create-explanation1' class='btndialog' data-target='dialog-message' value="0">Add Pin</button>

<script>
jQuery( 'button.btndialog' ).button().on( 'click', function() {
var target = jQuery(this).data('target');
alert(target);

jQuery("#"+target).dialog( 'open' );
});


function addUser_maps1()
{
alert('save data');
}
dialog_map = jQuery( '.dialogmsg' ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Save Pin": addUser_maps1,
Cancel: function() {
dialog_map.dialog( "close" );
}
},
close: function() {
}
});

form_map = dialog_map.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addUser_maps();
});

</script>
</div>
</div>
</div>
</figure>
</div>
</div>

<!-- Add Pin 2 Close -->

Open in new window


when user drag a button 1st time then id will be dialog-form1, second time it will be dialog-form2, third time it will be dialog-form3
in  
<div id="dialog-form" title="Create new Pin"> line

Open in new window


The jquery code
 jQuery("#"+target).dialog( 'open' );  

Open in new window

will work if ids are incremental.

hope you understand better now.
0
 
Julian HansenCommented:
I understand exactly what you want to do - but I can't tell you how unless I know how the drag is being implemented - that is what I have been asking for.

I will look at the link you provided and see if that sheds some light.
0
 
Julian HansenCommented:
Assuming you have used the same droppable container as in the link i.e. has the ui-droppable class then you can try this
$(function() {
  $( ".ui-droppable" ).droppable({
    drop: function( event, ui ) {
      $(ui.draggable).find('button').data('target','This is a test');
    }
  });
})

Open in new window

This is an initial test to see if this works. After dragging the button check to see if data-target is set to 'This is a test' if it is we can move to phase II to set it to the correct value.
0
 
Shano KhanSoftware EngineerAuthor Commented:
Well let me clarify one more thing. I am using Drupal CMS and I am working in my Template file. Everything is included and currently I have not used droppable event.

The library which I am using (contentbuilder.js) has a snippets.html file. Whatever I have added in it, it will be available in the sidebar for a user to drag on the page. So I am writing me dialog code in that file.

I have added this below code in my snippets.html file
<div  id="mydiv2" data-num="93" data-thumb="assets/minimalist-basic/thumbnails/x14.png" data-cat="0,17,22" data-title="Embed" data-module="data-mpin">
	<div class="section vimeo-section" style="margin-bottom: 30px;">
		<figure class="module-image module-image-full module-video">
		  <div class="row">
		    <div class="col-md-8 col-md-push-2 col-md-12" id="embed-slected">
		      <div class="module-image-full-wrap">
						<p></p>
            <div href="#" class="btn btn-inline pagebg-color" data-toggle="modal" data-target="#Modal">Add Pin</div>


<!-- FORM  for MODAL WINDOW 1 - Add Pin Information -->

<div id="dialog-form" title="Create new Pin">
<div id='dialog-message' class='dialogmsg'title="Add Pin for ">
<p class="validateTips_map">All form fields are required.</p>

 <form>
<fieldset>
<label for="name">Longitude:</label>
<input type="text" name="name" id="long_map_val" value="Jane Smith" class="text ui-widget-content ui-corner-all">
<label for="email">Latitude:</label>
<input type="text" name="email" id="lat_map_val" value="jane@smith.com" class="text ui-widget-content ui-corner-all">

<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>

<button id='create-explanation1' class='btndialog' data-target='dialog-message' value="0">Add Pin</button>

<script>
jQuery( 'button.btndialog' ).button().on( 'click', function() {
var target = jQuery(this).data('target');
alert(target);

jQuery("#"+target).dialog( 'open' );
});


function addUser_maps1()
{
alert('save data');
}
dialog_map = jQuery( '.dialogmsg' ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Save Pin": addUser_maps1,
Cancel: function() {
dialog_map.dialog( "close" );
}
},
close: function() {
}
});

form_map = dialog_map.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addUser_maps();
});

</script>
</div>
</div>
</div>
</figure>
</div>
</div>

<!-- Add Pin 2 Close -->

Open in new window


When user drag this snippet from sidebar then a button appears on my CMS page. When I click on that button then a Modal window opens due to the code added in my snippets.html file (code above). But when user drag that snippet 2nd time then modal window cannot open due to that ID issue. I have written some Jquery code which will open modal window according to the button id (code below)

<button id='create-explanation1' class='btndialog' data-target='dialog-message' value="0">Add Pin</button>

Open in new window


If I add 3 buttons and then just change the data-target value like below code then code will work fine. But instead of these 3 buttons I need one button of' Add Pin' only .
<button id='create-explanation1' class='btndialog' data-target='dialog-message1' value="0">Add Pin</button>
<button id='create-explanation1' class='btndialog' data-target='dialog-message2' value="0">Add Pin</button>
<button id='create-explanation1' class='btndialog' data-target='dialog-message3' value="0">Add Pin</button>

Open in new window


If user drag the snippet 2nd time then data-target will should be 'dialog-message2'. Otherwise it will open the previous model or will not open a model .

Hope you get more understanding now.

Thanks for your efforts.
0
 
Julian HansenCommented:
As I said - I understood you already. The problem is not understanding what you want to do - it is how your page is setup so that we can do what you want to do.

The link you gave me pointed to a template that uses the jQueryUI library for drag drop. The code I gave you is based on that. If the code does not work then I need to know what is handling the drag and drop - something is handling it - your page does not allow dragging and dropping natively.

Did you try to implement the script I gave you.
0
 
Shano KhanSoftware EngineerAuthor Commented:
ok let me test it then I will update you. Currently I am at my home not at my workplace.
I will give you update after running the code in morning. If that code works then what will be the next step?
0
 
Julian HansenCommented:
The next step is the easy part - figuring out what index to use and then setting the data-target to the right dialog value. I am not worried about that - the key thing is being able to set that message on drop - once that is working the rest follows.
0
 
Shano KhanSoftware EngineerAuthor Commented:
Test Code
I have added your code below my snippet. When I drag a snippet from my sidebar on my CMS page. Then nothing happens and no error/warning of JS appears.

I think that it not works due to dropable event. Now what to do????
0
 
Julian HansenCommented:
Ok let me explain how this works - I can't tell you where to put this code because I am flying blind here.

In the link you gave me (http://innovastudio.com/builderdemo/example1.html) they have an element with a ui-droppable class. This indicates that
a) They are most probably using the jQueryUI Library
b) That there is some code that is making that component a dropable element.

If they are dynamically assigning that class and my code runs before theirs then mine will never fire.

What I need to see is how the page looks when it is rendered - this is not easy because I suspect that much of the content is rendered dynamically

The code that does the above looks like this - my code must come after the .contentbuilder()
<script type="text/javascript">
    jQuery(document).ready(function ($) {
        // SAMPLE ONLY - KEEP YOUR CODE THE SAME IF IT DOES NOT EXACTLY
        // MATCH THE CODE BELOW
        $("#contentarea").contentbuilder({
            snippetFile: 'assets/minimalist-basic/snippets.html',
            snippetOpen: true,
            toolbar: 'left',
            iconselect: 'assets/ionicons/selecticon.html'
        });

       // MY CODE HERE
       $( ".ui-droppable" ).droppable({
         drop: function( event, ui ) {
           $(ui.draggable).find('button').data('target','This is a test');
         }
      });
    });
</script>

Open in new window


So what you need to do is find where the contentbuilder() call is in your code and then add my code as above. I can't guarantee this will work though - I simply don't have enough information to be able to accurately say what you need to do here.
0
 
Shano KhanSoftware EngineerAuthor Commented:
This not works. I have checked.
Let me make it more clear and easy for you:

// See this example.
http://jsbin.com/miqahiqiqo/1/edit?html,js,console,output

Open in new window


In it There are two buttons and when user click on button1 then MODAL1 opens.
Similarly when user clicks on Modal2 then modal2 opens.

Now in my case, when user drag this button first time, then MODAL opens first time because data-target="dialog-message1" first time.
Now I want that when user drag it second time, then data-target="dialog-message2".
And If user drag it third time, then data-target="dialog-message3".

If this will be done, then everything works fine. And you just need to edit that code of: jsbin.com

thanks
0
 
Julian HansenCommented:
Let me make it more clear and easy for you:
You don't need to - I have said repeatedly I know what you want to do - what we have been trying to establish is where and how to hook the code to be able to do it.

The next step - we are going to change the code as follows.
Swap my code out for this code
$( ".ui-droppable" ).droppable({
         drop: function( event, ui ) {
           // THIS IS THE ELEMENT BEING DROPPED
           var el = $(ui.draggable);

           // MAKE IT SO WE CAN IDENTIFY IT
           el.addClass('dialog-message-btn');

           // ITERATE OVER ALL THE DROPPED BUTTONS
           $('.dialog-message-btn').each(function(i ,e) {
             // SET THE INDEX TO NON-ZERO BASED
             var count = i + 1;
             // IF THE ELEMENT DROPPED IS THE <button> THEN DO THIS
             $(e).data('target','dialog-message' + count);

             // OTHERWISE COMMENT OUT THE ABOVE LINE AND
             // UNCOMMENT THIS ONE
             // $(e).find('button').data('target','dialog-message' + count);
          });
         }
      });

Open in new window

This adds a class to each new button dropped. We then find all the buttons with that class and create data-targets for them numbered according to their index.

This may not be right for you - for instance if you can remove buttons and you want to keep the same dialog message then this might not be what you want i.e.
Add button 1 => dialog-message1
Add button 2 => dialog-message2
Add button 3 => dialog-message3

Remove button 2
Add button 1 => dialog-message1
Add button 3 => dialog-message3

Now add another button - Button 3 will change to dialog-message2 and the new button will become 3.

If you are not able to remove buttons then you should be fine - otherwise post back with how you want the above to work with respect to deletions and dialog-message counts.
0
 
Shano KhanSoftware EngineerAuthor Commented:
I have tested the code but it only allows me to drop element one time. Second time it cannot allow me to drop.

I did one thing, I have setup a small webpage which allow you to drag a snippet on your page. Due to this everything will be clear to you and it will save a lot of time. Please check it at:

http://htmlbazaar.com/del/cb-m.zip

Open in new window


kindly put it in your localhost(like xammp) and run file example.html

Thanks for your efforts
0
 
Julian HansenCommented:
Try this code
		$('.ui-droppable').on('sortstop', function(e,i) {
			// THIS IS THE ELEMENT BEING DROPPED

			var btns = $(e.target).find('button');

			// ITERATE OVER ALL THE DROPPED BUTTONS
			btns.each(function(i ,e) {
				// SET THE INDEX TO NON-ZERO BASED
				var count = i + 1;
				// IF THE ELEMENT DROPPED IS THE <button> THEN DO THIS
				$(e).data('target','dialog-message' + count);
			});
		});

Open in new window

Note when we set data attributes with code they don't show in the source (console) they are set on the object.
0
 
Shano KhanSoftware EngineerAuthor Commented:
This code works fine. I have alert a custom message and message display everytime I drop a snippet on my cms page.
Also now I have added multiple snippets and there is no issue.

Now what to check with this code?
0
 
Julian HansenCommented:
Now what to check with this code?
I don't understand the question - you need to tell me what you still need?
0
 
Shano KhanSoftware EngineerAuthor Commented:
Sorry let me try to explain:

When I drag a button control from my sidebar to my CMS page, your code will be executed.But The Modal Window will open on a different event  i.e. when I click on that button. Checkout the below code which I used previously.

jQuery( 'button.btndialog' ).button().on( 'click', function() {
					 var target = jQuery(this).data('target');
						 jQuery("#"+target).dialog( 'open' );
				 });

Open in new window

Now issue is How can I pass your TARGET variable on the CLICK event so that correct dialog will open. We are very close to completion
0
 
Julian HansenCommented:
I thought we were already doing that? My code is setting the data-target.

Your code is not suited to dynamic creation of variables though. Try this
jQuery( '#container' ).on( 'click', button.btndialog, function() {
  var target = jQuery(this).data('target');
  jQuery("#"+target).dialog( 'open' );
});

Open in new window

0
 
Shano KhanSoftware EngineerAuthor Commented:
I have tested it. And it cannot allow me to drop the snippet second time.
What ID I need to pass in #container? (confusing for me)
jQuery( '#container' ).on( 'click', button.btndialog, function() {

Open in new window

0
 
Julian HansenCommented:
Quite a few problems here
1. The jQueryUI library you are using does not include dialogs. jQueryUI offers a customisable download where you include only the components you want to use - the one you have does not support dialogs

2. You can't open a dialog you have not declared - you have to bind the dialog() to the components that contain the dialog content and then use dialog('open') to open them.

3. There was a typo in my last post #container should be #contentarea - it is important to check the code you get from the posts - we don't have access to your code so we have to guess a lot of the time - in such cases we might not always copy the code correctly - always check.

I added the generic jQueryUI library from here
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" type="text/javascript"></script>

Open in new window

I added the dialogs like so
<div id="dialog-message1" class="dialogmsg" title="Explanation">Some information for the 1st message</div>
<div id="dialog-message2" class="dialogmsg" title="Explanation">Some information for the 2nd message</div>

Open in new window

I added the prep code for the dialogs
jQuery( '.dialogmsg' ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
  Cancel: function() {
	$(this).dialog( 'close' );
  }
},
close: function() {
}
});

Open in new window

And the launch code as follows
jQuery( '#contentarea' ).on('click', 'button.btndialog', function() {
  console.log('click');
  var target = jQuery(this).data('target'); 
  $("#"+target).dialog( 'open' );
});

Open in new window


You can see it working here (for 2 buttons)
0
 
Shano KhanSoftware EngineerAuthor Commented:
thank you so much for this. Let me add it in my code to final test it and then I will get back to you.
0
 
Shano KhanSoftware EngineerAuthor Commented:
We are very close. just 1 small issues:

1) I cannot notice that counter-variable increments in this code
jQuery('.ui-droppable').on('sortstop', function(e,i) {
	// THIS IS THE ELEMENT BEING DROPPED

	var btns = jQuery(e.target).find('button');

	// ITERATE OVER ALL THE DROPPED BUTTONS
	btns.each(function(i ,e) {
		// SET THE INDEX TO NON-ZERO BASED
		var count = i + 1;
		// IF THE ELEMENT DROPPED IS THE <button> THEN DO THIS
		jQuery(e).data('target','dialog-message' + count);
	});
});

Open in new window


I have dropped 5 buttons and each element has same data-target='dialog-message' (no increment)

Due to this issue I need to add this code multiple times with different id's
<div id="dialog-message1" class="dialogmsg" title="Explanation">Some information for the 1st message</div>
<div id="dialog-message2" class="dialogmsg" title="Explanation">Some information for the 2nd message</div>

Open in new window


The only thing left is that I want to write the above code one time only so that id will be changed programatically.
0
 
Julian HansenCommented:
I have dropped 5 buttons and each element has same data-target='dialog-message' (no increment)
This is not what it seems.
A sidebar on attributes and properties.
When you declare an attribute on an element like this
<button id="button1" data-target="dialog-message">Button<button>

Open in new window

When that element is loaded the data-target attribute is used to set the equivalent property on the node. Properties exist in the DOM but are not visible in the Markup.

When we get the data-target value for a node
var target = $('#button1').data('target');

Open in new window

We are getting the value from the property of the node - not the attribute
When we set the value
$('#button1').data('target', 'some value');

Open in new window

We are setting the value on the property. This does not change the attribute - the attribute might still say something different from the property however for our purposes it is the property value that matters.

The properties on those buttons are being set correctly (as you will see from the online demo I posted) - the increment is happening.

You can verify this by doing a console.log(jQuery(e).data('target')); immediately after line 11 of the jQuery code.

I am not sure about your question - you seem to be referring to the Dialog <div>'s rather than the button's. Where do the dialog div's come from? I was under the impression you would place those on the page?
0
 
Shano KhanSoftware EngineerAuthor Commented:
You can verify this by doing a console.log(jQuery(e).data('target')); immediately after line 11 of the jQuery code.
I have verified. It works.

I am not sure about your question - you seem to be referring to the Dialog <div>'s rather than the button's. Where do the dialog div's come from? I was under the impression you would place those on the page?

Let me explain about DIV and button confusion.

1) User drag a control from sidebar and place it on PAGE
2) A button appears on the page
3) When user click on that button, A MODAL window opens with some input fields so that user can write data in in.
4) After that, user click on Save button or cancel button. If user press Save button, then data will be saved in DB.
5) This is the reason of Dialog <div>

NOTE:
As i have added a <button> code:
<button id='create-explanation1' class='btndialog' data-target="dialog-message">Add Pin</button>

Open in new window

in snippets.html file, just like that I have added a code of Modal Window below that Code
so that when user drop a button snippet on page then modal window code will also be added but with a unique id.

 Hope you got my point now.

If you have any confusion about this do ask me.

Thanks
0
 
Julian HansenCommented:
Question
1. Is the dialog the same for each button
2. What role do the different buttons play - why have them - and how does that relate to the dialog

What I am asking is - do you have to create a different dialog (layout / fields are different) for each button
OR
Do we reuse the SAME dialog but depending on which button was clicked means the data is saved differently or with different parameters?
0
 
Shano KhanSoftware EngineerAuthor Commented:
Question
1. Is the dialog the same for each button
YES
2. What role do the different buttons play - why have them - and how does that relate to the dialog
Once a Dialog will open then there is a form in it. In form there are 2 fields. And 2 buttons. First button is 'save' and second is 'cancel'
For demo: Open this link:
https://jqueryui.com/dialog/#modal-form

Open in new window

and click on 'Create New User button'

What I am asking is - do you have to create a different dialog (layout / fields are different) for each button
OR
Do we reuse the SAME dialog but depending on which button was clicked means the data is saved differently or with different parameters?
I want to use the same dialog but when I save the results in DB I will also save Dialog ID.

thanks
0
 
Shano KhanSoftware EngineerAuthor Commented:
any update?
0
 
Shano KhanSoftware EngineerAuthor Commented:
any update?
0
 
Julian HansenCommented:
So the data-target is actually misleading - it is not the dialog you want to target - you want to open the SAME dialog but set some value IN the dialog to the dialog-message1 / dialog-message2 so that you can identify (when you save) which button opened the dialog.

That is different from the original requirement but not difficult.

What value in the dialog is going to store the button id?
0
 
Shano KhanSoftware EngineerAuthor Commented:
I have done it. Check this code

$('.ui-droppable').on('sortstop', function(e,i) {

	var btns = $(e.target).find('button');

	btns.each(function(i ,e) {
		var count = i + 1;
		$(e).attr('data-target','dialog-message' + count);
	});

	var dlg = $("html").find('.dialogmsg');
	dlg.each(function(i ,e) {

		var count = i + 1;

		$(e).attr('id','dialog-message' + count);
		jQuery( '.dialogmsg' ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			buttons: {
	                       "Save": savepin_info,
				Cancel: function() {
					$(this).dialog( 'close' );
				}
			},
			close: function() {
			}
		});

	});

});

jQuery( '#contentarea' ).on('click', 'button.btndialog', function() {
	//console.log('click');
	var target = jQuery(this).data('target');
	$("#"+target).dialog( 'open' );
});

Open in new window


On MODAL save button, I am using Ajax to save data to the MySql database.
While saving I also need to save the id of modal window which is in 'TARGET' variable. (i.e. dialog-message1). In database I will just save '1'. For dialog-message2, I will just save '2'. So how to access that variable in my Ajax Method.

Here is the AJax Code
	function savepin_info()
	{

		latitude_val = jQuery("#long_map_val").val();
		longitude_val  = jQuery("#lat_map_val").val();

		test_val_d  = jQuery("#"+target).val();
		alert(test_val_d);


		jQuery.ajax({

				type: "POST",
				url: "/sc/sites/all/themes/weebpal_backend/templates/insert-pin-data.php",
				data: {latitude_val:latitude_val,longitude_val:longitude_val},
				dataType: "JSON",
				success: AjaxSucceeded,
				error: AjaxFailed

		});


		function AjaxSucceeded() {
			alert('ajax success');
		}

		function AjaxFailed()
		{
		}

		jQuery(this).dialog( 'close' );  //close dialog after save

	}

Open in new window

0
 
Julian HansenCommented:
Ok but now you are working on the premise that there is a dialog for each button

When I asked you if it was the same dialog for each button you replied YES.

In your AJAX code I don't see anything that is communicating what button was pressed - you are retrieving this value and alerting it
test_val_d  = jQuery("#"+target).val();
alert(test_val_d);

Open in new window

But you never use it.

Based on your requirements I don't see how this is working for you - but if it is great.
0
 
Shano KhanSoftware EngineerAuthor Commented:
When I asked you if it was the same dialog for each button you replied YES.
Yes.  It was a same dialog but with different id.

In your AJAX code I don't see anything that is communicating what button was pressed - you are retrieving this value and alerting it

savepin_info() method was called when user clicked on 'SAVE' button of Dialog. This method contains the AJAX code to save results to Db.

jQuery( '.dialogmsg' ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			buttons: {
				"Save": savepin_info,
				Cancel: function() {
					jQuery(this).dialog( 'close' );

				}
			},

Open in new window


The question is how to get the target value?
Let me send you the files
0
 
Shano KhanSoftware EngineerAuthor Commented:
replace these files in the folder which I have sent you and the run new-example3.html
snippets.html
new-example3.html
0
 
Julian HansenCommented:
Yes.  It was a same dialog but with different id.
But that is not what your code is doing. You have this
var dlg = $("html").find('.dialogmsg');
dlg.each(function(i ,e) {

Open in new window

That indicates a dialog for EACH button
0
 
Shano KhanSoftware EngineerAuthor Commented:
well then let me remove my code. But need your help to fix this and proceed further.
0
 
Julian HansenCommented:
Ok so we are going to use one dialog

The only question I still have is: What is the server script expecting (in terms of a parameter) to indicate which button was pressed?

What parameter name must we use to pass that value?
0
 
Shano KhanSoftware EngineerAuthor Commented:
First revise me the Scope of Work again to save time:

On Sidebar there are Different Snippets like (1) Add Pin (2) Add Projects
If user drag a 'Add Pin' snippet on page then a 'Button Appears' on Page. When user click on that button,
 A MODAL window appears which has two input fields
a) Longitude
b) Latitude
User can fill both these fields and then press on 'Save' button of MODAL window to save the data to the database.
User can drag this snippet any number of times

Similarly, If user drag a 'Add Project' snippet on page then another 'Button Appears' on Page. When user click on it,
A MODAL window appears which has three input fields
a) Enter Project Name
b) Enter Project description
c) Enter Project Images

User can fill these fields and then press on 'Save' button of MODAL window to save this data to another table of  database.
User can drag this snippet any number of times

You already have my recent files.

The only question I still have is: What is the server script expecting (in terms of a parameter) to indicate which button was pressed?
What parameter name must we use to pass that value?
This is the problem.I have not set it. No idea how to do this.
0
 
Julian HansenCommented:
I am asking you about the server - not the client.
What is the server expecting to receive in each of these cases.

The script insert-pin-data.php - what is it expecting to receive (other than lat / long values) to indicate which button was clicked?
0
 
Shano KhanSoftware EngineerAuthor Commented:
The script insert-pin-data.php - what is it expecting to receive (other than lat / long values) to indicate which button was clicked?
I am trying to fetch PIN ID but failed. As I have asked in my previous message.


Here is the php script of insert-pin-data.php:
<?php
include('db.php');

$mapid_val = 1;
$pinid_val = 1;
$long_val=$_REQUEST['longitude_val'];
$lath_val=$_REQUEST['latitude_val'];

$query_pin = "INSERT INTO map_pin_detail(map_id, pin_id, latitude, longitude)
              VALUES
              ('".$mapid_val."','".$pinid_val."', '".$lath_val."', '".$long_val."')";

$result_pin = mysqli_query($conn, $query_pin) or die("Pin Query Error = ".mysqli_error());

$queries_status = 1;

if($queries_status==1)
{
  $res="Data Inserted Successfully:";
  echo json_encode($res);
}
else
 {
  $error="Not Inserted, some Problem occur.";
  echo json_encode($error);
}

Open in new window

0
 
Julian HansenCommented:
That PHP script only retrieves REQUEST data for lat / long - where is the button ID - is that meant to be the pin_id?
0
 
Shano KhanSoftware EngineerAuthor Commented:
By Pin_ID, I mean the dropped id. Like if user dropped 'PIN ID' snippet one time, then pin_id will be '1'. On second drop it will be '2' and so on.

Regarding button id I am totally confused that how to save  button id value.
0
 
Shano KhanSoftware EngineerAuthor Commented:
waiting for your reply.
0
 
Julian HansenCommented:
Regarding button id I am totally confused that how to save  button id value.
Ok, let me explain - getting the button id onto the dialog is easy.
All we do in the button click code is get the button id value (we can set this as a different data attribute) and then when we launch the dialog we do this

$('#dialogid .button-value').val(buttonid);
Where .button-value is a class given to the hidden input on the dialog that will be used to send the value to the server.

So when we create the button
jQuery('.ui-droppable').on('sortstop', function(e,i) {
  // THIS IS THE ELEMENT BEING DROPPED

  var btns = jQuery(e.target).find('button');

  // ITERATE OVER ALL THE DROPPED BUTTONS
  btns.each(function(i ,e) {
    // SET THE INDEX TO NON-ZERO BASED
    var count = i + 1;
    // IF THE ELEMENT DROPPED IS THE <button> THEN DO THIS
    // WE CREATE THE target PROPERTY AND THE id PROPERTY ON THE BUTTON
    jQuery(e).data({
        target: 'dialog-message' + count, 
        id    : count
    });
});

Open in new window

Now when you trigger the dialog
jQuery( '#contentarea' ).on('click', 'button.btndialog', function() {
  // GET THE DATA PROPERTY AS AN OBJECT
  var data = jQuery(this).data(); 

  // WE SET THE BUTTON ID ON THE DIALOG HERE
  jQuery('#' + target + ' .button-id').val(data.id);

  // OPEN THE DIALOG
  jQuery("#"+data.target).dialog( 'open' );
});

Open in new window


All that you need to do is add this to your dialog
<input type="hidden" name="buttonid" class="button-id">

Open in new window

And then in your PHP script
<?php
...
$buttonid = isset($_POST['buttonid']) ? $_POST['buttonid'] : false;
// USE THE buttonid VALUE WHEREVER YOU NEED IT HERE

Open in new window

0
 
Shano KhanSoftware EngineerAuthor Commented:
Well, I have tried this code but I am unable to get the value of 'BUTTONID' in my PHP file.

I have also tried to fetch this variable in my JS method as I am getting Latitude and Longitude value. See below code

function savepin_info()
{
       latitude_val = jQuery("#lat_map_val").val();
	longitude_val  = jQuery("#long_map_val").val();
	buttonid_val = 	jQuery('#dialogid .button-value').val(buttonid);
       alert(buttonid_val);

	jQuery.ajax({
	

Open in new window


But here alert return blank value.

I think there is some bug in it. Please check it.

Thanks
0
 
Shano KhanSoftware EngineerAuthor Commented:
hi, have you got  a chance to check it?
Because there is one more issue. If I drop pin 4 times, A modal window opens, user fill it and press save. The values are saved in DB. After that if user click on Pin 2 modal, and fill the fields and press submit then it will save the values of modal 1. This is also the issue.

We are very close to completion. Just need to fix these small bugs.

Thanks for your efforts.
0
 
Julian HansenCommented:
buttonid_val =       jQuery('#dialogid .button-value').val(buttonid);
This sets the value - it does not retrieve it
$(selector).val() retrieves it where selector uniquely identifies the button
Somewhere in your saveipn_info() function you need to get what button you are dealing with

it will save the values of modal 1. This is also the issue.
Can't help you without code.
0
 
Shano KhanSoftware EngineerAuthor Commented:
LEt me upload code for better review.
0
 
Shano KhanSoftware EngineerAuthor Commented:
Here is the screencast of the issue. Its give you correct picture
Screencast Link

And download code from here
http://htmlbazaar.com/del/cb-m-1.zip

Open in new window


Run final.html file via localhost available in root.
Rest of the code is in /assets/default/snippets.html

Thanks and looking forward for your reply.
0
 
Julian HansenCommented:
Ok I will take a look - the problem though is you are using a dialog for each button instead of sharing the same dialog.

What is happening, I think, is you are opening the dedicated dialog but querying the first one. This should not be difficult to fix. I will download your code and have a look tomorrow.
0
 
Shano KhanSoftware EngineerAuthor Commented:
thanks and waiting.
0
 
Shano KhanSoftware EngineerAuthor Commented:
I have reupload the file. Please download it again. The link was same.
Source files


Two Issues:
https://drive.google.com/file/d/1ZwiykqzMg2ZddAO_a8VKwDIxWP4POcN5/view
https://drive.google.com/file/d/1HI1EQLHtadQJTIjLEr2TsQfo6K5IcomB/view

Open in new window


2nd Video  issue Description: On each pin, when user fill the fields of Modal Window and press Save, the data is saved in DB. and the table appears below the pin button will be updated. Similarly if user add content for Modal 2 and press save then second time table will not be updated.

Note: Other than that, If I add a new snippet in left side bar which And setup a new  Modal Window with different fields then this should work. Obvioulsly will copy/paste the Modal1 code. This is just for information.
0
 
Julian HansenCommented:
I have updated 3 of your files - there are comments in the files to say what I have done.

This should do what you want.
final.html
snippets.html
insert-pin-data.php
0
 
Shano KhanSoftware EngineerAuthor Commented:
Thats great . Almost 95% is correct just a small issue.
See attached screencat

After I drop the Pin snippet second time, and fill the modal window data then contents changes for PIN1 not for Pin2.
Similarly, on 3rd Pin, I have fill data and press save, then still it update PIN HTML. It should update Pin 3 data.

Now this is only the issue. Please update in previous files and send back. Thanks
0
 
Shano KhanSoftware EngineerAuthor Commented:
Hello, I have seen it and it works perfectly. Let me do some more tests on it and I will get back to you. Thank you so much.
0
 
Shano KhanSoftware EngineerAuthor Commented:
Can you please the file: insert-pin-data.php?
0
 
Julian HansenCommented:
Why - I did not change that?
0
 
Shano KhanSoftware EngineerAuthor Commented:
oh Actually i need to see that how to get the value of Button id to save it in DB.
0
 
Julian HansenCommented:
But you already had this - I already gave you that code - which you said was working.

Nothing has changed on the db side - only the way in which we manipulate the browser

I posted the updated PHP file here https://www.experts-exchange.com/questions/29095069/Auto-increment-with-javascript-to-open-Multiple-instances-of-jQuery-Modal-Window-dynamically.html#a42544791
You responded with
Thats great . Almost 95% is correct just a small issue.
I fixed that - now you are saying the PHP side is not correct - I am confused.
0
 
Shano KhanSoftware EngineerAuthor Commented:
Sorry I was not running my insert-pin-data.php file. I was assuming  that you have changed in it.
Now I have test it with my old file and it works perfectly.
It also fetches correct Pin/Button id.

Thank you so much for that.

PS: Let me check whether I have some question and then  I will close this thread.
0
 
Shano KhanSoftware EngineerAuthor Commented:
One important question:

I need to add one additional snippet in my snippets.html file. Just like 'Add Pin', Its name will be 'Add Project'
The Add Pin form has two fields but 'Add Project' has 3-4 fields. I am reviewing the code that how to enhance it so That
it also work with 'Add Project'

 1) I will create a new form for that like
<form id="project-dialog-message" class="dialogmsg" title="">
	<input type="hidden" name="project_id">
	<fieldset>
		<label for="name">Project Title:</label>
		<input type="text" name="projecttitle_val" id="projecttitle_val" value="" class="text ui-widget-content ui-corner-all" placeholder="Longitude">
		<label for="email">Project Description:</label>
		<input type="text" name="projectdesc_val" id="projectdesc_val" value="" class="text ui-widget-content ui-corner-all" placeholder="Latitude">
		<label for="email">Project Image:</label>
		<input type="text" name="projectimage_val" id="projectimage_val" value="" class="text ui-widget-content ui-corner-all" placeholder="Latitude">

		<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">

	</fieldset>
</form>

Open in new window


The new Modal will be open from this:
var modalDialog = $('#project-dialog-message');

Open in new window


Instead of this function savepin_info(dialog) I will change it to function saveproject_info(dialog)

But main question is: What changes I need to add in these two functions"
$('.ui-droppable').on('sortstop', function(e,i) {
		var btns = $(e.target).find('button');
		btns.each(function(i ,e) {
			var count = i + 1;
			$(e)[0].id = 'modalButton-' + count;
			$(e).data({id: count});
		});
	});

	$('#contentarea' ).on('click', 'button.btndialog', function() {
		// GET THE DATA VALUES
		var data = $(this).data();
		// GET THE DIALOG
		// SET THE HIDDEN pin_id TO THE PIN
		modalDialog.prop('mtarget',$(this).next('.long_lat_val'));

		modalDialog[0].pin_id.value = data.id;
		modalDialog.dialog('option', 'title', 'Add Pin for ' + data.id);
		modalDialog.dialog('open');
	});

Open in new window


Looking forward for your feedback on this.

Thanks
0
 
Julian HansenCommented:
I am sorry this is now deviated from the original question. This is more like a development project than a question to help you with coding.

If you want to open a Gig or a Live Request I can help you with the remaining bits - if not I suggest you close this question and open another one as the original question has been answered.
0
 
Shano KhanSoftware EngineerAuthor Commented:
Ok I apologize as I am totally new at this platform. Let me close this question because it is solved now. I will stay in touch with you.
0
 
Shano KhanSoftware EngineerAuthor Commented:
Julian is fantastic coder. He understands the problem and tried his best to resolve the issue. Thank you so much.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.