0

I'am trying to get the value of the input type text in the following way:

$( document ).on( 'click', '.reset-to-default-img', function(e) {
    alert($('#image').val());
  });

When i click the button i got undefined alert message. I want to get the value. Not sure why. Here's my html:

  <p>
  <!-- Set Default Custom Image  -->
  <label for="widget-gallery-posts-widget[__i__][image]"></label>
  <input name="widget-gallery-posts-widget[__i__][image]" id="widget-gallery-posts-widget-__i__-image" class="widefat" type="text" size="36"  value="" />
  <button class="upload_image_button button button-primary" type="button">Upload Your Custom Default Image</button> <br /> <br />
          <img src="http://localhost/Gallery-Posts-Widget/wp-content/plugins/gallery-posts-widget/views/images/default-thumbnail.jpg"  id="custom-default-img" width="150" height="100" />
      </p>

I want to get the value of this input:

  <input name="<?php echo $this->get_field_name( 'image' ); ?>" id="<?php echo $this->get_field_id( 'image' ); ?>" class="widefat" type="text" size="36"  value="<?php echo esc_attr( $image ); ?>" />

Any ideas ?

5
  • 1
    where is your element with image id? Commented Aug 25, 2017 at 12:14
  • 1
    When asking a question about what's happening client-side, show us what your browser sees, not the PHP code that generates it. Ideally, provide a runnable minimal reproducible example demonstrating the problem, using Stack Snippets (the [<>] toolbar button). That will help you get good answers more quickly. Commented Aug 25, 2017 at 12:15
  • I'am generating the id in this way: id="<?php echo $this->get_field_id( 'image' ); ?>" Commented Aug 25, 2017 at 12:15
  • what does this " id="<?php echo $this->get_field_id( 'image' ); ?>" generates? Commented Aug 25, 2017 at 12:17
  • So your id is widget-gallery-posts-widget-__i__-image not image Commented Aug 25, 2017 at 12:17

2 Answers 2

1

You should use closest method in combination with find method.

$( document ).on( 'click', '.reset-to-default-img', function(e) {
  var image=$(this).closest('p').find('.widefat').val();
});
Sign up to request clarification or add additional context in comments.

Comments

1

From your php method you are getting id widget-gallery-posts-widget-__i__-image not image so change your code as below

$( document ).on( 'click', '.reset-to-default-img', function(e) {
    alert($('#widget-gallery-posts-widget-__i__-image').val());
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.