3

I have a jquery code like this:

let $options = JSON.parse(data.options);
let $keys = Object.keys($options);
$keys.forEach(function (item,index, array) {
  $('#' + item ).val($options[item] );
});

I want to fill all input value in the id from the $keys with data in the $options. but it doesn't work. but if I do it manually like this it works:

      $("#title").val($options.title);
      $("#type").val($options.type);
      $("#location").val($options.location);

I'm sure that the problem is in the this code: $('#' + item ) i try so many things but seem it doesn't work. so is it any way i can fix this?

Here's my HTML:

<div class="modal fade" id="widget_modal" tabindex="-1" role="dialog" aria-labelledby="AddUserModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <form id="widget_form" class="form-horizontal" method="post" enctype="multipart/form-data" action="/admin/widgets/store">
            <input type="hidden" id="csrf" name="csrf_token">
            <input type="hidden" name="id" id="id">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">
                        Add Widget
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">
                            &times;
                        </span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group row">
                        <label class="col-lg-4 col-form-label" for="title">
                            Widget Title *
                        </label>
                        <div class="col-lg-8">
                            <input id="title" name="title" class="form-control" autofocus>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-lg-4 col-form-label" for="type">
                            Type *
                        </label>
                        <div class="col-lg-8">
                            <select class="custom-select form-control" id="type" name="type">
                                <option value="">Select Widget Type</option>
                                <option value="popular-post">Popular Post</option>
                                <option value="recent-post">Recent Post</option>
                                <option value="featured-post">Featured Post</option>
                                <option value="post-tabs">Post Tabs</option>
                                <option value="post-carousel">Post Carousel</option>
                                <option value="tags">Tags</option>
                                <option value="archive">Archive</option>
                                <option value="calender">Calendar</option>
                                <option value="blockquote">Blockquote</option>
                                <option value="mini-gallery">Mini Gallery</option>
                                <option value="list">List</option>
                                <option value="search">Search</option>
                                <option value="testimonials">Testimonial Carousel</option>
                                <option value="social-media">Social Media</option>
                                <option value="contact-us">Contact Us</option>
                                <option value="flickr">Flickr Feed</option>
                                <option value="instagram-feed">Instagram Feed</option>
                                <option value="recent-tweets">Recent Tweets</option>
                                <option value="video">Video</option>
                            </select>
                        </div>
                    </div>
                    <div id="post_div" class="form-group row">
                        <label class="col-lg-4 col-form-label" for="post_number">
                            Number of Post
                        </label>
                        <div class="col-lg-8">
                            <input id="post_number" name="post_number" class="form-control" autofocus>
                        </div>
                    </div>
                    <div id="testimonial_div" class="form-group row">
                        <label class="col-lg-4 col-form-label" for="testimonial_number">
                            Number of Testimonial
                        </label>
                        <div class="col-lg-8">
                            <input id="testimonial_number" name="testimonial_number" class="form-control" autofocus>
                        </div>
                    </div>
                    <div id="galleries_div" class="form-group row">
                        <label class="col-lg-4 col-form-label" for="image_number">
                            Number of Image
                        </label>
                        <div class="col-lg-8">
                            <input id="image_number" name="image_number" class="form-control" autofocus>
                        </div>
                    </div>
                    <div id="video_div" class="form-group row">
                        <label class="col-lg-4 col-form-label" for="video_url">
                            Video URL
                        </label>
                        <div class="col-lg-8">
                            <input id="video_url" name="video_url" class="form-control" autofocus>
                        </div>
                    </div>
                    <div id="blockquote_div">
                        <div class="form-group row">
                            <label class="col-lg-4 col-form-label" for="blockquote_author">
                                Author
                            </label>
                            <div class="col-lg-8">
                                <input id="blockquote_author" name="blockquote_author" class="form-control" autofocus>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-4 col-form-label" for="blockquote_content">
                                Quote
                            </label>
                            <div class="col-lg-8">
                                <input id="blockquote_content" name="blockquote_content" class="form-control" autofocus>
                            </div>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-lg-4 col-form-label" for="location">
                            Location *
                        </label>
                        <div class="col-lg-8">
                            <select class="custom-select form-control" id="location" name="location">
                                <option value="">Select Position</option>
                                    <option value="left">Left</option>
                                    <option value="right">Right</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        Close
                    </button>
                    <button id="submit_button" type="submit" class="btn btn-primary">
                        Save changes
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

and here's my full edit script:

 $(document).on('click', 'a.edit', function (event) {
            event.preventDefault();
            let $id = $(this).closest('tr').data('id');
            let url = "/admin/widgets/" + $id + "/edit";

            $.post(url,{ id: $id, csrf_token: $csrf }).done(function (data) {
                console.log(data.options);

                let $options = JSON.parse(data.options);

                var post = ["popular-post", "recent-post", "featured-post", "post-tabs","post-carousel"];

                if (post.includes($options.type)){
                    post_div.show();
                    testimonial_div.hide();
                    galleries_div.hide();
                    video_div.hide();
                    blockquote_div.hide();
                }else if($options.type === 'testimonials'){
                    post_div.hide();
                    testimonial_div.show();
                    galleries_div.hide();
                    video_div.hide();
                    blockquote_div.hide();
                }else if($options.type === 'mini-gallery'){
                    post_div.hide();
                    testimonial_div.hide();
                    galleries_div.show();
                    video_div.hide();
                    blockquote_div.hide();
                }else if($options.type === 'video'){
                    post_div.hide();
                    testimonial_div.hide();
                    galleries_div.hide();
                    video_div.show();
                    blockquote_div.hide();
                }else if($options.type === 'blockquote'){
                    post_div.hide();
                    testimonial_div.hide();
                    galleries_div.hide();
                    video_div.hide();
                    blockquote_div.show();
                }else{
                    post_div.hide();
                    testimonial_div.hide();
                    galleries_div.hide();
                    video_div.hide();
                    blockquote_div.hide();
                }

                page_modal.modal("show");

                let $keys = Object.keys($options);
                $keys.forEach(function (item,index, array) {
                    console.log($('#' + item));
                    $('form [name="' + item +'"]').val($options[item] );
                });

                validator.resetForm();
                $(".modal-title").text("Edit Widget");
                page_modal.find("form")[0].reset();
                $("#id").val(data.id);
                $("#csrf").val($csrf);
                submit_button.html("Update Widget");
            });
        });

Here's the screnshot that provided by console.log('item : ' + item); and console.log('$options[item] =' + $options[item] );

enter image description here

6
  • What is the value of data.options? Also check the console for errors which will help you debug the issue Commented Jan 17, 2020 at 15:22
  • @RoryMcCrossan it's a json. like this: {"title":"Posts Tab","type":"post-tabs","post_number":"2","location":"right"} widgets.js:308 {"title":"Testimonial Number","type":"testimonials","testimonial_number":"3","location":"right"} Commented Jan 17, 2020 at 15:25
  • i console for the error already. no error at all. Commented Jan 17, 2020 at 15:26
  • @Ying since the JSON object you've shared above is not an array, you can't iterate it with forEach. Try changing your data.options value into an array, even if it returns one value. Then you'll be able to perform forEach on that object. Commented Jan 17, 2020 at 15:31
  • Your posted code works. Error has to be in the data object jsfiddle.net/80wbkajy/2 Commented Jan 17, 2020 at 15:33

1 Answer 1

5

Just access them in jQuery using the name attribute of the form fields.
Assuming each option keyname is the same as the form field name of course.

By using brackets [] and then the attribute name and optionally an attribute value you can target specific elements with specific values. For more reading choose: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

+function() {
  let data = {
     options : '{"title":"Posts Tab","type":"post-tabs","post_number":"2","location":"right"}'   
  };
  let $options = JSON.parse(data.options);
  let $keys = Object.keys($options);
  $keys.forEach(function (item,index, array) {
    $('form [name="' + item +'"]').val($options[item] );
  })
}();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal fade" id="widget_modal" tabindex="-1" role="dialog" aria-labelledby="AddUserModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <form id="widget_form" class="form-horizontal" method="post" enctype="multipart/form-data" action="/admin/widgets/store">
            <input type="hidden" id="csrf" name="csrf_token">
            <input type="hidden" name="id" id="id">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">
                        Add Widget
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">
                            &times;
                        </span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group row">
                        <label class="col-lg-4 col-form-label" for="title">
                            Widget Title *
                        </label>
                        <div class="col-lg-8">
                            <input id="title" name="title" class="form-control" autofocus>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-lg-4 col-form-label" for="type">
                            Type *
                        </label>
                        <div class="col-lg-8">
                            <select class="custom-select form-control" id="type" name="type">
                                <option value="">Select Widget Type</option>
                                <option value="popular-post">Popular Post</option>
                                <option value="recent-post">Recent Post</option>
                                <option value="featured-post">Featured Post</option>
                                <option value="post-tabs">Post Tabs</option>
                                <option value="post-carousel">Post Carousel</option>
                                <option value="tags">Tags</option>
                                <option value="archive">Archive</option>
                                <option value="calender">Calendar</option>
                                <option value="blockquote">Blockquote</option>
                                <option value="mini-gallery">Mini Gallery</option>
                                <option value="list">List</option>
                                <option value="search">Search</option>
                                <option value="testimonials">Testimonial Carousel</option>
                                <option value="social-media">Social Media</option>
                                <option value="contact-us">Contact Us</option>
                                <option value="flickr">Flickr Feed</option>
                                <option value="instagram-feed">Instagram Feed</option>
                                <option value="recent-tweets">Recent Tweets</option>
                                <option value="video">Video</option>
                            </select>
                        </div>
                    </div>
                    <div id="post_div" class="form-group row">
                        <label class="col-lg-4 col-form-label" for="post_number">
                            Number of Post
                        </label>
                        <div class="col-lg-8">
                            <input id="post_number" name="post_number" class="form-control" autofocus>
                        </div>
                    </div>
                    <div id="testimonial_div" class="form-group row">
                        <label class="col-lg-4 col-form-label" for="testimonial_number">
                            Number of Testimonial
                        </label>
                        <div class="col-lg-8">
                            <input id="testimonial_number" name="testimonial_number" class="form-control" autofocus>
                        </div>
                    </div>
                    <div id="galleries_div" class="form-group row">
                        <label class="col-lg-4 col-form-label" for="image_number">
                            Number of Image
                        </label>
                        <div class="col-lg-8">
                            <input id="image_number" name="image_number" class="form-control" autofocus>
                        </div>
                    </div>
                    <div id="video_div" class="form-group row">
                        <label class="col-lg-4 col-form-label" for="video_url">
                            Video URL
                        </label>
                        <div class="col-lg-8">
                            <input id="video_url" name="video_url" class="form-control" autofocus>
                        </div>
                    </div>
                    <div id="blockquote_div">
                        <div class="form-group row">
                            <label class="col-lg-4 col-form-label" for="blockquote_author">
                                Author
                            </label>
                            <div class="col-lg-8">
                                <input id="blockquote_author" name="blockquote_author" class="form-control" autofocus>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-lg-4 col-form-label" for="blockquote_content">
                                Quote
                            </label>
                            <div class="col-lg-8">
                                <input id="blockquote_content" name="blockquote_content" class="form-control" autofocus>
                            </div>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-lg-4 col-form-label" for="location">
                            Location *
                        </label>
                        <div class="col-lg-8">
                            <select class="custom-select form-control" id="location" name="location">
                                <option value="">Select Position</option>
                                    <option value="left">Left</option>
                                    <option value="right">Right</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        Close
                    </button>
                    <button id="submit_button" type="submit" class="btn btn-primary">
                        Save changes
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

Sign up to request clarification or add additional context in comments.

8 Comments

it still doesn't work. is it because it's inside a modal or something?
but when i fill the data like this it's work $("#location").val($options.location);. Form input name is the same, but not sure why it's not filled with the data.
Your form fields don't have the attribute id="location" the # stands for id selection. Just make it like $('[name="location"]').val($options.location); if you don't want the automated iteration. For clarity you could post the contents of data.options in your question.
It has. that why this code works: $("#location").val($options.location);.
@Ying My example also works with your posted options values in your form.What I think causes the problem are these lines of code: validator.resetForm(); $(".modal-title").text("Edit Widget"); page_modal.find("form")[0].reset(); I suggest you move those before the forEach loop. Because these probably empty out your forms to defaults right after you set your values.
|

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.