The thing that I'd like to happen is that when the value of the status field is Paid the input field fines should be read-only.
How to achieve this?
This is my form:
This is my code:
<div class="form-group">
<label for="status" class="col-sm-3 control-label">Status</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="status" value = "Paid" name="status" readonly>
</div>
</div>
<div class="form-group">
<label for="fines" class="col-sm-3 control-label">Fines</label>
<div class="col-sm-9">
<input type="text"
class="form-control" id="fines" name="fines" required>
</div>
</div>
Javascript line of code:
<script type = "text/javascript">
$(document).ready (function(){
$('input[type=text][name=status]').change(function() {
if (this.value == "Paid") {
$("#fines").prop("readonly",true);
}
else{
$("#fines").prop("readonly",false);
}
});
});
</script>
Seeing as you're status field is set to readonly on load, I'd imagine you want to trigger a change event instantly.
$(document).ready (function(){
// setup a variable for multi-use
var $statusField = $('input[type=text][name=status]');
// watch for changes to the statusField
$statusField.change(function() {
// simpler check for paid status
$('#fines').prop('readonly', this.value === 'Paid');
});
// trigger a change on ready
$statusField.change();
});
This way you have access to trigger the change programatically but also have the ability to watch the status field. I've also cleaned up your code a little bit!
try like this
if ($(this).val() == "Paid") {
$("#fines").attr("readonly",true);
}
else{
$("#fines").attr("readonly",false);
}
I have a number of inputs like this:
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_name">
<label class="fg-label">Place Name</label>
</div>
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_address">
<label class="fg-label">Place Address</label>
</div>
I get some data from an API and then append to these inputs (so the user can edit).
This works fine. The issue is that I want to add a class to this:
<div class="fg-line">
This is simple enough if I only have one of these and one input, but since I have multiple, I need some way to check each input and if not empty add the class fg-toggled such that the line becomes:
<div class="fg-line fg-toggled">
If I had just one input, I'd do this:
if (('#place_name').value != '' || ('#place_name').value != ('#place_name').defaultValue) {
$('.fg-line').addClass('fg-toggle')
}
But I don't know how to do this without writing this out for every class (there are 30+). Is there a way to iterate this somehow? I tried checking .place-edit but since it's a class, if any of the inputs with the class are not empty then they all get the new class added.
Simply loop through each input and find the parent using .closest().
$('.placeInformation').each(function() {
var $input = $(this);
if ($input.val()) {
var $parent = $input.closest('.fg-line');
$parent.addClass('fg-toggled')
}
});
Sample plunkr
Can use filter()
$('.fg-line').has('.placeInformation').filter(function(){
return !$(this).find('.placeInformation').val()
}).addClass('fg-toggled')
Not sure what "default" should be or how it is declared. Could be set in a data attribute and add an || to above filter condition
Use each() and closest()
Try this :
$(".fg-input").each(function() {
if ($(this).val() != '') {
$(this).closest(".fg-line").addClass('fg-toggle');
}
})
.fg-toggle
{
color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_name">
<label class="fg-label">Place Name</label>
</div>
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_address">
<label class="fg-label">Place Address</label>
</div>
You could just loop through the .place-edit class and then check the values and add the class to the parents, like this:
$('.place-edit').each(function(){
if($(this).val() != '' || $(this).val() != $(this).defaultValue) {
$(this).parent().addClass('fg-toggle');
}
})
Try this.. I'm assuming they all have the same class
if (('#place_name').value != '' || ('#place_name').value != ('#place_name').defaultValue) {
$('.fg-line').each(function(){
$(this).addClass('fg-toggle')
});
}
I have a form inside ng-if directive. I want to check the form validation in controller using $valid.
<div ng-if="paymentMethod == 12">
<form name="creditForm" id="cc-form" novalidate>
<div class="form-group">
<label for="cardNumber">Card Number</label>
<input type="text" autofocus class="form-control" name="card_number" ng-minlength="16" id="cardNumber" ng-model="creditCardNumber" required>
<div class="red-text" ng-messages="creditForm.card_number.$error" ng-if="creditForm.card_number.$dirty || creditForm.$submitted">
<div ng-message="required">##global.Card_Num_Required##</div>
<div ng-message="maxlength">##global.Card_Num_MinLength##</div>
<div ng-message="minlength">##global.Card_Num_MaxLength##</div>
<div ng-message="minlength">##global.Card_Num_Numeric ##</div>
</div>
</div>
and trying to check valid form in controller
if ($scope.$parent.creditForm.$valid) {
alert('valid');
} else {
alert('not valid');
}
but the form is not accessible from controller.
The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
you can go throgh this link doc and also my answer here answer
You can use ng-show instead of ng-if if its feasible to you.
It works fine when you use auxiliary object in your controller.
In Your Controller file
$scope.page = {
creditForm:null
};
in your HTML file
<div ng-if="paymentMethod == 12">
<ng-form name="page.creditForm" id="cc-form" novalidate>
<div class="form-group">
<label for="cardNumber">Card Number</label>
<input type="text" autofocus class="form-control" name="card_number" ng-minlength="16" id="cardNumber" ng-model="creditCardNumber" required>
<div class="red-text" ng-messages="page.creditForm.card_number.$error" ng-if="page.creditForm.card_number.$dirty || page.creditForm.$submitted">
<div ng-message="required">##global.Card_Num_Required##</div>
<div ng-message="maxlength">##global.Card_Num_MinLength##</div>
<div ng-message="minlength">##global.Card_Num_MaxLength##</div>
<div ng-message="minlength">##global.Card_Num_Numeric ##</div>
</div>
</div>
</ng-form>
in this model you can saftly use ng-form inside ng-if
This happens because ngIf creates a new scope, so name="form" will register the form controller on that new scope (which is a child of the ctrl scope). You can solve this, by binding to an existing object on the target scope. (Alternatively, you can bind to the controller and use the controllerAs syntax, which is generally considered a good practice.)
This is because of how prototypal inheritance works in JavaScript.
You can find a sample plunker here
<form name="data.form" novalidate ng-if=true>
http://plnkr.co/edit/2Ip3gNPdUWWV0zK8PNJr?p=preview
$scope.$watch('creditForm.$valid', function(newVal) {
//$scope.valid = newVal;
alert('valid');
});
I have an input:
<input
type="text"
id="name"
class="form-control"
name="name"
v-model="form.name"
:disabled="validated ? '' : disabled"
/>
and in my Vue.js component, I have:
..
..
ready() {
this.form.name = this.store.name;
this.form.validated = this.store.validated;
},
..
validated being a boolean, it can be either 0 or 1, but no matter what value is stored in the database, my input is always disabled.
I need the input to be disabled if false, otherwise it should be enabled and editable.
Update:
Doing this always enables the input (no matter I have 0 or 1 in the database):
<input
type="text"
id="name"
class="form-control"
name="name"
v-model="form.name"
:disabled="validated ? '' : disabled"
/>
Doing this always disabled the input (no matter I have 0 or 1 in the database):
<input
type="text"
id="name"
class="form-control"
name="name"
v-model="form.name"
:disabled="validated ? disabled : ''"
/>
To remove the disabled prop, you should set its value to false. This needs to be the boolean value for false, not the string 'false'.
So, if the value for validated is either a 1 or a 0, then conditionally set the disabled prop based off that value. E.g.:
<input type="text" :disabled="validated == 1">
Here is an example.
var app = new Vue({
el: '#app',
data: {
disabled: 0
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button #click="disabled = (disabled + 1) % 2">Toggle Enable</button>
<input type="text" :disabled="disabled == 1">
<pre>{{ $data }}</pre>
</div>
you could have a computed property that returns a boolean dependent on whatever criteria you need.
<input type="text" :disabled=isDisabled>
then put your logic in a computed property...
computed: {
isDisabled() {
// evaluate whatever you need to determine disabled here...
return this.form.validated;
}
}
Not difficult, check this.
<button #click="disabled = !disabled">Toggle Enable</button>
<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="disabled">
jsfiddle
You can manipulate :disabled attribute in vue.js.
It will accept a boolean, if it's true, then the input gets disabled, otherwise it will be enabled...
Something like structured like below in your case for example:
<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="validated ? false : true">
Also read this below:
Conditionally Disabling Input Elements via JavaScript
Expression You can conditionally disable input elements inline
with a JavaScript expression. This compact approach provides a quick
way to apply simple conditional logic. For example, if you only needed
to check the length of the password, you may consider doing something
like this.
<h3>Change Your Password</h3>
<div class="form-group">
<label for="newPassword">Please choose a new password</label>
<input type="password" class="form-control" id="newPassword" placeholder="Password" v-model="newPassword">
</div>
<div class="form-group">
<label for="confirmPassword">Please confirm your new password</label>
<input type="password" class="form-control" id="confirmPassword" placeholder="Password" v-model="confirmPassword" v-bind:disabled="newPassword.length === 0 ? true : false">
</div>
Your disabled attribute requires a boolean value:
<input :disabled="validated" />
Notice how i've only checked if validated - This should work as 0 is falsey ...e.g
0 is considered to be false in JS (like undefined or null)
1 is in fact considered to be true
To be extra careful try:
<input :disabled="!!validated" />
This double negation turns the falsey or truthy value of 0 or 1 to false or true
don't believe me? go into your console and type !!0 or !!1 :-)
Also, to make sure your number 1 or 0 are definitely coming through as a Number and not the String '1' or '0' pre-pend the value you are checking with a + e.g <input :disabled="!!+validated"/> this turns a string of a number into a Number e.g
+1 = 1
+'1' = 1
Like David Morrow said above you could put your conditional logic into a method - this gives you more readable code - just return out of the method the condition you wish to check.
You may make a computed property and enable/disable any form type according to its value.
<template>
<button class="btn btn-default" :disabled="clickable">Click me</button>
</template>
<script>
export default{
computed: {
clickable() {
// if something
return true;
}
}
}
</script>
Try this
<div id="app">
<p>
<label for='terms'>
<input id='terms' type='checkbox' v-model='terms' /> Click me to enable
</label>
</p>
<input :disabled='isDisabled'></input>
</div>
vue js
new Vue({
el: '#app',
data: {
terms: false
},
computed: {
isDisabled: function(){
return !this.terms;
}
}
})
To toggle the input's disabled attribute was surprisingly complex. The issue for me was twofold:
(1) Remember: the input's "disabled" attribute is NOT a Boolean attribute.
The mere presence of the attribute means that the input is disabled.
However, the Vue.js creators have prepared this...
https://v2.vuejs.org/v2/guide/syntax.html#Attributes
(Thanks to #connexo for this... How to add disabled attribute in input text in vuejs?)
(2) In addition, there was a DOM timing re-rendering issue that I was having. The DOM was not updating when I tried to toggle back.
Upon certain situations, "the component will not re-render immediately. It will update in the next 'tick.'"
From Vue.js docs: https://v2.vuejs.org/v2/guide/reactivity.html
The solution was to use:
this.$nextTick(()=>{
this.disableInputBool = true
})
Fuller example workflow:
<div #click="allowInputOverwrite">
<input
type="text"
:disabled="disableInputBool">
</div>
<button #click="disallowInputOverwrite">
press me (do stuff in method, then disable input bool again)
</button>
<script>
export default {
data() {
return {
disableInputBool: true
}
},
methods: {
allowInputOverwrite(){
this.disableInputBool = false
},
disallowInputOverwrite(){
// accomplish other stuff here.
this.$nextTick(()=>{
this.disableInputBool = true
})
}
}
}
</script>
Can use this add condition.
<el-form-item :label="Amount ($)" style="width:100%" >
<template slot-scope="scoped">
<el-input-number v-model="listQuery.refAmount" :disabled="(rowData.status !== 1 ) === true" ></el-input-number>
</template>
</el-form-item>
If you use SFC and want a minimal example for this case, this would be how you can use it:
export default {
data() {
return {
disableInput: false
}
},
methods: {
toggleInput() {
this.disableInput = !this.disableInput
}
}
}
<template>
<div>
<input type="text" :disabled="disableInput">
<button #click="toggleInput">Toggle Input</button>
</div>
</template>
Clicking the button triggers the toggleInput function and simply switches the state of disableInput with this.disableInput = !this.disableInput.
This will also work
<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="!validated">
My Solution:
// App.vue Template:
<button
type="submit"
class="disabled:opacity-50 w-full px-3 py-4 text-white bg-indigo-500 rounded-md focus:bg-indigo-600 focus:outline-none"
:disabled="isButtonDisabled()"
#click="sendIdentity()"
>
<span v-if="MYVARIABLE > 0"> Add {{ MYVARIABLE }}</span>
<span v-else-if="MYVARIABLE == 0">Alternative text if you like</span>
<span v-else>Alternative text if you like</span>
</button>
Styles based on Tailwind
// App.vue Script:
(...)
methods: {
isButtonDisabled(){
return this.MYVARIABLE >= 0 ? undefined: 'disabled';
}
}
Manual:
vue v2
vue v3
If isButtonDisabled has the value of null, undefined, or false, the
disabled attribute will not even be included in the rendered
element.
Bear in mind that ES6 Sets/Maps don't appear to be reactive as far as i can tell, at time of writing.
We can disable inputs conditionally with Vue 3 by setting the disabled prop to the condition when we want to disable the input
For instance, we can write:
<template>
<input :disabled="disabled" />
<button #click="disabled = !disabled">toggle disable</button>
</template>
<script>
export default {
name: "App",
data() {
return {
disabled: false,
};
},
};
</script>
There is something newly released called inert, which is literally making it ignored by the browser.
<template>
<input
type="text"
id="name"
class="form-control"
name="name"
:inert="isItInert"
/>
</template>
<script setup>
const isItInert = true
</script>
Here is the playground for testing purposes.
Vue 3
<input
type="text"
id="name"
class="form-control"
name="name"
v-model="form.name"
:disabled="VALIDATOR == '0'"
/>
I have an application with add friend feature, in that feature, user must fill their friend's username in the textbox. this is the html code:
<div content-for="title">
<span>Add Friend</span>
</div>
<form class="form-inline" role="form">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">User ID</label>
<input type="text" class="form-control" data-ng-model="add.email" id="exampleInputEmail2" placeholder="User ID">
</div>
<button type="submit" class="btn btn-default" data-ng-click="addfriends()">Add</button>
the interface will be like this
and this is the js code:
// addfriend
$scope.add = {};
$scope.addfriends = function(){
$scope.messages = {
email : $scope.add.email,
userid : $scope.datauser['data']['_id']
};
//event add friend
socket.emit('addfriend',$scope.messages,function(callback){
if(!callback['error']){
$scope.datauser['data']['penddingrequest'].push(callback['data']);
//push pendding request to localstorage user
localStorageService.remove('user');
localStorageService.add('user', $scope.datauser);
$scope.add['email'] = '';
alert('Successfully added friend');
}else{
var msg = callback['error'];
navigator.notification.alert(msg,'','Error Report','Ok');
}
});
};
I want to change this feature little bit, I want to make this textbox showing some suggestion based on the input, like if user input 'a', the textbox will show all user id that start with 'a'. something like twitter's searchbox or instagram searchbox. these user ids is from database.
example searchbox of web instagram
my question is how to change this textbox to be autocomplete but still work like before? thanks very much
There are many ways to do this.
First is this one: You basically create Angular directive for your input.
http://jsfiddle.net/sebmade/swfjT/
Another way to do is to attach onKeyUp event to your input:
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">User ID</label>
<input type="text" class="form-control" data-ng-model="add.email" id="exampleInputEmail2" placeholder="User ID" ng-keyup="searchFriends()">
<div ng-model="searchFriendsResult" />
</div>
And then, in your controller, you create a searchFriends function that will:
Search your database
Display the result in the view.
Something like this (not a complete code):
$scope.searchFriends = function(value){
// Make Ajax call
var userRes = $resource('/user/:username', {username: '#username'});
userRes.get({username:value})
.$promise.then(function(users) {
$scope.searchFriendsResult = users;
});
};
Use Bootstrap Typeahead
<input type="text" ng-model="asyncSelected"
placeholder="Locations loaded via $http"
uib-typeahead="address for address in getLocation($viewValue)"
typeahead-loading="loadingLocations"
typeahead-no-results="noResults"
class="form-control"/>