last day (14 days later) » 

10:26 AM
0
A: save input values to localstorage & "bind" it with HTML element

TomalakWhile you can solve this problem in jQuery, I would recommend that you don't bother. What you describe is exactly the problem that has been solved in a multitude of MVVM frameworks. Here you have an in-memory model of your UI (i.e. the state of your application). The framework does everything ...

 
AWA
Sorry if I expressed myself in a way that I only needed jQuery. I actually need any kind of solution that would work with logged-in users and visitors even after they close the browser & come back later. I'll look into your solution and let you know.
 
@AWA I assumed that jQuery wasn't a hard requirement. That wouldn't have made sense.
 
AWA
I ran to dead-end. My form is kind of dynamic (& complex) because I add fields with ACF & code mostly uses foreach cases to decide input type, structure etc. After watching few tutorials about knockout.js, Im finding it extremly difficult to add it to my solution.. I might (or not) overcome this eventually but could you help me to understand saving/getting/removing "group of data" to localStorage using knockout.js by updating your answer?
 
My answer already contains that. It contains a "group" (i.e., an array) of values. And it shows how to turn the entire thing into JSON, which means you can save it anywhere you like, localStorage included.
Now I don't know ACF, but from the documentation it looks like it does most of the work on the server. This is unfortunate, because knockout is a client framework. It is geared towards creating HTML at run-time on the client all by itself, it does not work well with server-generated HTML. This looks like a showstopper to me. Maybe you are able to extract something of value from support.advancedcustomfields.com/forums/topic/… - the associated git repository claims to have localStorage support.
 
AWA
I've debated about scrapping ACF before, I might just do that in near future & hard-code all inputs. This leaves only few questions: 1. How to approach to different types of inputs? 2. Current solution gives search results via ajax if checkbox is checked, something is written into textbox etc. Could this be a showstopper?
Hey! Thanks for helping me out.
 
10:27 AM
@AWA No, these kinds of things work extremely well with knockout. Knockout has no own Ajax support, it's job is to turn raw data into working user interfaces (and of course user interactions back into data).
Knockout does not care where the data comes from. Could be Ajax, could be localStorage, could be hard-coded into the HTML, that's up to you.
For different types of inputs knockout supports templates: knockoutjs.com/documentation/template-binding.html
 
AWA
I'll look into this.
 
downside of course is that you would have to scrap everything and turn your working server side code inside out. not sure if you want that.
 
AWA
How about alternatives?
 
And of course, being a client-only framework that employs some advanced concepts and thought models, there is a learning curve attached to it.
 
AWA
Yes, I already scratched my head - new thing to learn again. 9 months ago I didn't even know what is browser inspector & how to open it.
 
10:33 AM
Well, alternatives of course are to stay with jQuery. It's probably possible to do what you need with it. It might end up as a bit more error-prone and complex compared to a clean MVVM solution, but I don't know scratch about ACF and therefore can only offer help if I see the actual HTML you have to deal with.
Might be useful if I delete my answer and you rewrite your question to make a more prominent mention of ACF and cross your fingers that someone comes along who has some expertise with ACF.
 
AWA
Could you give me a very basic example how it would look/work with jQuery so that I could decide what to do?
 
Not until I see a representative sample of HTML at the very least. But probably it's out of scope even for jQuery, because if ACF works anything like I imagine, the server sends all HTML pre-filled when you load the page.
And since I'm not sure if I want to take a crash course in ACF (especially as I hate PHP and don't hold WordPress in especially high regard)... :-|
 
AWA
Well, thanks for the ACF link that uses localStorage, I'll look into it and see if there's anything I could use. I think you can delete your answer then. I might change question later or even delete it.
 
So my educated guesses will be next to useless compared to someone who knows something about ACF.
 
AWA
Don't worry about that, Im not forcing you to learn that. :-D Let's stick to stuff we like.
 
10:43 AM
The question is pretty good, I would not delete it if I were you. (It's one of the few few times that a new SO user has done virtually everything right in a question)
Also it seems to cover a topic that actually nobody else seems to have covered anywhere else.
So if I delete my answer, the question will receive more attention for being unanswered.
 
AWA
Okay, I'll keep it & try to look solution, ACF or not. Not sure tho if I should continue with ACF because it mostly for people who don't feel confortable with code & do everything in panel.
 
Panel?
 
AWA
WordPress admin panel - ACF lets you to choose input types, type in IDs etc in "front-end" - by front-end I mean you don't have to look at code not even once. While I now know HTML, PHP etc pretty good, I might scrap ACF because it's just another thing that trashes admin panel.
 
Ah, I see. Yeah, that's way to high level for me. :) I like to fiddle with things at the code level, I don't like to WYSIWYG my UIs.
Well, in the end it's a "right tool for the job" thing. Determine what the actual problem is you want to solve. If it is "getting complex, structured data from the server to a client and back, while driving a complex UI in the meantime" then knockout and its cousins are your friends.
If "making people who don't like to code happy" is the problem, then, well... :)
 
AWA
Yeah, that's the case. :D Just to give you a taste what one input from my code is:
case 'estate_floors' :

?>
<div class="<?php echo $columns; ?> form-group">
<input type="number" name="<?php echo $search_parameter; ?>" id="<?php echo $search_parameter; ?>" value="<?php echo isset( $_GET[$search_parameter])?$_GET[$search_parameter]:''; ?>" placeholder="<?php echo __( $search_labels[$i], 'tt' ); ?>" min="0" class="form-control" />
</div>
<?php
break;
 
10:54 AM
holy sh*t
yeah, that's not knockout-able.
 
AWA
That's the least complicated input I found. :D
 
Knockout solves the exact same problem, only a lot differently.
You'd have to scrap and re-work all of that. And you would end up with code that probably does not integrate well with WP. (Again, I know nothing about WP, either)
wait, let me whip up some aircode that demonstrates how this would look like in knockout, just to give you an impression.
 
AWA
Well, makers of this search advertised it as industry grade search engine. They might be right. It's actually not too complicated to work with if you've read & tried to understand it form half an hour. :D I only wish I knew the way to do it.
 
<div id="searchForm" data-bind="foreach: groups">
  <div data-bind="template: {name: 'template:' + groupType}"></div>
</div>

<script type="text/html" id="template:estate_floor">
  <div class="form-group" data-bind="css: columnClass">
    <input type="number" class="form-control" data-bind="
      attr: {name: paramName, id: paramName, placeholder: paramPlaceholder, min: 0},
      value: paramValue,
    " />
  </div>
</div>
the script serves as a template for a certain kind of input field
 
AWA
I imagine jQuery would work like this:

1. User hits the button "Save search"
2. Use .val() to get each input's value
3. Somehow bind value to input
4. Somehow "group" them
5. Somehow bind "the group" to "Get inputs" button
6. Save all this mess to localStorage

And if you like to get them:
1. User hits "Get inputs" button
2. Get "the group" from localStorage
3. Find every value's input
4. Insert values
 
11:08 AM
you can define many different templates and bind them dynamically, depending on what data your UI is based on
so in effect you need no convoluted PHP/HTML mish mash on the server, you only need static HTML
and a PHP backend that is geared towards receiving and providing JSON.
There's a lot of "somehow" in there... :)
 
AWA
How this would behave with fields that have values? Dropdows for example.
Yeah, just started understanding jQuery, I might lose few "somehows" after like 30 minutes of surfing in Google & jQuery docs. :D
 
well dropdowns bind against an array of values as their source knockoutjs.com/documentation/options-binding.html
knockout then creates the actual <option> elements for you
 
AWA
You are right, that requires rewriting almost everything because my website's core/nature is basically fields & search.
 
Anyway, as for the jQuery approach...
var formState = $(".form-group").map(function () {
    var contents = {};

    $(this).find(".form-control").each(function () {
        contents[this.id] = $(this).val();
    });

    return contents;
}).toArray();

console.log( JSON.stringify(formState) );
this would give you an array of objects whose keys and values correspond to the IDs and values of every .form-control on your page, respectively.
 
AWA
Does this help that every input is with class .form-control?
 
11:17 AM
way ahead of you. ;)
Of course that code sample will not work right-away. But it's a start.
and the reverse:
var formState = JSON.parse(savedFormState);

$.each(formState, funtion (i, group) {
    $.each(group, function (formFieldId, value) {
        $("#" + formFieldId).val(value);
    });
});
all of this assumes a unique ID on every .form-control. Not sure if that's the case for your HTML.
 
AWA
Hmm, Im trying to translate this to my brain. :D (still struggling with code someone else write)

If I have 10 inputs with class of .form-control (even with different input types), it makes an array of all these inputs and also binds every input with it's value?
 
It's probably too simplistic to assume that.
 
AWA
Yes, every input has unique ID.
 
it binds nothing, it makes an array of them.
the outcome of the first code sample would look something like this:
[
  {input11: "value 1.1", input12: "value 1.2"},
  {input21: "value 2.1", input22: "value 2.2"},
  {input31: "value 3.1", input32: "value 3.2"},
  {input41: "value 4.1", input42: "value 4.2"}
]
of course if every input invariably has a unique ID, then we would not even need to make an array of objects, a single object would be enough.
 
AWA
Didn't lie, every input has it's own ID.
 
11:29 AM
and the "binding", as you call it, would happen when we restore the data to the form (catch 22 is of course that the empty form must exist with all inputs and the exact same IDs before we load the data - I don't know if that's the case for you).
 
AWA
Don't mind me, didn't learned this at school & Im not very familiar with "official" names. :D
 
that's all right, that's only me trying to make sure that we talk about the same thing
but if that is the case, i.e. if the user loads the page and the server sends an empty form for them to fill in, with all necessary IDs in place - then what you want to do becomes very easy in jQuery.
 
AWA
Answer to your statement is yes, all inputs exist & are the same in any case. How about hidden inputs?
 
I thought all the time that we are dealing with a dynamic form that contains all kinds of sections that can be duplicated or deleted and that you would need to save that state as well
makes no difference if the input is hidden or not.
 
AWA
Sorry if I make it look like that. Situation: Search form that is not dynamic. There are no buttons for add or delete inputs. All inputs are the same for every user & doesn't change in process.
 
11:35 AM
well, that's good news then.
 
AWA
Some inputs are "empty", some are with values (taxonomies) like dropdowns & there's also a date input (I use bootstrap datepicker).
So, previously written jQuery is perfectly valid in my case?
 
Yes.
 
AWA
I think I can use this information to invent something workable.

Then only big question mark is that how to have more than once saved values? Like you see in my perfect example image, there are 5 "slots" where you can save 5 different searches.
 
function getFormState()
    var formState = {};

    $(".form-control, :input:hidden").each(function () {
        formState[this.id] = $(this).val();
    });
    return formState;
}

function setFormState(formState) {
    $.each(formState, function (key, value) {
        var $target = $("#" + key);
        if ( $target.is(".ui-datepicker) ) {
            // set datepicker value...
        } else if ( $target.is(":text") ) {
            $target.val(value);
        } // etc
    });
}
this would get all form field values into an object
and an object back into the form again
converting the object to JSON and storing it in localStorage, as well as restoring it on page load would be your job
also error handling would be your job, for example when the localStorage object is not in the right format, or when a date is out of range, all kind of things could go wrong
 
AWA
11:51 AM
Yes, especially when I have over 30 different inputs.
 
right. But the approach itself works with 3 or 3000 inputs, just as long as they have unique IDs
 
AWA
JSON.stringify() - converting to JSON
jQuery.parseJSON() - restoring object

localStorage.setItem('yourKeyName', 'JSON here'); - to localStorage
localStorage.getItem('yourKeyName'); - from localStorage

Im thinking that I could use keys to identify 5 different searches.

$('.search-one').click(function() {
$('.search-one').click(function() {
if(localStorage.getItem("first-search") != null) {

}
}
Ough, why do I even write code here if I have editor..
 
don't forget to indent your code here with four spaces so it prints nicely
shortcut CTRL+K
JSON.stringify() / JSON.parse()
you could use keys to identify 5 different searches.
 
AWA
12:10 PM
Thanks. I guess the easiest way would be to set localStorage key on "Save" button press to first unactive button's ID, then it's also easy to retrieve correct localStorage if that specific search button is pressed.
 
Sounds like a plan.
 
12:35 PM
@AWA Tell me how it goes and if I should edit my answer into the what came out of this discussion here, or if I should delete it. (this chat room goes away when I delete my answer)
 
AWA
Edit it what came out of this. It seems to be working - Im currently working on it and atleast console.log showed correct values. Is there a chance that chat room closes? I might want to copy-paste few things to my PC before it does.
 
not when I don't delete my answer
it will get locked at some point when there was no activity for a few days, but it will continue to sit here
 
AWA
Do you delete your answer? I'll let you know in comments how it works out.
But it started out well.
 
no, I'll replace it with a working sample that basically does we've worked out here.
hot tip for your next jQuery question: do mention your server side environment and do include meaningful sample HTML, as it is seen by the browser.
 
AWA
Thank you. Im not familiar with some things - that's why some of my questions might not be the perfect but I'll try, I really do.
Last question: is there a way to narrow down the search to specific element? (e.g. search all .form-controls IN div class="container")

There are few other .form-controls on page I don't want.
Sorry, I think I might worked for too long.. brain is getting tired.

".container.form-control" to selector seems like a reasonable idea.
Still having issue that if I change value (type in something to input), it still outputs initial value from page load..
 
1:00 PM
Yes, that's possible. Look at how jQuery selectors work (they work very similarly to CSS selectors, but are more powerful in comparison).
"all .form-controls IN div class="container" is so easy that you will figure it out yourself in a few minutes.
note that ".container.form-control" is not the same as ".container .form-control".
 
AWA
I should get some sleep but this thing don't let me. :)

I wonder if it's possible to get CURRENT value of input? Value parameter doesn't change before page reloads.
 
I think you should get some sleep instead.
 
AWA
Im too hooked up, I couldn't sleep.
That's so weird. This fiddle jsfiddle.net/6Gadm/4 shows updated value when button is pressed but mine only shows the value on page load, even if it's changed.
 
Well, it's your funeral. ;) Code written tired is usually best thrown away on the next morning.
 
AWA
It's a start. :D
I just need something that kind of works so that I could use my energy to make it perfect tomorrow.
 
1:12 PM
As you can see, .val() grabs the current value of the input element in question.
If it does not do that for your "real" page, you are not looking at the right input element, plain and simple.
Double check that your IDs are really unique in the HTML source.
 
AWA
My bad. I've also got an icon in footer that opens mini-search modal & you are right, IDs are same - didn't know that. Always though there can't be 2 IDs..
At least saving works. ;) I'll change the IDs of other search form tomorrow.
 
I guess that's it, then.
 
AWA
Thank you! There were times when I thought I should forget it but now there's light at the end of tunnel.
 
1:29 PM
That's good to hear. Check out my modified answer, as well.
 
 
2 hours later…
AWA
3:07 PM
Im almost there, just minor problem at the end.
@Tomalak Let me know if you're here.
 
4:09 PM
@AWA If it's just a minor problem, you can figure it out on your own, I'm sure. ;)
 
AWA
It wasn't so minor before. I've never done anything like this & there we're nothing online about my problem. But I managed to put the puzzle pieces together & after trying-failing thousand times it's working now. :)
Was* Time to sleep now!
 

last day (14 days later) »