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();
} );
Related
I am trying to make a website but I am very new to the jquery stuff and I added jquery load more comment into my website
My question is, I have a load more button that works the way I intended it to work however when all the data are loaded or when there is no comment I can't seem to get the load button to turn hidden
//jquery script
<script>
$(document).ready(function() {
var commentCount = 20;
var qidNow = "<?php echo $qid; ?>";
$("button").click(function() {
commentCount = commentCount + 20;
$("#comments").load("includes/load-comments.inc.php", {
commentNewCount: commentCount,
qid: qidNow
});
});
});
//load-comments page
<?PHP
require 'dbh.inc.php';
include 'function.inc.php';
$commentNewCount = $_POST["commentNewCount"];
$qid = $_POST["qid"];
$count = 0;
$sqlComment = "SELECT comment, commentTime, commenterId FROM comments WHERE commentOn = ?
LIMIT ?";
$stmtComment = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmtComment, $sqlComment)) {
header("Location: ../viewtopic.php?error=sqlerror4");
exit();
} else {
//bind parameter to the placeholder
mysqli_stmt_bind_param($stmtComment, "ii", $qid, $commentNewCount);
//run parameter inside database
mysqli_stmt_execute($stmtComment);
$commentData = mysqli_stmt_get_result($stmtComment);
}
if (mysqli_num_rows($commentData) > 0) {
while ($row = mysqli_fetch_assoc($commentData)) {
$count++;
echo "<div class='individualComment'>";
echo "<div class='commentCount'> คอมเม้นที่" . $count . "</div>";
echo "<div class='actualComment'>" . $row['comment'] . "</div>";
echo "<div class='commentDateBx'>" . dateReformat($row['commentTime']) . "</div>";
echo "<div class='commenterIdBx'>ID :" . $row['commenterId'] . "</div>";
echo "</div>";
}
}else {
echo "There is no comment yet";
}
I am working with a wordpress theme called X theme. My lead dev guy bailed and this function is not working. The purpose of it is to flip to the first image in that products gallery when a mousein/out event occurs. The query is looking for a proceeding post ID which is not there or doesn't meet the criteria for the query. So instead I would like it to simply get the image a better way because this doesn't work consistently.
function x_woocommerce_shop_thumbnail() {
GLOBAL $product;
$stack = x_get_stack();
$stack_thumb = 'entry-full-' . $stack;
$stack_shop_thumb = $stack_thumb;
$id = get_the_ID();
$rating = $product->get_rating_html();
woocommerce_show_product_sale_flash();
echo '<div class="entry-featured">';
echo '<a id="id'.$id.'" value="'.$id.'" href="'.get_the_permalink().'">';
echo get_the_post_thumbnail( $id , $stack_shop_thumb );
global $wpdb;
foreach($wpdb->get_results('SELECT ID FROM wp_posts WHERE post_parent = "'.$id.'" AND post_type = "attachment" ORDER BY ID DESC LIMIT 1') as $key => $row){
$file = '_wp_attached_file';
$childId = $row->ID;
global $wpdb;
$query = 'SELECT meta_value FROM wp_postmeta WHERE meta_key = "'.$file.'" AND post_id = "'.$childId.'"';
$otherImage = $wpdb->get_var($query);
if($otherImage != ''){
echo '<img id="otherImage" src="/wp-content/uploads/'.$otherImage.'"/>';
}
}
if ( ! empty( $rating ) ) {
echo '<div class="star-rating-container aggregate">' . $rating . '</div>';
}
echo '</a>';
echo "</div>";
}
The java & jQuery for the flip (is running in the footer of theme)
//Product Hover Image Switch
jQuery(document).ready(function() {
jQuery('[id^=id]').mouseover(function(){
if(jQuery(this).children('#otherImage').attr('src') != ''){
jQuery(this).fadeTo(200, 0, function(){
var source = jQuery(this).children('#otherImage').attr('src'),
original = jQuery(this).children('.wp-post-image').attr('srcset');
jQuery(this).children('.wp-post-image').attr('srcset', source);
jQuery(this).children('#otherImage').attr('src', original);
}).fadeTo(200, 1);
}
});
jQuery('[id^=id]').mouseout(function(){
if(jQuery(this).children('#otherImage').attr('src') != ''){
jQuery(this).fadeTo(200, 0, function(){
var source = jQuery(this).children('#otherImage').attr('src'),
original = jQuery(this).children('.wp-post-image').attr('srcset');
jQuery(this).children('.wp-post-image').attr('srcset', source);
jQuery(this).children('#otherImage').attr('src', original);
}).fadeTo(200, 1);
}
});
});
I have a data set of items coming from a SQL database. Those items are displayed in multiple divs like:
<?php
$url = 'DataBase';
$json_response = file_get_contents ( $url );
$json_arr = json_decode ( $json_response, true );
for($i = count ( $json_arr )-1; $i > 0; $i--) {
$json_obj = $json_arr [$i];
echo '<div id="MyDIV">';
echo $json_obj ['id'] ;
echo $json_obj ['title'];
echo $json_obj ['article'];
echo '<button id="read_more_btn">Read more</button>';
echo '</div>'
}
?>
My problem is that I cannot handle click events for EACH div, so I cannot identify which item has been clicked. I’ve been searching for a solution for quite a while, but haven’t found anything. So my question is – how can I identify the clicked item?
EDIT
I have no idea how I can dynamically assign an ID to a button
You could use a data attributes (HTML5 assumed) to attach the Id as meta data to your divs. Your PHP (note I am adding data-id attributes):
<?php
$url = 'DataBase';
$json_response = file_get_contents ( $url );
$json_arr = json_decode ( $json_response, true );
for($i = count ( $json_arr )-1; $i > 0; $i--) {
$json_obj = $json_arr [$i];
echo '<div data-id="' . $json_obj['id'] . '">';
echo $json_obj ['id'] ;
echo $json_obj ['title'];
echo $json_obj ['article'];
echo '<button id="read_more_btn">Read more</button>';
echo '</div>'
}
?>
JS - simple click handler attachment, using jQuery .data() [docs] to get data attribute:
$('div').click(function(e) {
var id = $(this).data("id");
alert(id);
});
JSFiddle Demo
How about when creating the html in the php, you echo the id inside the class.
echo '<div id="mydiv-' . $json_obj['id'] . '">';
So now in the html, it's going to look like
<div id="mydiv-1"> ... </div>
<div id="mydiv-2"> ... </div>
<div id="mydiv-3"> ... </div>
etc.
And then in Javascript, you could access them the same way you access any tag.
$('#mydiv-1').click(function(e){
console.log('a div was clicked');
console.log($(this))
});
So in order to assign listeners to each div, you could do a loop
for(var i = 1;$('#mydiv-container').children().length >= i,i++)
{
$('#mydiv-' + i).click(function(){
}
Make sure to add a container for all the divs.
Give each div a unique numeric class, so your jquery will be
$('div').click(function() {
var item_id = $(this).attr("class");
//do stuff here
});
or
$('div').click(function() {
var item_id = this.className;
//do stuff here
});
Hope someone can help.
I'm currently building a directory, and have used ACF to populate some data. I am now working toward building a filter for the options selected within one of my ACF groups, The field group is called 'Member Directory' the field I'm specifically targeting is: 'wha_service_offered'.
There are four checkbox values within this:
supplier : Supplier
manufacturer : Manufacturer
installer : Installer
consultant : Consultant
I have used checkbox as more than one option may apply to a member.
I have set up functions.php with the following:
// Filter Services
add_action('pre_get_posts', 'my_pre_get_posts');
function my_pre_get_posts( $query )
{
// validate
if( is_admin() )
{
return $query;
}
// allow the url to alter the query
// eg: http://www.website.com/members?wha_service_offered=installer
// eg: http://www.website.com/members?wha_service_offered=consultant
if( isset($_GET['wha_service_offered']) )
{
$query->set('meta_key', 'wha_service_offered');
$query->set('meta_value', $_GET['wha_service_offered']);
}
// always return
return $query;
}
And within my archive-members.php
php
<div id="search-services">
<?php
$field = get_field_object('wha_service_offered');
$values = isset($_GET['wha_service_offered']) ? explode(',', $_GET['wha_service_offered']) : array();
?>
<ul>
<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>
<li>
<input type="checkbox" value="<?php echo $choice_value; ?>" <?php if( in_array($choice_value, $values) ): ?>checked="checked"<?php endif; ?> /> <?php echo $choice_label; ?></li>
</li>
<?php endforeach; ?>
</ul>
</div>
javascript
<script type="text/javascript">
(function($) {
$('#search-services').on('change', 'input[type="checkbox"]', function(){
// vars
var $ul = $(this).closest('ul'),
vals = [];
$ul.find('input:checked').each(function(){
vals.push( $(this).val() );
});
vals = vals.join(",");
window.location.replace('<?php echo home_url('members'); ?>?wha_service_offered=' + vals);
console.log( vals );
});
})(jQuery);
</script>
When the filter is used it simply returns a blank page.
I would be grateful if anyone could point out where I have made an error.
Thanks.
--
So debug returns:
Declaration of Custom_Nav_Walker::start_el() should be compatible with
Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = Array, $id = 0) in
/Applications/MAMP/htdocs/website.com/wp-content/themes/wha/functions.php on line 169
Warning: Cannot modify header information - headers already sent by (output started at
/Applications/MAMP/htdocs/website.com/wp-content/themes/wha/functions.php:169) in
/Applications/MAMP/htdocs/website.com/wp-includes/pluggable.php on line 1179
The offending item is:
class Custom_Nav_Walker extends Walker_Nav_Menu {
function check_current($classes) {
return preg_match('/(current[-_])/', $classes);
}
function start_el(&$output, $item, $depth, $args) {
global $wp_query;
$indent = ($depth) ? str_repeat("\t", $depth) : '';
$slug = sanitize_title($item->title);
$id = apply_filters('nav_menu_item_id', 'menu-' . $slug, $item, $args);
$id = strlen($id) ? '' . esc_attr( $id ) . '' : '';
$class_names = $value = '';
$classes = empty($item->classes) ? array() : (array) $item->classes;
$classes = array_filter($classes, array(&$this, 'check_current'));
if ($custom_classes = get_post_meta($item->ID, '_menu_item_classes', true)) {
foreach ($custom_classes as $custom_class) {
$classes[] = $custom_class;
}
}
$class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
$class_names = $class_names ? ' class="' . $id . ' ' . esc_attr($class_names) . '"' : ' class="' . $id . '"';
$output .= $indent . '<li' . $class_names . '>';
$attributes = ! empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) .'"' : '';
$attributes .= ! empty($item->target) ? ' target="' . esc_attr($item->target ) .'"' : '';
$attributes .= ! empty($item->xfn) ? ' rel="' . esc_attr($item->xfn ) .'"' : '';
$attributes .= ! empty($item->url) ? ' href="' . esc_attr($item->url ) .'"' : '';
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
}
I'm not understanding why the walker nav would affect the filter?
--
Corrected line 169 error by amending the following from:
function start_el(&$output, $item, $depth, $args) {
To
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {}
I now have the following errors:
Notice: Undefined index: choices in /Applications/MAMP/htdocs/website.com/wp-content/themes/wha/archive-members.php on line 54
Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/website.com/wp-content/themes/wha/archive-members.php on line 54
Which relates to:
<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>
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;
}