HTML Select styled by jQuery with infinite loop - javascript

I have styled my select items using JQuery, which outputs the items in an unordered list. This is working. I've used some javascript to create in infinite scroll effect on the unordered list. The infinite scroll basically repeats the entire list resulting in two identical sets of list items. However, the cloned set list items are not clickable and thus the form does not render any results when clicking the cloned list items.
Link to the select in question (try the Emotional Quality Select) - http://dev.chrislamdesign.com/shortwave/sample-page/
Link to codepen infinite scroll - https://codepen.io/doctorlam/pen/oKgRvO
Here's my PHP
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<div class="container d-flex justify-content-between">
<div class="row" style="width: 100%">
<?php
if( $terms = get_terms( array('hide_empty' => false,'taxonomy' => 'emotional_quality', 'orderby' => 'name' ) ) ) : ?>
<div id="emotional" class="col-md-4">
<?php
echo '<select class="form-submit" name="categoryfilter2"><option value="">Emotional Quality</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>'; ?>
</div>
<?php endif;
if( $terms = get_terms( array( 'hide_empty' => false,'taxonomy' => 'genre', 'orderby' => 'name' ) ) ) : ?>
<div id="genre" class="col-md-4">
<?php echo '<select class= "form-submit" name="categoryfilter"><option value="">Select genre...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>'; ?>
</div>
<?php endif;
if( $terms = get_terms( array( 'hide_empty' => false,'taxonomy' => 'cinematic_style', 'orderby' => 'name' ) ) ) : ?>
<div id="cinematic" class="col-md-4">
<?php echo '<select class="form-submit" name="categoryfilter3"><option value="">Cinematic Style</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>'; ?>
</div>
<?php endif;
?>
<!-- <button>Apply filter</button> -->
<input type="hidden" name="action" value="myfilter">
</div><!-- row -->
</div>
</form>
Here's the Javascript to style the select
<script>
jQuery(document).ready(function($){
$('select').each(function(){
var $this = $(this), numberOfOptions = $(this).children('option').length;
$this.addClass('select-hidden');
$this.wrap('<div class="select"></div>');
$this.after('<div class="select-styled"></div>');
var $styledSelect = $this.next('div.select-styled');
$styledSelect.text($this.children('option').eq(0).text());
var $list = $('<ul />', {
'class': 'select-options'
}).insertAfter($styledSelect);
$list.wrap('<div class="scroll-container"><div class="wrap-container"></div></div>');
for (var i = 0; i < numberOfOptions; i++) {
$('<li />', {
text: $this.children('option').eq(i).text(),
rel: $this.children('option').eq(i).val()
}).appendTo($list);
}
var $listItems = $list.children('li');
$styledSelect.click(function(e) {
e.stopPropagation();
$('div.select-styled.active').not(this).each(function(){
$(this).removeClass('active').next('.scroll-container').hide();
});
$(this).toggleClass('active').next('.scroll-container').toggle();
});
$listItems.click(function(e) {
e.stopPropagation();
$styledSelect.text($(this).text()).removeClass('active');
$this.val($(this).attr('rel'));
$('.scroll-container').hide();
//console.log($this.val());
});
$(document).click(function() {
$styledSelect.removeClass('active');
$('.scroll-container').hide();
});
});
});
</script>
Here's the Javascript for the infinite scroll
<script>
jQuery(function($){
$('#emotional .wrap-container').attr('id', 'wrap-scroll-1');
$('#emotional .wrap-container ul').attr('id', 'ul-scroll-1');
$('#genre .wrap-container').attr('id', 'wrap-scroll-2');
$('#genre .wrap-container ul').attr('id', 'ul-scroll-2');
$('#cinematic .wrap-container').attr('id', 'wrap-scroll-3');
$('#cinematic .wrap-container ul').attr('id', 'ul-scroll-3');
});
</script>
<!-- Infiinite scroll for emotional quality-->
<script>
var scrollW = document.getElementById("wrap-scroll-1");
var scrollUl = document.getElementById("ul-scroll-1");
var itemsScrolled,
itemsMax,
cloned = false;
var listOpts = {
itemCount: null,
itemHeight: null,
items: []
};
function scrollWrap() {
var scrollW = document.getElementById("wrap-scroll-1");
var scrollUl = document.getElementById("ul-scroll-1");
itemsScrolled = Math.ceil(
(this.scrollTop + listOpts.itemHeight / 2) / listOpts.itemHeight
);
if (this.scrollTop < 1) {
itemsScrolled = 0;
}
listOpts.items.forEach(function(ele) {
ele.classList.remove("active");
});
if (itemsScrolled < listOpts.items.length) {
listOpts.items[itemsScrolled].classList.add("active");
}
if (itemsScrolled > listOpts.items.length - 3) {
var node;
for (_x = 0; _x <= itemsMax - 1; _x++) {
node = listOpts.items[_x];
if (!cloned) {
node = listOpts.items[_x].cloneNode(true);
}
scrollUl.appendChild(node);
}
initItems(cloned);
cloned = true;
itemsScrolled = 0;
}
}
function initItems(scrollSmooth) {
var scrollUl = document.getElementById("ul-scroll-1");
var scrollW = document.getElementById("wrap-scroll-1");
listOpts.items = [].slice.call(scrollUl.querySelectorAll("li"));
listOpts.itemHeight = listOpts.items[0].clientHeight;
listOpts.itemCount = listOpts.items.length;
if (!itemsMax) {
itemsMax = listOpts.itemCount;
}
if (scrollSmooth) {
var scrollW = document.getElementById("wrap-scroll-1");
var seamLessScrollPoint = (itemsMax - 3) * listOpts.itemHeight;
scrollW.scrollTop = seamLessScrollPoint;
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var scrollW = document.getElementById("wrap-scroll-1");
initItems();
scrollW.onscroll = scrollWrap;
});
</script>
AJAX CALL
<script>
jQuery(function($){
jQuery('.select-options li').click(function() {
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
</script>
The original list items trigger the form and return the correct results. The cloned list items don't. I think it has to do with the identical rel values but am not sure.

Changing your ajax call to the below suggested way should make the click work for you:
<script>
jQuery(function($){
jQuery('body').on('click', '.select-options li', function() {
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
</script>
The reason as to why this should work is because now the click event is bound on the class irrespective of whether the element with that class was loaded in DOM loading or after the DOM was loaded completely.
The direct call to .click or in the format jQuery('.select-options li').on('click', function(){}); only binds event to elements loaded before the DOM was ready.

Related

How to pass select option values from php code to Jquery?

When clicking add row button, new row will add to the specific table. So I need to add a select option with php option values.
How to pass this php values to jQuery?
Jquery function
I need to show select option inside the rowData.push('');
$('.dt-add').each(function () {
var whichtable = $(this).parents('form').attr('data-id');
$(this).on('click', function(evt){
//Create some data and insert it
var rowData = [];
var table = $('#teammembertable' + whichtable).DataTable();
// rowData.push('');
rowData.push('<select class="form-control addstafftype" id="addstafftype" name="addstafftype"><option value="">Select</option><option value="Leader">Leader</option><option value="Technician">Technician</option></select');
rowData.push('<button type="button" data-id='+ whichtable +' class="btn-xs dt-delete dt-deletes"><i style="font-size:10px" class="fa"></i></button>');
table.row.add(rowData).draw( false );
});
});
PHP CODE
$dataadd_team_memb = array(
'team_id' => $id,
'Staff_id' => $this->input->post('getaddstaffname'),
'Staff_type' => $this->input->post('getaddstafftype'),
'status' => "active"
);
$insert_id = 0;
if ($this->db->insert("team_members", $data)) {
$insert_id = $this->db->insert_id();
}
$('.dt-add').each(function () {
var whichtable = $(this).parents('form').attr('data-id');
$(this).on('click', function(evt){
var rowData = [];
var table = $('#teammembertable' + whichtable).DataTable();
rowData.push('<select class="form-control addstafftype" id="addstafftype" name="addstafftype">'+
'<option value="">Select</option>'+
'<?php foreach($selectallstaff as $staffname){ ?>'+
'<option value="<?php $staffname["Staff_id"]; ?>"><?php $staffname["Staff_name"]; ?></option>'+
'<?php } ?>'+
'</select');
rowData.push('<button type="button" data-id='+ whichtable +' class="btn-xs dt-delete dt-deletes"><i style="font-size:10px" class="fa"></i></button>');
table.row.add(rowData).draw( false );
});
});

button radio wont stay checked after update Wordpress

I m trying to implement query with custom fields on my local wordpress website.
All works like a charm except when I check the radio button, this one want to be checked...
Can you help me please ? thanks for your reply.
<div id="archive-filters">
<?php foreach( $GLOBALS['my_query_filters'] as $key => $name ):
$field = get_field_object($key);
if( isset($_GET[ $name ]) ) {
$field['value'] = explode(',', $_GET[ $name ]);
}
// create filter
?>
<div class="filter" data-filter="<?php echo $name; ?>">
<?php create_field( $field ); ?>
</div>
<?php endforeach; ?>
</div>
<script type="text/javascript">
(function($) {
// change
$('#archive-filters').on('change', 'input[type="radio"]', function(){
var url = '';
args = {};
$('#archive-filters .filter').each(function(){
var filter = $(this).data('filter'),
vals = [];
$(this).find('input:checked').each(function(){
vals.push( $(this).val() );
});
// append to args
args[ filter ] = vals.join(',');
});
// update url
url += '?';
// loop over args
$.each(args, function( name, value ){
url += name + '=' + value + '&';
});
// remove last &
url = url.slice(0, -1);
// reload page
window.location.replace( url );
});
})(jQuery);
</script>

Add / Update Custom Fields After Select Pictures in Media Window (Wordpress)

I have a question about wordpress, I just added a button called Add Slider in Add/Edit Post Page.
here's my code in my function.php :
//Add button to create slider
add_action('media_buttons','add_my_media_button',15);
function add_my_media_button(){
echo 'Add Slider';
}
function include_media_button_js_file(){
wp_enqueue_script('media_button',get_bloginfo('template_directory').'/js/media_button.js',array('jquery'),'1.0',true);
}
add_action('wp_enqueue_media','include_media_button_js_file');
and this my media_button.js code
jQuery(function($){
$(document).ready(function(){
$('#insert-my-media').click(open_media_window);
})
function open_media_window(){
if (this.window === undefined) {
this.window = wp.media({
title: 'Insert a media',
library: {type:'image'},
multiple: true,
button: {text:'Insert'}
});
var self = this; //needed to retrieve the function below
this.window.on('select',function(){
var files = self.window.state().get('selection').toArray();
var values;
for (var i = 0; i < files.length; i++) {
var file = files[i].toJSON();
if(values===undefined){
var values = file.url;
}
else{
var values = values+','+file.url;
}
};
wp.media.editor.insert(values);
});
}
this.window.open();
return false;
}
});
after user select the pictures in media window and press Insert button it will add url value of pictures to content editor post box.
My question is how to add this value automatically on custom fields box and add/update that automatically without click add custom field button.
So user can add / update custom fields for that pictures url without view/ check custom fields to view in post editor on Screen Options in wordpress.
Please help me for this question, Thanks.
I modify my jquery / js like this..
$(document).ready(function(){
// $('#insert-my-media').click(open_media_window);
if($('#images_id').val() != '' && $('#images_url').val() != ''){
$('#open_media').text("Edit Slider");
}
$('#open_media').click(function(e){
e.preventDefault();
var target = $('#images_id');
var target_url = $('#images_url');
var btnSave = $('#publishing-action input.button');
if(target.val() == '' && target_url.val() == ''){
var wpmedia = wp.media({
title: 'Insert a media',
library: {type:'image'},
multiple: true,
button: {text:'Insert'}
});
wpmedia.on('select', function(){
var ids = [];
var urls = [];
var models = wpmedia.state().get('selection').toArray();
for (var i = 0; i < models.length; i++) {
var file = models[i].toJSON();
ids.push(file.id);
urls.push(file.url);
};
target.val(ids.join(","));
target_url.val(urls.join(","));
$('#deleting_slider').val("");
$('#open_media').text("Adding...");
btnSave.click();
});
wpmedia.open();
}else{
wp.media.gallery
.edit('[gallery ids="'+ target.val() +'" urls="'+ target_url.val() +'"]')
.on('update', function(g){
var ids = [];
var urls = [];
for (var i = 0; i < g.models.length; i++) {
var file = g.models[i].toJSON();
ids.push(file.id);
urls.push(file.url);
};
target.val(ids.join(","));
target_url.val(urls.join(","));
$('#deleting_slider').val("");
$('#open_media').text("Editing...");
btnSave.click();
});
}
});
$('#save_desc').click(function(e){
e.preventDefault();
var target = $('#desc_editor');
var btnSave = $('#publishing-action input.button');
target.val(target.val());
btnSave.click();
});
$('#delete_slider').click(function(e){
e.preventDefault();
/*var target = $('#images_id');
var target_url = $('#images_url');*/
var btnSave = $('#publishing-action input.button');
/*target.val("");
target_url.val("");*/
$('#deleting_slider').val("Deleting...");
$('#delete_slider').text("Deleting...");
btnSave.click();
});
});
and then I make file called metabox.php to create metabox
<?php
function koplan_add_metabox(){
add_meta_box(
'koplan_metabox_gallery',
'Slider Gallery',
'koplan_show_metabox',
'post'
);
}
function koplan_add_maps_metabox(){
add_meta_box(
'koplan_metabox_maps',
'Maps Descriptions',
'koplan_show_maps_metabox',
'post'
);
}
function koplan_show_metabox($post){
$ids = get_post_meta($post->ID, 'gallery_images', true);
$urls = get_post_meta($post->ID,'images',true);
?>
Add Slider
<hr>
<input type="hidden" name="gallery_images" id="images_id" value="<?php echo $ids; ?>">
<input type="hidden" name="gallery_urls" id="images_url" value="<?php echo $urls; ?>">
<input type="hidden" name="deleting_slider_post_meta" id="deleting_slider" value="<?php echo $urls; ?>">
<?php
if($ids=="" and $urls==""){
return;
}
else{
echo do_shortcode('[gallery ids="'.$ids.'" urls="'.$urls.'"]');
}
?>
<hr>
Delete Slider
<?php
}
function koplan_save_gallery_metabox($post_id){
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if(! isset($_POST['gallery_images']) && !isset($_POST['gallery_urls'])){
return;
}
$ids = sanitize_text_field( $_POST['gallery_images'] );
$urls = sanitize_text_field( $_POST['gallery_urls'] );
$terms = wp_get_object_terms( $post_id, 'category', array( 'fields' => 'names' ) );
/*$termsname = $terms[0]->name;*/
if(strlen($terms[1]) > strlen($terms[0])){
$term = $terms[1];
}
else{
$term = $terms[0];
}
$sldata = '<slider images="'.$term.'" />';
update_post_meta($post_id, 'slider', $sldata);
update_post_meta($post_id, 'gallery_images', $ids);
update_post_meta($post_id, 'images', $urls);
if(isset($_POST['deleting_slider_post_meta']) && $_POST['deleting_slider_post_meta'] != ""){
delete_post_meta($post_id, 'slider', $sldata);
delete_post_meta($post_id, 'gallery_images', $ids);
delete_post_meta($post_id, 'images', $urls);
}
}
function koplan_show_maps_metabox($post){
$desc = get_post_meta($post->ID,'mapsdesc',true);
if($desc!=""){
?>
<textarea name="maps_descriptions" id="desc_editor" placeholder="Insert Descriptions Here" class="wp-editor-area" cols="40" autocomplete="off" style="height:320px; width:100%;"><?php echo $desc; ?></textarea>
<?php
}else{
?>
<textarea name="maps_descriptions" id="desc_editor" placeholder="Insert Descriptions Here" class="wp-editor-area" cols="40" autocomplete="off" style="height:320px; width:100%;"></textarea>
<?php
}
?>
<hr>
Save
<?php
}
function koplan_save_maps_desc_metabox($post_id){
if (define('DOING_AUTOSAVE') && DOING_AUTOSAVE){
return;
}
if(!isset($_POST['maps_descriptions'])){
return;
}
$desc = $_POST['maps_descriptions'];
update_post_meta($post_id,'mapsdesc',$desc);
}
add_action( 'add_meta_boxes', 'koplan_add_metabox' );
add_action('add_meta_boxes','koplan_add_maps_metabox');
add_action( 'save_post', 'koplan_save_gallery_metabox' );
add_action( 'save_post', 'koplan_save_maps_desc_metabox' );
?>
I said problem solved, case closed. Thanks all, thanks stackoverflow

Dependent drop down is not working

In this below code i have 2 dropdown in one dropdown i get course code from course subject table and in another drop relevant subject code for selected course code from course subject table should be displayed. But i cant get the dependent dropdown subject code .Pls any one help me.
Controller:student_site
function search_by_course()
{
$this->load->model('subject_model');
$id = $this->input->post('subject_id');
//get your data from model
$res_subject = $this->subject_model->subject_list($id);
$html_string = "";
$html_string .= "<select id='subject_code_id'>";
for($x=0;$x<count($res_subject);$x++)
{
$html .= "<option id=".$res_subject[$x]->subject_id.">".$res_subject[$x]->subject_name."</option>";
}
$html_string .= "</select>";
echo json_encode(array('html_string'=>$html_string));
}
model:student_model
function subject_list($id)
{
//echo "exam_name inside get_subject_records".$exam_name;
//$this->db->select('course_code,subject_code');
//$this->db->where('exam_name',$exam_name);
$this->db->where('course_code',$course_name);
$query = $this->db->get('coursesubject');
return $query->result();
}
view:student_detail_view
<td >
<?php
$js = 'class="dropdown_class" id="course_code_id'.$row->id.'" ';
$js_name = 'course_code_id'.$row->id;
echo form_dropdown($js_name, $data, $row->course_code, $js);
?>
</td>
<td>
<div class="subject"></div>
</td>
<script>
$(function(){
$("#course_code_id").live("change keypress",function(){
var id = 0;
id = $(this).val();
if( $(this).val() !==''){
$.post('<?php echo site_url('student_site/search_by_course') ?>',
{
subject_id: id
},function(data){
$(".subject").html( data['html_string']);
},"JSON"
);
}
});
});
</script>
Changes to do:
In view:
<div class="subject">
<select id="subject_code_id"></select>
</div>
<script>
$(function(){
$("#course_code_id").live("change", function(){
var id = $(this).val();
if( id != ''){
$.ajax({
url : '<?=base_url('student_site/search_by_course')?>',
type : 'POST',
data : { 'subject_id' : id },
success : function(resp){
if( resp != "" ){
$("#subject_code_id").html('resp');
}else{
alert("No response!");
}
},
error : function(resp){
alert("Error!");
}
});
}
});
});
</script>
In controller:
function search_by_course(){
$this->load->model('subject_model');
$id = $this->input->post('subject_id');
//get your data from model
$res_subject = $this->subject_model->subject_list($id);
$html_string = "";
//$html_string .= "<select id='subject_code_id'>";
for($x=0;$x<count($res_subject);$x++)
{
$html .= "<option id=".$res_subject[$x]->subject_id.">".$res_subject[$x]->subject_name."</option>";
}
//$html_string .= "</select>";
//echo json_encode(array('html_string'=>$html_string));
echo $html_string;
}

JS - jQuery Dynamic add remove Input Fields

I have a form where I add Input fields ( groups ) dynamically.
It is quite a complex form, and a PART can be seen here : FIDDLE
The actual error i get on the consul is :
Error: uncaught exception: query function not defined for Select2 s2id_autogen1
When I have fields already in the form ( the first two for example ) the EDIT and REMOVE button will work just fine .
My problem is that the REMOVE button ( styled input field ) is not working for the dynamically ADDED fields ( actually "appended" by JS and populated from PHP )
NOTE on code: I know the code is a mess :-(. It was inherited and will be cleaned soon.
it was copied and pasted from the HTML output.
The ADD , REMOVE and EDIT are actually styled like buttons ( too long and irrelevant to paste )
The actual source is PHP and it is spanning over multiple files ( so is the JS ) , and thus a bit too complicated to show here .
UPDATE : The code as per popular request :-)
public function show_field_repeater( $field, $meta ) {
global $post;
// Get Plugin Path
$plugin_path = $this->SelfPath;
$this->show_field_begin( $field, $meta );
$class = '';
if ($field['sortable'])
$class = " repeater-sortable";
echo "<div class='at-repeat".$class."' id='{$field['id']}'>";
$c = 0;
$meta = get_post_meta($post->ID,$field['id'],true);
if (count($meta) > 0 && is_array($meta) ){
foreach ($meta as $me){
//for labling toggles
$mmm = isset($me[$field['fields'][0]['id']])? $me[$field['fields'][0]['id']]: "";
echo '<div class="at-repater-block at-repater-block-'.$c.$field['id'].'"><h3>'.$mmm.'
<span class="at-re-remove">
<input id="remove-'.$c.$field['id'].'" class="buttom button-primary" type="submitkb" value="Remove '.$field['name'].'" accesskey="x" name="removek">
</span>';
echo '<script>
jQuery(document).ready(function() {
jQuery("#remove-'.$c.$field['id'].'").on(\'click\', function() {
var answer = confirm("Are you sure you want to delete this field ??")
if(!answer){
event.preventDefault();
}
jQuery(".at-repater-block-'.$c.$field['id'].'").remove();
});
});
</script>';
echo '<span class="at-re-toggle">
<input id="edit-'.$field['id'].'" class="buttom button-primary" type="" value="Edit '.$field['name'].'" accesskey="p" name="editk"></h3>
</span>
<span style="display: none;">
<table class="repeate-box wp-list-table widefat fixed posts" >';
if ($field['inline']){
echo '<tr class="post-1 type-post status-publish format-standard hentry category-uncategorized alternate iedit author-self" VALIGN="top">';
}
foreach ($field['fields'] as $f){
//reset var $id for repeater
$id = '';
$id = $field['id'].'['.$c.']['.$f['id'].']';
$m = isset($me[$f['id']]) ? $me[$f['id']]: '';
$m = ( $m !== '' ) ? $m : $f['std'];
if ('image' != $f['type'] && $f['type'] != 'repeater')
$m = is_array( $m) ? array_map( 'esc_attr', $m ) : esc_attr( $m);
//set new id for field in array format
$f['id'] = $id;
if (!$field['inline']){
echo '<tr>';
}
call_user_func ( array( &$this, 'show_field_' . $f['type'] ), $f, $m);
if (!$field['inline']){
echo '</tr>';
}
}
if ($field['inline']){
echo '</tr>';
}
echo '</table></span>
<span class="at-re-toggle"><img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/edit.png';
}else{
echo 'http://i.imgur.com/ka0E2.png';
}
echo '" alt="Edit" title="Edit"/></span>
<img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/remove.png';
}else{
echo 'http://i.imgur.com/g8Duj.png';
}
echo '" alt="'.__('Remove','mmb').'" title="'.__('Remove','mmb').'"></div>';
$c = $c + 1;
}
}
echo '<img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/add.png';
}else{
echo 'http://i.imgur.com/w5Tuc.png';
}
echo '" alt="'.__('Add','mmb').'" title="'.__('Add','mmb').'" ><br/><input id="add-'.$field['id'].'" class="buttom button-primary" type="submitk" value="Add '.$field['name'].'" accesskey="q" name="addk"></div>';
//create all fields once more for js function and catch with object buffer
ob_start();
echo '<div class="at-repater-block">';
echo '<table class="wp-list-table repeater-table">';
if ($field['inline']){
echo '<tr class="post-1 type-post status-publish format-standard hentry category-uncategorized alternate iedit author-self" VALIGN="top">';
}
foreach ($field['fields'] as $f){
//reset var $id for repeater
$id = '';
$id = $field['id'].'[CurrentCounter]['.$f['id'].']';
$f['id'] = $id;
if (!$field['inline']){
echo '<tr>';
}
if ($f['type'] != 'wysiwyg')
call_user_func ( array( &$this, 'show_field_' . $f['type'] ), $f, '');
else
call_user_func ( array( &$this, 'show_field_' . $f['type'] ), $f, '',true);
if (!$field['inline']){
echo '</tr>';
}
}
$js_code2 ='<span class=\"at-re-remove\"><input id="remove-'.$c.$field['id'].'" class="buttom button-primary remove-'.$c.$field['id'].'" type="submi7" value="Removevv " accesskey="7" name="remove7"></span>';
if ($field['inline']){
echo '</tr>';
}
$js_code2 = str_replace("\n","",$js_code2);
$js_code2 = str_replace("\r","",$js_code2);
$js_code2 = str_replace("'","\"",$js_code2);
echo $js_code2;
echo '</table><img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/remove.png';
}else{
echo 'http://i.imgur.com/g8Duj.png';
}
echo '" alt="'.__('Remove','mmb').'" title="'.__('Remove','mmb').'" ></div>';
$counter = 'countadd_'.$field['id'];
$js_code = ob_get_clean ();
$js_code = str_replace("\n","",$js_code);
$js_code = str_replace("\r","",$js_code);
$js_code = str_replace("'","\"",$js_code);
$js_code = str_replace("CurrentCounter","' + ".$counter." + '",$js_code);
echo '<script>
jQuery(document).ready(function() {
var '.$counter.' = '.$c.';
jQuery("#add-'.$field['id'].'").on(\'click\', function() {
'.$counter.' = '.$counter.' + 1;
jQuery(this).before(\''.$js_code.'\');
// jQuery("#'.$field['id'].'").append(\''.$js_code2.'\');
// alert(\''.$js_code2.'\');
update_repeater_fields();
});
});
</script>';
echo '<script>
jQuery(document).ready(function() {
jQuery(".remove-'.$c.$field['id'].'").on(\'click\', function() {
var answer = confirm("Are you sure you want to delete this field ??")
if(!answer){
event.preventDefault();
}
jQuery(".remove-'.$c.$field['id'].'").remove();
});
});
</script>';
echo '<br/><style>
.at-inline{line-height: 1 !important;}
.at-inline .at-field{border: 0px !important;}
.at-inline .at-label{margin: 0 0 1px !important;}
.at-inline .at-text{width: 70px;}
.at-inline .at-textarea{width: 100px; height: 75px;}
.at-repater-block{background-color: #FFFFFF;border: 1px solid;margin: 2px;}
</style>';
$this->show_field_end($field, $meta);
}
OK so as you've already been told, the live is deprecated.
Here's the fiddle of the solution: http://jsfiddle.net/y8JFb/2/
Basically give each new div that you dynamically create a unique ID based on your counter, then give data attribute to your remove counter which contains that ID.
Then you have your click handler:
$( document ).on( "click", ".at-re-remove", function( e ) {
$("#"+$(e.target).data("remove")).remove();
$(e.target).remove();
} );

Categories

Resources