Reset disabled input field's value - meteor

HTML:
<template name="Dep_Con">
<input disabled={{SBD_Dep_Con}} class="input" value="" type="text"/>
</template>
Js:
Template.registerHelper("SBD_Dep_Con", function() {
var returnval = "n";
const ans = Session.get('chosen')
const product = ProductList.findOne({ product: ans});
console.log("product.dep_con:" + product.department_contact)
if(product.department_contact == "N/A") {return true}
else {return false}
});
I've successfully enable / disable an inputfield (text) in html depends on another dropbox's value using the code above.
The problem is when the inputfield is filled when enabled and followed by being disabled, the value filled remains. Is there a way to reset an inputfield's value when its 'disabled' status change? Or am I looking at the wrong direction (i.e. there's a way for the form to not retrieve value from a disabled inputfield)?

You can clear the input field before disabling it using jquery. I have modified your code slightly.
<template name="Dep_Con">
<input disabled={{SBD_Dep_Con}} class="input" id="input_field" value="" type="text"/>
</template>
JS File
Template.registerHelper("SBD_Dep_Con", function() {
var returnval = "n";
const ans = Session.get('chosen');
const product = ProductList.findOne({ product: ans});
console.log("product.dep_con:" + product.department_contact)
if(product.department_contact == "N/A") {
$('#input_field').val(''); //Add this corresponding to id.
return true }
else {
return false}
});

Related

Get each checked checkbox value

I'm trying to get the value of each checked box that has been selected as true. Each time I select a checkbox it grabs the value of that checkbox instead of all the selected checkboxes.
Path: talentList.html
<fieldset>
<div class="checkbox">
<label>
<input name="specialisation" type="checkbox" value="Accounting Firm"> Accounting Firm
</label>
</div>
<div class="checkbox">
<label>
<input name="specialisation" type="checkbox" value="Accounting in Industry"> Accounting in Industry
</label>
</div>
</fieldset>
Path: talentList.js
Template.talentList.events({
'change [name="specialisation"]': function ( event, template ) {
let specialisation = event.target.value;
template.candidateListFilter.set( specialisation );
}
});
There is only one target set in the event handler so event.target.value will be a scalar instead of an array. You need to iterate over the array of checkboxes.
Template.talentList.events({
'change [name="specialisation"]': function ( event, template ) {
$.each($('[name="specialisation"]'),function(i,cb){
let specialisation = cb.value;
template.candidateListFilter.set( specialisation );
});
}
});
To be honest this seems like an odd pattern. If you want to update a document whenever a checkbox is checked/unchecked you shouldn't have to set the state of all the other checkboxes at the same time, you should be able to just poke the one you want.
Not sure if this is correct. It creates an object of all selected options.
'change [name="specialisation"]': function ( event, template ) {
$(document).ready(function(){
var specialisation = $('input[name="specialisation"]:checked').map(function(){
return $(this).val();
});
var specialisationListArray = specialisation.get();
template.candidateListFilter.set( specialisationListArray );
});
},

Meteor - checkbox is maintaining old value

I am new to Meteor :)
I have a template helper:
userRoleMap: function() {
var u = getUser();
if (u) {
var lstRoles = Meteor.roles.find({}).fetch();
var userRoles = u.roles ? u.roles : [];
_.map(lstRoles, function(r) {
_.extend(r, {
userMapped: _.contains(userRoles, r.name)
});
return r;
});
return lstRoles;
}
return [];
}
I am using this helper in my template as:
{{#each userRoleMap}}
<div class="checkbox">
<label>
<input type="checkbox" class="chkUserRole" value="{{name}}" checked="{{userMapped}}"> {{name}}
</label>
</div>
{{/each}}
I am showing the above html/template in a bootstrap-modal. I am showing this modal on click of a button (and setting user-id in a Session which I am using when calling getUser() function).
The issue is the checkbox check state is not changing based on value of "userMapped". It is getting set correctly first time, but not afterwards. The helper userRoleMap is getting called every-time I open modal, but the checkboxes are having same checked state which they had when it was opened previously (manual checks/unchecks are getting maintained).
The return value of helper method is working as expected (verified by logging it on console).
Anything I am missing here ? Something to do with _.extend() ?
The Meteor way to do this is to either return checked as an element attribute or not:
Template.registerHelper( 'checked', ( a, b ) => {
return a === b ? 'checked' : '';
});
{{#each userRoleMap}}
<div class="checkbox">
<label>
<input type="checkbox" class="chkUserRole" value="{{name}}" {{checked userMapped true}}> {{name}}
</label>
</div>
{{/each}}

semantic form validation - Validation for either one of the fields as non-empty

I have a form in which I have 2 fields, ssn and phone. I would like the user to enter anyone of the field. I'm using semantic validation, here is my code, can you please let me know how to validate the form using Semantic?
<form class="ui error form basic segment" role="form" method="POST" action="{{ url('/username/email') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="patch">
<div class="ui info message">
Please enter either SSN or phone to email you the username.
</div>
<div class="field">
<label for="ssn">SSN</label>
<div class="ui icon input">
<input type="text" class="form-control" name="ssn" value="{{ old('ssn') }}">
</div>
</div>
<div class="field">
<label for="phone">Phone</label>
<div class="ui icon input">
<input type="text" class="form-control" name="phone" value="{{ old('phone') }}">
</div>
</div>
<input type="submit" value="Email Username" class="ui primary button">
</form>
<script type="text/javascript">
$('.ui.form')
.form({
inline : true,
on: 'blur',
fields: {
username: {
identifier : 'ssn',
rules: [
{
type : 'empty',
prompt : 'Please enter a SSN'
}
]
},
}
})
;
</script>
`
Here's a little bit more elegant solution that follows Semantic UI fields identification standard.
Field could be identified not only via input[name="…"] CSS selector offered in Oniisaki's accepted answer, but also by DOM element id or data-validation attribute:
/**
* Checks whether current field value or at least one of additionally
* given fields values is not empty, neither blank string.
* #param {string} value Current field value.
* #param {string} fieldIdentifiers Comma separated field identifiers.
* #return {boolean}
*/
$.fn.form.settings.rules.allEmpty = function(value, fieldIdentifiers) {
var $form = $(this);
return !!value || fieldIdentifiers.split(',').some(function(fieldIdentifier) {
return $form.find('#' + fieldIdentifier).val() ||
$form.find('[name="' + fieldIdentifier +'"]').val() ||
$form.find('[data-validate="'+ fieldIdentifier +'"]').val();
});
};
// Using newly created custom validation rule.
// Notice how multiple fields are defined, if required.
$('.ui.form').form({
ssn: {
identifier: 'ssn',
rules: [{
// Multiple field identifiers could be defined,
// like `allEmpty[phone,email,skype]`.
type: 'allEmpty[phone]',
prompt: 'SSN or Phone (at least one field) must be filled.'
}]
}
});
I would create a Semantic UI custom validation function that accepts parameters for your purpose.
Here's the link: http://jsfiddle.net/owcfuhtq/
The code:
$(document).ready(function(){
// function to check if at least one text is not empty for a collection of elements
// text is the value of the input device
// csv is the argument as string. It's the string inside "[" and "]"
$.fn.form.settings.rules.isAllEmpty = function(text,csv){
//If the text of the field itself isn't empty, then it is valid
if (text)
return true;
var array = csv.split(','); // you're separating the string by commas
var isValid = false; // return value
$.each(array,function(index,elem){
// for each item in array, get an input element with the specified name, and check if it has any values
var element = $("input[name='"+elem+"']");
//If element is found, and it's value is not empty, then it is valid
if (element && element.val())
isValid = true;
});
return isValid;
};
var formValidationRules =
{
ssn: {
identifier: 'ssn',
rules: [{
type: "isAllEmpty[phone]",
//If you got additional fields to compare, append it inside the [] with a "," separator
//E.g. isAllEmpty[field1, field2]
prompt: 'An error occurred'
}]
}
}
$('.ui.form').form(formValidationRules);
});
If you want to include select box you can use it sth like this :
$.fn.form.settings.rules.isAllEmpty = function (text, csv) {
if (text) {
return true;
}
var array = csv.split(',');
var isValid = false;
$.each(array, function (index, elem) {
var element = $("input[name='" + elem + "']");
if (element.length == 0) {
element = $("select[name='" + elem + "']")
}
if (element && element.val()) {
isValid = true;
}
});
return isValid;
};

HOW TO CONVERT TRIPLE TAG IN METEOR 0.7.0.1 ACCORDING TO VERSION 0.8.0

I have updated meteor application to version 0.8.0 from 0.7.0.1. Every changes tried to do but not able to figure out, how to change triple tag according to new version. Referred the following link and tried to do so but still getting error.
The link following is: https://github.com/meteor/meteor/wiki/Using-Blaze
The code of .html file is: Basically this {{{done }}} part. I tried to change according to the above link as {{> done}}. But then getting error as ""Reactive HTML attributes must either have a constant name or consist of a single {{helper}} providing a dictionary of names and values. A template tag of type INCLUSION is not allowed here.
""
<template name="subscribedKeyword">
<div class="issue" >
<div class="issue-content">
<h3>
{{category}}
<input id='check' class="checktype" name="mark" type="checkbox" value="1" {{{ done}}} />Get Notifications
<input type="hidden" name="mark" value="0" />
</h3>
</div>
</div>
</template>
The corresponding .js file code is: I think that there is no need to change anything in this file. As according to the above link, changes need to be done in the html file only.
Template.subscribedKeyword.done = function () {
// alert('inside done function');
var subscribedUsersOfThisDomain= Subscribed.findOne(this._id);
var subscribedPersons = subscribedUsersOfThisDomain.categorySubscribedUsers;
// alert('before if block in done function');
if(subscribedPersons && subscribedPersons.length)
{
var j;
var ch='';
// alert('before loop in done function');
for(j= 0;j< subscribedPersons.length;j++)
{
//alert('j '+j);
//alert('person '+person[j].username);
if(subscribedPersons[j].username === Meteor.user().username)
{
ch ="checked";
// alert('value of ch that is set'+ch);
break;
}
}
if(ch=== 'checked')
{
// alert('while returning value in if block');
return 'checked="checked"';
}
else
{
// alert('while returning value in else block');
return '';
}
}
else
return '';
};
Do let me know what changed need to be done. Thanks in advance
The simplest way I can see is:
<template name="subscribedKeyword">
<div class="issue" >
<div class="issue-content">
<h3>
{{category}}
<input id='check' class="checktype" name="mark" type="checkbox" value="1" checked={{done}} />Get Notifications
<input type="hidden" name="mark" value="0" />
</h3>
</div>
</div>
</template>
Template.subscribedKeyword.done = function () {
// alert('inside done function');
var subscribedUsersOfThisDomain= Subscribed.findOne(this._id);
var subscribedPersons = subscribedUsersOfThisDomain.categorySubscribedUsers;
// alert('before if block in done function');
if(subscribedPersons && subscribedPersons.length)
{
var j;
var ch='';
// alert('before loop in done function');
for(j= 0;j< subscribedPersons.length;j++)
{
//alert('j '+j);
//alert('person '+person[j].username);
if(subscribedPersons[j].username === Meteor.user().username)
{
ch ="checked";
// alert('value of ch that is set'+ch);
break;
}
}
if(ch=== 'checked')
{
// alert('while returning value in if block');
return "checked";
}
else
{
// alert('while returning value in else block');
return null;
}
}
else
return null;
};
According to https://github.com/meteor/meteor/wiki/Using-Blaze#conditional-attributes-with-no-value-eg-checked-selected

Is it possible to change input value using CSS?

Can I change an input field value using CSS when user clicks it?
Like:
<input type=text name=username>
<input type=password name=password>
So, when the user click into this field, the text will go away and he will be able to write something.
I have tried:
input[value="Input desired username here"] {
styles...
}
Any clues?
There's no need to use css for this. You can use placeholder attribute for your input tag, it will show a default value in input boxes:
<input type="text" name="username" placeholder="Username" />
Please consider that placeholder attribute is not supported in all browsers and if you want to make it cross-browser you can write a javascript code to put a default value in your input-boxes or use this simple and quick fix:
<input type="text" name="username" onFocus="if(this.value=='Username') this.value='';" onBlur="if(this.value=='') this.value='Username';" value="Username" />
This is called a placeholder. Modern browsers will allow you to use a placeholder attribute like this:
<input type="text" name="username" placeholder="Input desired username here" />
and it will appear as you would like. Then you will need to utilize Modernizr to back port that functionality to older browsers. Something like this JavaScript will help:
$(document).ready(function () {
if(!Modernizr.input.placeholder) {
$('[placeholder]').focus(function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function () {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}).blur();
$('[placeholder]').parents('form').submit(function () {
$(this).find('[placeholder]').each(function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
})

Resources