Is it possible to do 2 way data-binding on meteor - meteor

I am new to meteor.. I am looking for a way to perform 2 way databinding between a model/collection to template. It is my understanding that when the contents of a collection change, the template reacts to this change and updates itself. However, how to automatically the collection when a user types, for example, in a textbox?

You could use the template events binding
e.g if you have
html
<template name="home">
<input type="text" name="text" value="{{text}}"/>
</template>
client js
Template.home.text = function() {
return MyCollection.findOne({_id:"1"}).text;
}
Template.home.events({
'change input[name=text]':function(event,context) {
MyCollection.update(_id, {$set:{text:event.target.value}});
}
});
So that will make it update as soon as the textbox loses focus/enter is pressed/etc
If you want to use the submit button & for something a bit cooler have a look at the controllers branch of meteor on github for the
easy forms system currently in the works to easen this up a bit.

Related

How to focus an input on subscriptionsReady using FlowRouter in Meteor

I'm currently getting used to using FlowRouter after a while using Iron Router and trying to set up some best practices. I'm subscribing to my collection at a template level.
Previously I've waited for a template to render using onRendered and then targeted my input field and applied focus(), however I am now trying to only show my template in Blaze when the subscriptions are ready using the following (please excuse the Jade but I think it's pretty clear in this case)
template(name="subjectNew")
unless Template.subscriptionsReady
+spinner
else
form
input(type="text" name="name")
So the basic idea is that until the subscriptions are ready the spinner shows. The issue I'm having is that now even when the template renders, the focus won't apply. I've tried various methods of wrapping it in an autorun call but not sure the best way of trying to target the first field when combined with this approach?
Template.subjectNew.onRendered(function() {
console.log('rendered');
$('input').first().focus();
});
Is it possible?
Many thanks for any ideas.
Your subjectNew is considered rendered even when it is only showing the spinner. Just stick your:
form
input(type="text" name="name")
Into a separate template and then attach your focus code to the onRendered handler of that other template.
template(name="subjectNew")
unless Template.subscriptionsReady
+spinner
else
+myForm
template(name="myForm")
form
input(type="text" name="name")
js:
Template.myForm.onRendered(function(){
$('input').focus()
});
I think using an autorun would be a good approach but then you would have to employ Tracker.afterFlush() to wait to set the focus after the form is rendered.
Something like:
Template.subjectNew.onRendered(function() {
this.autorun(() => {
if (this.subscriptionsReady()) {
Tracker.afterFlush(() => $('input').first().focus());
}
});
});

Is it ok to user multiple submit buttons is asp.net web pages

#{
var db = Database.Open("DataExample");
var sql = "Select * from FenixProducts";
if(IsPost){
if(Request["button"].Equals("Filter1")){
sql = "Select * from FenixProducts where TorchLumens > 1200";
}
if(Request["button"].Equals("Filter2")){
sql = "Select * from FenixProducts where TorchLumens < 200";
}
}
var productResult = db.Query(sql);
}
#foreach(var x in productResult){
#ProductHelpers.fenixTorchGenerateProcuct(x.TorchName, x.TorchLumens, x.TorchRange, x.TorchPrice)
}
<form action="" method="post" style=" clear: left;">
<button type="submit" name="button" value="Filter1">Filter1</button>
<button type="submit" name="button" value="Filter2">Filter2</button>
</form>
Is it a good practise? I plan to use multiple buttons in the same form and filter products based on the button clicked.
It is not a bad practice to use multiple buttons. There is no point to restrict that, however, you should separate your backend code from your view and you should make sure your pages are easy to use.
In your case two buttons could resolve your problem, but if you need to enable many possible customizing scenarios, then a search could be customized by select and input tags as well.
it is ok for a demo page, or you do it for fun.
but it's not a good idea to do that in a real project. that will become a nightmare for you to maintain that project.
you are mixing busniess logic, database access in the view.
what if you want a third filter in future? add one more button?
you can use a radio button or dropdownlist as the input of that form and post that input back to your handler, handle the logic base on the value of the input.
then move your handler into another file, post the form to that file, to seprate the responsibility.
if you are working on a webform project, write the logic in your .cs file and if you are working on a mvc project, write the logic in your controller

How to update UI based on FileUpload control change

I have an FileUpload control on a page. I need to change some values based on the filename once a user selects a file. I'm trying to find out the best way to do this. The only option I can see is listening in JavaScript for a change event and then either..
a) forcing a post back and updating the form
b) updating things on the client side using JavaScript and some back end async calls.
Is there any other options and if not which of this is preferable?
Thanks
If you are using jquery, you can attach a function to the change of the file upload.
Consider the following example html:
<input id="myFile" type="file">
<p><label id="myLabel">No File</label></p>
And let's say we wanted to update the label with the name of the selected file. To do that, we'd use the following javascript:
$(document).ready(function () {
$("#myFile").change(function () {
$("#myLabel").html($(this).val());
});
});
Here's a fiddle in action: http://jsfiddle.net/ffkuL/1/
If you aren't using jquery, you can do something like this:
var upload = document.getElementById("myFile");
upload.onchange = function (e) {
var label = document.getElementById("myLabel");
label.innerHTML = this.value;
};
And here's a fiddle for that one: http://jsfiddle.net/8PYwK/
(Honestly, though, I find that it's far simpler in the long run to use jquery in the long run when dealing with ASP.NET controls.)
Obviously, the label changing in my samples are just examples. Following that pattern, though, you can make whatever changes you need to on the client side (rather than needing to post back).

I am trying to refresh a sidebar.php in wordpress on a form submit

I am trying to refresh a sidebar.php in wordpress on a form submit (that is in a widget on the sidebar.php).
I have video on the page and if the entire page refreshes, the video has to play from the beginning.
I need a solution to simply refresh the sidebar.php when someone submits the form ... I am not an expert php programmer so simple is best!
btw. I am using formidable plugin for the form.
thanks in advance!
Sounds like a job for ajax!
Now, you could do it from scratch, but that would be unnecessarily painful. Instead, I recommend including jquery into your page by adding this into your header
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
(which uses the latest version, which is hosted on google)
Now that you have jquery loaded, there are many easy ways to submit your data without interrupting the flow of things. Here is how I would do it (I am assuming that you are using method="post"):
Change your <input type="submit" > into a <button>, so clicking on it doesn't trigger the built-in form submit (which would interrupt your video).
Set the id attribute of your button to something so that you can reference it easily like <button id="mysubmitbutton">. (While you are at it, give id attributes to all the form fields you care about if you have not already so that you can reference them easily as well, like <input type="text" name="firstName" id="firstName"> instead of just <input type="text" name="firstName">)
Inside the <head> portion of your website, add some code that looks like something like this:
<script type="text/javascript">
//makes it so that it goes after the html document is ready for it
$(document).ready(function() {
//this ties a onclick event to your button you made
$("#mysubmitbutton").click(function(){
//when the button is clicked, it will asychronously post to where you want it to
$.post("urlthatwasinyouractionequalsattribute.php",
{
//put all your post variables here, referencing the ids you made earlier
firstName: $("#firstName").val(),
time: $("#time").val() //be sure you don't have a trailing comma on the last one
},
function(data) {
//data is whatever the other website sends back. do whatever you want here...
alert("Result: " + data);
});
});
});
</script>
Fire it up and it should work. Obviously, you will need to change the values so that it matches your form, etc.
Hope that helps! Please mark as answer if it did.

What is the best way to allow for multiple buttons on an ASP.NET MVC form?

I have a feeling I'm being too "webforms" with this, but I'll ask anyway. I have a form in an ASP.NET MVC project that has some input fields and two buttons on it. One button is used to 'filter' one of the list boxes. The other is used to submit the form. My view looks something like this:
<%using (Html.BeginForm())
{%>
<%=Html.TextBox("SearchItems") %>
<input type="submit" name="Command" value="Find" />
<%=Html.ListBox("SelectedItems", new MultiSelectList(model.AvailableItems,"Id", "Name", model.SelectedItems))%>
//Some other form fields.
<input type="submit" name="Command" value="Send" />
<%} %>
My action looks something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index([Bind(Prefix = "")]SendMessageRequest model)
{
if (model.Command == "Find")
return SearchItems(model);
if (model.Command == "Send")
return Send(model);
throw new Exception("Invalid command.");
}
This works- the controller chooses the correct action based on the button that was clicked. However, it is not ideal, because the input button's value is also the displayed text. If I wanted to translate this app, then the action would break. To get around this, I can use a <button> element, which allows the text and value to be different. However, this app is for Pocket IE, and apparently Pocket IE handles these differently - it submits both values for Command, which breaks the action.
Since this is for Pocket IE, I'm also pretty limited in terms of what I can do with JavaScript. Ajax is out, but I could possibly set a hidden field from the buttons' onClick.
So, my question is what's the best way to allow for a single form with multiple buttons on an MVC view? Alternatively, should I be breaking up my view into multiple forms somehow?
I would suggest multiple forms with 2 different actions. This I think is also more testable:
(c => c.Search(), FormMethod.Get);
{ %>
Find
(c => c.Send(), FormMethod.Post);
{ %>
Send
or something like that. Then in the controller you have 2 corresponding actions. This means the responsibility is broken out. With MVC you can have multiple forms, unlike in Webforms. So you can break free!
No need for a hidden field, you can set the form's action on the button's click event.
The javascript (in jQuery) is something like:
$("#myForm").attr("action", "mvcaction");
$("#myForm").submit();
You can wrap that up in a standard function that takes a parameter which is the action for example. We're using this for standard menu items in a menu form object, it works quite well.
EDIT: Not sure if Pocket PC handles JQuery at all, though if it doesn't it should be possible to do the above in regular javascript.
Here's a very good article describing all the alternatives for multiple buttons forms: http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx
Personally I agree with Odd, the jQuery onclick actions seems the best option.
The app I am creating needs to be massively ajax'd up, however the multiple forms problem hit as well.
We got round it using the $.post() method from the jQuery library.
$("#update").click(function() {
$.post("/Register", { name: $("#firstName").val(),
surname: $("#surname").val(),
username: $("#email").val(),
accountName: $("#accountName").val(),
password: $("#password").val()
},
function(data) {
alert(data);
});
});
And the cancel button sent fewer values back.
$("#cancel").click(function() {
$.post("/Cancel", { username: $("#email").val(),
password: $("#password").val()
},
function(data) {
alert(data);
});
});
Ok again its reliant on javascript being enabled, but if you are going to disable javascript you best not use the internet (and my app 'cause it will be heavy on the js).

Resources