Wordpress Widget add fields dynamically

Thursday, July 10, 2014

I have created a custom widget where I want to add fields dynamically with jQuery. It places the field but it just won't add the field.


Hope anyone can help me out to see what's wrong



<?php
add_action( 'widgets_init', 'custom_widget');

function custom_widget() {
register_widget( 'custom_widget_info' );
}

class custom_widget_info extends WP_Widget {


function custom_widget_info () {

$this->WP_Widget('custom_widget_info', 'custom_widget', $widget_ops ); }

public function form( $instance ) {

if ( isset( $instance[ 'titel' ]) && isset ($instance[ 'option' ])) {
$titel = $instance[ 'titel' ];
$option = $instance[ 'option' ];
}
else {
$titel = __( '', 'widget_title' );
$option = __( '', 'widget_title' );
} ?>
<p>Titel: <input name="<?php echo $this->get_field_name( 'titel' ); ?>" type="text" value="<?php echo esc_attr( $titel );?>" /></p>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;

$('#addNew').live('click', function() {
$('<p><input type="text" id="p_new" size="40" name="p_new_' + i +'" value="" placeholder="I am New" /><a href="http://ift.tt/Wao6TO" id="remNew">Remove</a> </p>').appendTo(addDiv);
i++;

return false;
});

$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});

</script>

<div id="addinput">
<p>
<input type="text" id="p_new" size="20" name="p_new" value="" placeholder="Input Value" /><a href="http://ift.tt/Wao6TO" id="addNew">Add</a>
</p>
</div>
<?php

}

function update($new_instance, $old_instance) {

$instance = $old_instance;

$instance['titel'] = ( ! empty( $new_instance['titel'] ) ) ? strip_tags( $new_instance['titel'] ) : '';

$instance['option'] = ( ! empty( $new_instance['option'] ) ) ? strip_tags( $new_instance['option'] ) : '';

return $instance;

}

function widget($args, $instance) {

extract($args);

echo '<div class="footer_item">';
echo $before_widget; //Widget starts to print information

$titel = apply_filters( 'widget_title', $instance['titel'] );

$option = empty( $instance['option'] ) ? '&nbsp;' : $instance['option'];

if ( !empty( $titel ) ) { echo $before_title . $titel . $after_title; };
echo $option;
echo $after_widget; //Widget ends printing information
echo '</div>';

} }
?>


I think it might have something to do with the load of the jQuery because it's not loades through the enque scripts, but I have no idea how to fix that. I'll do some google searches on how to fix this.


BTW if there is a debugger for JQuery that would be awesome to. Then I can see where it goes wrong. I use FireQuery in FireBug but that doesn't tells me where the script goes wrong.


Thnx M.







http://ift.tt/1rXK68J