Template helper to dynamically set div id, Meteor - javascript

I have this template event:
'click .edit_user_button': function(ev){
ev.preventDefault();
var id = this._id;
var children = $("'#" + id + "'");
console.log(children);
children.css('display', 'inline-block');
}
That I want to target this input:
<input class='user_input form-control edit_fields' id='username_field {{_id}}' type="text" name='username' placeholder="username">
but I can't get it to work. The template has scope, and this._id matches {{_id}} in the template.

Is children supposed to be the variable that targets the input ?
This is just elementary jQuery.
var input = $('input[username]').val();

This is not the meteor way to do manual DOM manipulation. If you want a class on an element to be dynamic, just write a helper function to return that class from a reactive variable (collection, session or reactiveVar). For example, for an input to be disabled reactively, do this:
<input id="chopoffthehead" disabled={{isDisabled}}/>
helper function:
isDisabled: function() {
return Session.get('isCreatureHydra');
}
This way, whenever the session variable isCreatureHydra is set to true, the input will be disabled.

Related

Changing input box also need to find check box checked or not in JS

I have input box along with checkbox in table <td> like below,
<td>
<input class="Comment" type="text" data-db="comment" data-id="{{uid}}"/>
<input type="checkbox" id="summary" title="Check to set as Summary" />
</td>
Based on check box only the content of input box will be stored in DB.
In the JS file, I tried like
var updateComment = function( eventData )
{
var target = eventData.target;
var dbColumn = $(target).attr('data-db');
var api = $('#api').val();
var newValue = $(target).val();
var rowID = $(target).attr('data-id');
var summary = $('#summary').is(':checked');
params = { "function":"updatecomments", "id": rowID, "summary": summary };
params[dbColumn] = newValue;
jQuery.post( api, params);
};
$('.Comment').change(updateComment);
But the var summary always returning false.
I tried so many ways prop('checked'),(#summary:checked).val() all are returning false only.
How to solve this problem?
Looks like you have multiple rows of checkboxes + input fields in your table. So doing $('#summary').is(':checked') will return the value of first matching element since id in a DOM should be unique.
So, modify your code like this:
<td>
<input class="Comment" type="text" data-db="comment" data-id="{{uid}}"/>
<input type="checkbox" class="summary" title="Check to set as Summary" />
</td>
And, instead of $('#summary').is(':checked'); you can write like this:
var summary = $(target).parent().find(".summary").is(':checked');
By doing this, we are making sure that we are checking the value of checkbox with the selected input field only.
Update: For listening on both the conditions i.e. when when checking checkbox first and then typing input box and when first typing input box and then checked:
Register the change event for checkbox:
// Whenever user changes any checkbox
$(".summary").change(function() {
// Trigger the "change" event in sibling input element
$(this).parent().find(".Comment").trigger("change");
});
You have missed the jQuery function --> $
$('#summary').is(':checked')
('#summary') is a string wrapped in Parentheses. $ is an alias for the jQuery function, so $('#summary') is calling jquery with the selector as a parameter.
My experience is that attr() always works.
var chk_summary = false;
var summary = $("#summary").attr('checked');
if ( summary === 'checked') {
chk_summary = true;
}
and then use value chk_summary
Change all the occurrences of
eventData
To
event
because event object has a property named target.
And you should have to know change event fires when you leave your target element. So, if checkbox is checked first then put some text in the input text and apply a blur on it, the it will produce true.
Use like this
var summary = $('#summary').prop('checked');
The prop() method gets the property value
For more details, please visit below link.
https://stackoverflow.com/a/6170016/2240375

How to pass JavaScript variable to g:remoteFunction "update" property?

I have a function in JavaScript that submits a message to a method in a Grails controller and at the same time updates div with myID id.
function messageKeyPress(field,event,messageBox) {
...
var message = $('#messageBox').val();
<g:remoteFunction action="submitMessage" params="\'message=\'+message" update="myID"/>
...
}
I use it like this:
<div id="chatMessages" class="chatMessages"></div>
<input type="text" id="messageBox" class="messageBox" name="message" onkeypress="messageKeyPress(this,event,'#messageBox');"/>
<div id="myID">
I would like that function to be reusable being able to update different divs.
I tried:
onkeypress="messageKeyPress(this,event,'#messageBox', '#myID');"
and in JavaScript:
function messageKeyPress(field,event,messageBox, myID) {
...
<g:remoteFunction action="submitMessage" params="\'message=\'+message" update="${myID}"/>
But that didn't work. My question is how to pass a JavaScript variable to Grails g:remoteFunction "update" property.
I suggest you to use jQuery instead. It is bundled by default to Grails projects. As a result, you'll get a neat separation between javascript code and gsp view logic. For instance, application.js might look like this:
(function($) {
$('.messageBox').on('keypress', function () {
...
var params = {message: $(this).val()};
var url = $(this).data('url');
var target = $(this).data('target');
$.post(url, params, function(response) {
$(target).html(response);
});
...
});
})(jQuery);
and your view file:
<input type="text" id="messageBox"
class="messageBox" name="message"
data-url="${createLink(action: 'submitMessage')}"
data-target="#myId"/>
<div id="myID"></div>
You should assign a messageBox css class to every input field you want to have this event listener. And in data-target attribute of every field you can specify a selector for all divs that should be updated.
jQuery is very easy to learn. http://api.jquery.com/
The update attribute should be set to the ID of the element to be updated, not a selector that matches this element. In other words, try this:
onkeypress="messageKeyPress(this,event,'#messageBox', 'myID');" // '#' removed from myID

How to make simplier the jquery code

Aim is to detect if after page load input values are changed.
Input fields (19 fields) for example
<input type="text" name="date_day1" id="date_day1" value=" >
<input type="text" name="date_month1" id="date_month1" value=" >
<input type="text" name="date_year1" id="date_year1" value=" >
<input type="text" name="amount1" id="amount1" value=" >
Then hidden input field like this
<input type="text" name="is_row_changed1" id="is_row_changed1" value="">
<script>
$("#date_day1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
$("#date_month1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
</script>
If in any of input fields (19 fields) value is changed, then I need to reflect it in this hidden input field (I decided to set the hidden input field value to 1).
After that ajax with php where I check if the hidden input field value is 1. If 1, then update mysql. Aim is to reduce usage of server resources.
Question
Javascript code for the hidden input field would be long. May be some way (code) to make is shorter (simplier)?
Add a row_changed class to each input then you can target them all with one call:
$(".row_changed").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
(you can also simplify it even more with QuickSilver's comment.)
You could use JQuery selectors in order to set the same "input changed" callback for all input elements declared in your HTML code:
var anyFieldChanged = false; //Global variable
function changedCallBack()
{
anyFieldChanged = true;
alert('Fields changed');
}
allInputs = $('input');
allInputs.each(function() { this.onchange = yourCallBack(); });
I don't know if it's just in your example code, but you have several elements with the same ID, which is not valid. Each ID should be unique (which is the purpose of any ID). You can either add a class to each input you want to track and select on that like Shawn said or if you want to track every input except the hidden on the page you can use
$("input:[type!=hidden]").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
Use like this.
<script>
$("#date_day1").on("change", function () {
$('#is_row_changed1').val(1);
});
$("#date_month1").on("change", function () {
$('#is_row_changed1').val(1);
});
// etc
</script>

copy form to Backbone.js model

I have a form:
<form>
<input type="text" name="email" >
<input type="text" name="phone" >
<input type="button" value="ok" />
</form>
When clicking the button, I'd like to copy the form values to a corresponding model.
I've found Backbone.ModelBinder which will automatically copy values to model whenever the values are changed, but that's not what I want, I just want to copy the values when the button is clicked.
write a custom function into the view where the form is located and bind it to the ok click event:
events: {
...
'click input[name="ok"]': 'copyFormToModel'
...
},
...
copyFormToModel: function() {
var email = $('input[name="email"]').val();
var phone = $('input[name="phone"]').val();
// Perform some sort of validation
this.model.email = email;
this.model.phone = phone;
}
This isn't the prettiest answer, but if you have just one small form in your page, then using some library or plugin might be a bit overkill. If you want to use a plugin or library, then for your case I think backbone-forms could do the trick. It features updating the model bound to the form with a method call rather than every time fields are updated.
This code may be you need:
events: {
...
'click input[value="ok"]': 'collectData2Model'
...
},
...
//suppose employee is your model
collectData2Model: function(e) {
var employee = new Employee();
var attr = {};
$('input').each(function(){
var input = $(this);
attr[input.attr('name')] = input.val();
});
employee.bind('error',function(model,error){
alert(error);
});
// set method will automatically call the model's validate method
employee.set(attr);
}

Set the name of a Jquery selector as a string in a variable

I'm quite a noob at Jquery but I'm trying to set a variable based on the name of a form element.
I.e. variable = "someForm" based on this example:
<form id="hello" name="someForm" >
First name: <input type="text" name="firstname" />
Last name: <input type="text" name="lastname" />
Email: <input type="text" name="email" />
<input type="submit" value="Subscribe" />
</form>
I'm using the following code which doesn't seem to work:
var formName = 0;
$('input').parentsUntil('form', this).focus(function() {var formName = this.name;})
if (stTime == 0) { // This ensures someone cannot start a form multiple times
var stTime = new Date();
stDelay = stTime - loTime;
alert(formName);
}
Thanks in advance!
The focus event will not bubble, see http://www.quirksmode.org/dom/events/blurfocus.html#t06
Couple of other issues:
The formName variable being assigned to inside the event handler isn't the same variable as the first line since you're re-declared it, it then exists only inside the scope of that event function.
parentsUntil will return all ancestors until the form element, not the element itself which is presumably what you want.
Your code is out of context so it's difficult to understand how formName and the timer variables should be used and where they should be declared, but this should work for the event:
$('form :input').focus(function() {
formName = $(this).parents('form').attr('name');
});
:input is a jQuery selector that matches all <input> types, along with <textarea> and <select>
The focus event will bubble, so you can just use:
$('form').focus(function() {
formName = this.name;
});
But it'd be better to store your timer when it's submitted, for example:
$('form').submit(function() {
formName = this.name;
});
Also don't use var inside the event handler, as this will create a new, local variable, not set your formName variable declared above it.
var formName = 0;
$('input').parentsUntil('form', this).focus(function() {var formName = this.name;})
This can't work. You are trying to assign to the formName variable defined in the first line, but you're redefining the variable in the second line. You are actually dealing with two different variables, one in the function scope and one in global scope.
Solution:
var formName = 0;
$('input').parentsUntil('form', this).focus(function() {formName = this.name;})
// --- no var here

Categories

Resources