jQuery UI onchange each loop not working as expected - javascript

What I'm trying to achieve is when the list of textareas is rearranged that the name of the textareas updates to always be ordered ascending. To demonstrate:
Original
name content
value[0] content0
value[1] content1
value[2] content2
Reordered (not necessarily in this order, just an example)
name content
value[0] content2
value[1] content0
value[2] content1
What I've written should loop through the list and update the name attributes, but sometimes it just doesn't and the other times it will get the order of the names very wrong. Here's the jQuery I'm running:
$(document).ready(function(){
$( ".sortable" ).sortable();
$( ".sortable" ).disableSelection();
$( ".sortable" ).on("sortchange", function( event, ui ) {
var $i = 0;
$('.sortable > li').each(function(){
$(this).children('textarea').attr( 'name', 'value[' + $i + ']' );
$i++;
});
});
});
And a fiddle. Not sure what I'm doing wrong.

use sortstop instead of sortchange:
$(document).ready(function(){
$( ".sortable" ).sortable();
$( ".sortable" ).disableSelection();
$( ".sortable" ).on("sortstop", function( event, ui ) {
var $i = 0;
$('.sortable > li').each(function(){
$(this).children('textarea').attr( 'name', 'value[' + $i + ']' );
$i++;
});
});
});
fiddle: https://jsfiddle.net/kz4t8ph5/2/
Also take a look at Saif's answer below :)

use sortupdate instead of sortchange. sortchange is triggered during sorting that's why you are getting unexpected number sequence. sortupdate will be triggered when you stopped sorting. so you will get the final position and expected sequence.
$( ".sortable" ).on("sortupdate", function( event, ui )
{
}

Related

How to add multiple input fileds to a div using jquerys clone and append

I am using jquery, to add dynamically two input fields in a new "row" div. The problem is, that only the second input field is cloned and appended.I canĀ“t find the solution. Any help is appreciated.
Trainer= {
neuen_trainer_hinzufuegen(){
var n = $( ".trainerposition" ).length;
$( "#trainer" ).append( $('<div class="trainerposition" id="trainerposition_'+n+'"></div>') );
$( "#trainer_0_vorname" ).clone().appendTo( "#rtrainerposition_"+n );
$( "#trainerposition_"+n+" input:nth-child(2)").attr('name', 'trainer_'+n+'_vorname');
$( "#trainerposition_"+n+" input:nth-child(2)").attr('id', 'trainer_'+n+'_vorname');
$( "#trainer_0_nachname" ).clone().appendTo( "#trainerposition_"+n );
$( "#trainerposition_"+n+" input:nth-child(3)").attr('name', 'trainer_'+n+'_nachname');
$( "#trainerposition_"+n+" input:nth-child(3)").attr('id', 'trainer_'+n+'_nachname');
}
}
You have an extra r in your selector :-)
$( "#trainer_0_vorname" ).clone().appendTo( "#rtrainerposition_"+n );
I think this should be
$( "#trainer_0_vorname" ).clone().appendTo( "#trainerposition_"+n );

Weird JQuery scripts behavior

Applied DataTable (jquery.dataTables.min.js) to the existing table, so having that table paged and sorted:
$( '#news_table' ).DataTable( {
"order": [[ 5, "asc" ]],
"lengthMenu": [5, 10, 20],
} );
Everything works smoothly on first page of the table. Some JQuery scripts stop working correctly when change page. So, there are related chunks of code:
<td>
<a href="#myModal" class="editNews" role="button" data-toggle="modal" data-id="${news.id}">
<img src="resources/img/edit.png"></img>
</a>
</td>
By clicking on image (edit.png) modal window appears. The next part converts the modal to the edit flavour.
$( '.editNews' ).click(function(e) {
e.preventDefault();
$( '#deleteNews' ).removeClass( 'notShow' );
var dataId = $( this ).attr( 'data-id' );
$( '#resetNews' ).addClass( 'notShow' );
$.ajax({
type: "GET",
dataType: "json",
url: "admin/update/" + dataId,
success: function( response ) {
console.log( response );
$( '#myModalLabel' ).html( "Edit post with id:<span style='color: rgb(255, 0, 0);'>" + response.id + "</span>" );
$( '#newsId' ).text( response.id );
$( '#incomingDate' ).text( response.incomingDate );
$( '#changeDate' ).text( response.changeDate );
$( '#messageTitle' ).val( response.title );
$( 'div#messageStatus button' ).each(function( index ) {
if ( response.messageStatus == index + 1) {
$( this ).addClass( 'active' );
}
});
$( '.note-editable' ).html( response.message );
$( '#messageOrder' ).text( response.messageOrder );
$( '#myModal' ).modal( 'show' );
},
complete:function() {
}
});
return false;
});
I mean, that clicking, say on the link (edit.png) on any page excepting first one modal window will still appear, but will be empty, so looks like scripts just missed. I tried to figure it out, but stuck.
There are also some other scripts which also stopped acting properly.
Thanks for the any advice.
Images below illustrate the situation:
Hi this is quite common problem, you use your jQuery code once (on DOM ready I suppose).
When you click pagination table is generated again and that new elements are not bind to your jQuery code.
You have to 1) run jQuery code after each ajax request maybe using ajax complete:function() {//put me here...
or 2)
use jQuery "on"
$( "body" ).on( "click", ".editNews", function() {
//put your code here
});

Variable from jquery to PHP wordpress

I'm building in Wordpress, I know I need to use AJAX, but not how to do so.
I have a drop down select box, when the user selects an option a div appears.
The data in that div needs to be pulled from a custom post, so I have a php variable to do this.
What I need to do, is be able to change that php variable based on the selection of the drop down.
I can do this in jQuery, but I don't know how to transfer the jQuery var to php.
Any assistance would be much appreciated.
$(document).ready(function(){
$('select').change(function(){
$( 'select option:selected').each(function(){
if($(this).attr('value')=='choose'){
hide_visible();
}
var val = $('#course_select option:selected').val();
var course_id;
if (val == 'CPR'){
course_id = 106; <!-- I need to send this to php -->
$( '#course_id' ).val(course_id);
};
if($(this).attr('value') == val){
if ($( '.course-info ' ).is(':visible')) {
$( '.course-info' ).slideUp( 'slow' ).delay(700);
$( '.iframe' ).slideUp( 'slow' );
$( '.form' ).slideUp( 'slow' );
$( '.'+ val ).slideDown( 'slow' );
}else{
$('.iframe').slideUp( 'slow' );
$( '.course-info' ).slideUp( 'slow' );
$( '.'+ val ).slideDown( 'slow' );
};
}
});
}).change();
});
From your edited question, you can just do something like the following:
$('.result-element').load('my-page.php?courseid=' + courseId);
Look into api.jquery.com/load for more information is using jQuery.load().
Your my-page.php can get "courseid" from $_GET['courseid'] and you can just echo your raw HTML as a "partial" which jQuery will automatically add to the '.result-element' element.
You won't need your PHP variable.
On the change event of your drop down, fetch the value selected, then build your ajax query and send it to the server.
Checkout the following functions of jQuery: ajax(), change(), val(), html(), show().
You also need to setup an endpoint for jQuery to request the data. Something like http://domain.com/api/get-my-data. That's a wordpress task (ie. PHP). This endpoint / script should return a JSON encoded object that contains the content of your div.
Maybe this helps additional that you're using jquery also. cheers men :)
$(document).ready(function(){
$('select').change(function(){
$( 'select option:selected').each(function()
{
if($(this).attr('value')=='choose')
{
hide_visible();
}
var val = $('#course_select option:selected').val();
var course_id;
if (val == 'CPR')
{
course_id = 106; // Sample code where you can send your jquery variable to php page
$.post("send_variable.php", {id:val}, function(data){
alert(data) //shouts the data from send_variable.php page
$("#hiddenTextbox").val(data); //this passes the value from send_variable.php to a textbox with Id(hiddenTextbox) into the page
});
$( '#course_id' ).val(course_id);
}
if($(this).attr('value') == val)
{
if ($( '.course-info ' ).is(':visible'))
{
$( '.course-info' ).slideUp( 'slow' ).delay(700);
$( '.iframe' ).slideUp( 'slow' );
$( '.form' ).slideUp( 'slow' );
$( '.'+ val ).slideDown( 'slow' );
}
else
{
$('.iframe').slideUp( 'slow' );
$( '.course-info' ).slideUp( 'slow' );
$( '.'+ val ).slideDown( 'slow' );
}
}
}
});
}).change();
Here's the code for send_variable.php
<?php
$val1 = $_POST['id'];
echo $val1; //thus returning the data that depends on your selected from dropdown
?>
Hopes this helps :)

tabs submiting form on new window, why?

I have an issue here.
I've been using Tabs (widget jqueryUi).
All seems to work fine, but sometimes when I submit a form (inside the tab), the result comes in the window and not in the tabdiv.
I don't want that, the client has to keep in the websystem.
I already tried putting target="_self" in the form, but keep doing the issue sometimes.
var $tabs = $("#main").tabs({
tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close notext inline'>Remove Tab</span></li>",
idPrefix: "tab_",
add:function(e, ui){
$tabs.tabs('select', '#' + ui.panel.id).show("blind");
$j( "#list_tabs .ui-icon-close:last" ).on( "click", function(e, elemento) {
var index = $( "li", $("#main").tabs() ).index( $( this ).parent() );
$("#main").tabs( "remove", index );
desativarItemSubmenu($('#' + $(this).parent()[0].id.replace('tab_', '')));
});
},
select: function(event, ui){
var id = $(ui.tab).parent()[0].id;
if(id)
ativarItemSubmenu($('#' + id.replace('tab_', '')));
},
cache:true,
ajaxOptions: {async: false,cache: false}
})
$(".anchor").live("click", function(){
if("<?php echo $this->session->userdata("cod_usuario") ?>" == ""){
window.location.reload;
}
var url = this.rel;
var tab_title = this.text;
var tab_id = "tab_"+this.id;
if(!$('#' + tab_id).length){
if($('#main').tabs('length') > 3)
$("#main").tabs("remove", 3);
$("#main").tabs("add", url, tab_title);
$("#list_tabs li:last").attr("id", tab_id);
$("#list_tabs li:last").addClass("active");
}
else{
$('#main').tabs('option', 'selected', $('#' + tab_id).index());
}
})
// Remove a tab clicando no "x" (remove tab by click on "x")
$( "#main span.ui-icon-close" ).live( "click", function() {
var index = $( "li", $("#main").tabs() ).index( $( this ).parent() );
$("#main").tabs( "remove", index );
});
I am not fully confident about this answer, but if not the solution then perhaps it will give you ideas that could lead to the solution.
It appears that you are changing the ID attribute of tabs on the fly. When you change an element's ID, you remove it from the DOM -- or rather, you re-inject it as a new element into the DOM. Therefore, any javascript that was previously bound to that element is no longer bound. Since you are using jQuery UI tabs, the changed element may stop being a tab.
This could cause the type of problem that you are describing.
Solution: instead of changing the tab ID, refactor your code to use classes that you add/remove.
As a general rule, use great caution when changing IDs on the fly.

Update number on jQuery UI tooltips

I have folders with tooltips such as '0 entries' or '5 entries' and so on. I need this tooltip number to update by 1 every time something is dropped into the folder. The title doesn't always start at zero, and I need $(this) drop div updated, as I have many. Here is the working fiddle http://jsfiddle.net/4ehSG/3
jQuery
$(document).tooltip();
var dropped =0;
$( ".draggable" ).draggable();
$( ".droppable" ).droppable({
drop: function( event, ui ) {
dropped++;
$( this )
.attr('title',dropped+' entries')
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
$( ".draggable" ).fadeOut();
}
});
HTML
<div class="draggable ui-widget-content">
<p>Drag me to my target</p>
</div>
<div class="droppable ui-widget-header" title='2 entries'>
<p>Drop here</p>
</div>
Here is an example of what you can do: http://jsfiddle.net/4ehSG/9/
drop: function( event, ui ) {
var dropped = parseInt($(this).attr('title')) + 1;
$( this )
.attr('title',dropped+' entries')
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
$( ".draggable" ).fadeOut();
}
You could increase a variable every time an element is dropped
try this
$(document).tooltip();
var num = 0;
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
num++;
$( "#draggable" ).fadeOut();
$( "#droppable" ).attr("title", num + " entries");
}
});
your updated example: http://jsfiddle.net/4ehSG/4/
If you have multiple instances of droppable and draggable, you may want to give each droppable an array associated with it. That way you don't need to rely on a count object and you could drop the same draggable on multiple droppable objects.
DEMO
$(document).tooltip();
$( ".draggable" ).draggable();
$( ".droppable" ).droppable({
drop: function( event, ui ) {
if(!$(this).data('droplist')){ //check for array
$(this).data('droplist', []); //if doesn't exist, create array
}
var droplist = $(this).data('droplist'),
drag = $(ui.draggable)[0];
if(droplist.indexOf(drag) === -1) //check if element exists in array
droplist.push(drag);
$( this )
.addClass( 'ui-state-highlight' )
.find( 'p' )
.html( 'Dropped!' )
.end()
.attr('title', droplist.length + ' entries');
$(this).data('droplist', droplist); //set list
}
});
DEMO
$(document).tooltip();
var count = 0;
$("#draggable").draggable();
$("#droppable").droppable({
drop: function (event, ui) {
count++;
$(this)
.attr('title', count + ' entries')
.addClass("ui-state-highlight")
.find("p")
.html("Dropped!");
$("#draggable").fadeOut();
}
});
You can use:
document.getElementById('droppable').title = value;
The above line of code is without using jQuery.
If you want to use jQuery, use the following:
$("#droppable").attr( 'title', value );

Categories