Alpine JS Toggle Input Values - javascript

I have a button that I want to toggle the value on a html input element from 0 to 1 and vice versa but I can't figure out how to do it with Alpine JS.
// input will be 0 or 1
<input type="hidden" value="0" name="status" x-ref="status">
// Toggles the status between 1 and 0
<button type="button"
x-data="{ on: false }" :class="{ 'bg-gray-200': !on, 'bg-primary-600': on }"
#click="$refs.status.value = 1"
>Toggle Status</button>
I was able to get the code above to change the input value to 1 but can't figure out how to get it to toggle it back and forth. Any ideas would mean a lot.

Here you go
<div x-data="{ status: false }">
<form>
<input type="hidden" value="0" name="status" x-model.number="status">
<span x-text="status"></span>
<button type="button" x-on:click="status = !status">
Toggle Status
</button>
</form>
</div>
The global status is held at the div element. The status is outputted inside a span using x-text.
The hidden input is bound to the status using x-model and transforming the boolean value to a number using the .number modifier.
Update
For whatever reasons this does not work anymore, I created a new sample here: https://codepen.io/codedge/pen/wvgNqee
It just defines two x-data values, one for the boolean value and one for the integer one.
<div x-data="{ status: false, num: 0 }">
<form>
<input type="hidden" value="0" name="num">
<span x-text="num"></span>
<button type="button" x-on:click="status = !status; num = (status == true ? 1 : 0)">
Toggle Status
</button>
</form>
</div>

Related

how to save toggle button state on refresh using javascript

Hey everyone I am having difficulty keeping the state of my toggle button on when i refresh the page, it is stored in localStorage correctly, but even after several attempts, I wasn't able to call the function to execute on page refresh
save.addEventListener('click', () => {
localStorage.setItem("checkbox1", checkBox1.checked);
localStorage.setItem("checkbox2", checkBox2.checked);
localStorage.setItem('timezone', timezone.selectedIndex);
}
function isChecked() {
const checkBox1 = document.getElementById('checkbox1');
if (document.getElementById('checkbox1').checked == false) {
localStorage.getItem('checkbox1');
}
}
window.onload = function() {
isChecked();
};
}
<form>
<div class="toggle-switch-1">
<p class="notification-1">Send Email Notifications</p>
<!-- toggle switch goes here -->
<label type="button" class="switch-light switch-candy">
<input id="checkbox1" type="checkbox">
<span>
<span id="off">Off</span>
<!-- <span id="on1">On</span> -->
<!-- <button onclick="check()" id="on1">On</button> -->
<span id="on1">On</span>
<a></a>
</span>
</label>
</div>
<div class="toggle-switch-2">
<p class="notification-2">Send Profile to Public</p>
<!-- toggle switch goes here -->
<label class="switch-light switch-candy" onclick="">
<input id="checkbox2" type="checkbox">
<span>
<span id="off">Off</span>
<span id="on2">On</span>
<a></a>
</span>
</label>
</div>
<select class="form-field" id="timezone">
<option disabled selected>Select Timezone</option>
<option>Eastern Standard Time (EST)</option>
<option>Pacific Standard Time (PST)</option>
<option>Central Standard Time (CST)</option>
<option>Mountain Standard Time (MST)</option>
</select>
<div class="settings-button">
<button type="button" class="button-primary" id="save">Save</button>
<button class="button-disabled" id="cancel">Cancel</button>
</div>
</form>
Im trying to save the state of the button on refresh (clicking save button) but it defaults to off when I refresh as well as the drop down list of timezones, if anyone can help clear this up, I would appreciate it Thank you!!
You are just getting the value from the local storage. But not actually assigning it to any toggle buttons. You need to assign them to make it work
function isChecked() {
document.getElementById('checkbox1').checked = localStorage.getItem('checkbox1') === 'true');
}
This is how it works:
Get the value out of local storage.
The value saved in the local storage would be of type string.
So we need to convert it to Boolean value to make it work. The === check will do that for you.
Finally assign it to the checkbox.

Button combination

I want to get input from the user in a type="number" text box.
the limitation is a number between 1994-1998.
I currently have two buttons. One "submit" button and a second ("button") button that goes to the next screen.
I want to make the 2 buttons one.
Which means that as soon as I click the "Move to Next page" button, the input is also checked.
And you can move to the next screen only with proper input.
would much rather do it only with HTML and less with JavaScript if possible.
If there is no option then it is also possible with JavaScript.
function check () {
console.log('Checked!');
}
<div>
between 1994 and 1998: <input id="section5input" type="number" name="quantity" min="1994" max="1998">
<input type="submit">
Calculate the answers!
</div>
</div>
<div class="box" id="section6">
<h1>fin!</h1>
<div class="question-text">
<input style="padding: 20px;" type="button" class="btn" onclick="check();">check!!!
</div>
</div>
From what I understand you want to go to next page only if input is correct then check this out. I have created a form and placed your html inside it. Now the submit button will only work if check function return true.
function check(){
//return true, if correct
//return false, if incorrect
return true;
}
<form action='yourURLforNextPage' method="POST">
Between 1994 and 1998:
<input id="section5input" type="number" name="quantity" min="1994" max="1998">
<input type="submit" onclick="return check();">
</form>
function check(){
let val = document.getElementById("section5input");
if((val.value!= "" && null) && (val.value> 1994 && val.value<1998) ){
//code to render to next screen
}
}

Way to know which button was clicked - Angular 5

I'm developing a quiz app have 4 options for a given question. I have already written a func to verify if the clicked option is correct answer or wrong.I'm having problem in knowing which option was selected by user and I want to style it using CSS as - If the wrong option is selected, the clicked option would turn red and the correct option would turn green in color and vice versa.
HTML :
<div *ngFor="let actiVar of activeArray ;let j = index" >
{{actiVar.QuestionID}}.{{actiVar.Question}}
<br>
<br>
<button type="button" name="s" id="one" (click)="filterAnswer(actiVar.OP[j+0]) ; getColor(actiVar.OP[j+0])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+0]}}</button>
<br>
<br>
<button type="button" name="s" id="two" (click)="filterAnswer(actiVar.OP[j+1]) ; getColor(actiVar.OP[j+1])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+1]}}</button> <br>
<br>
<button type="button" name="s" id="three" (click)="filterAnswer(actiVar.OP[j+2]) ; getColor(actiVar.OP[j+2])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+2]}}</button> <br>
<br>
<button type="button" name="s" id="four" (click)="filterAnswer(actiVar.OP[j+3]) ; getColor(actiVar.OP[j+3])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+3]}}</button>
<br>
</div>
I have set a getColor func onclick of the option selected but what it does is,if a wrong option is selected by the user,it turns all the 4 options to red and vice versa.It doesn't specifically turn the clicked option to red.
getColor(j: any) {
if (j == this.activeArray[0].isRight) {
this.buttonColor = 'green';
}
else {
this.buttonColor = 'red';
}
}
this.activeArray[0].isRight is the correct answer retrieved from JSON.
I understand that I will have to make use of individual id tag on button to know which option-button was clicked but I had no luck finding the correct logic on stackoverflow.
You can use a Template reference variables -> https://angular.io/guide/template-syntax#ref-vars
<button #buttonRef1 type="button" (click)="filterAnswer(actiVar.OP[j+0], buttonRef1)" [disabled]="permissionoptions">{{actiVar.OP[j+0]}}</button>
<button #buttonRef2 type="button" (click)="filterAnswer(actiVar.OP[j+1], buttonRef2)" [disabled]="permissionoptions">{{actiVar.OP[j+1]}}</button>
<button #buttonRef3 type="button" (click)="filterAnswer(actiVar.OP[j+2], buttonRef3)" [disabled]="permissionoptions">{{actiVar.OP[j+2]}}</button>
<button #buttonRef4 type="button" (click)="filterAnswer(actiVar.OP[j+3], buttonRef4)" [disabled]="permissionoptions">{{actiVar.OP[j+3]}}</button>
filterAnswer:
filterAnswer(answer: string, button: HTMLButtonElement) {
// Do logic here
button.style.backgroundColor = desiredColor; // example: "#f00"
}
You can use the own filterAnswer method for passing the name of the button. This aprroach its the easier way to make it.
<button type="button" name="s" id="one" (click)="filterAnswer(actiVar.OP[j+0], 'one') ; getColor(actiVar.OP[j+0])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+0]}}</button>
You have to pass $event as another argument and get id from that object
check this solution
Angular2 get clicked element id

AngularJS - Check if an input of type "number" has a value, 0 being a valid value

I am struggling to get AngularJS to work properly with a small thing that I am trying to implement.
I have an input of type number (which likely causes the issue) which is bound to a variable in my controller, and I need to disable a button if this input is empty.
Here's the code for my input and button:
<input type="number" min="0" max="20" ng-model="student.mark">
<button ng-disabled="!student">Send</button>
I tried several solutions to disable my button if the field is empty, but enable it if it has a value of 0:
<button ng-disabled="!student || !student.mark">Send</button>
<button ng-disabled="!student || !angular.isNumber(student.mark)">Send</button>
<button ng-disabled="!student || student.mark == ''">Send</button>
<button ng-disabled="!student || student.mark === ''">Send</button>
None of those seem to work. It will work properly if I have any number in my input, but either the button will be disabled if I have the value "0", or the button will stay enabled if I put a valid value and then remove it.
What makes me think that it should work is the fact that if I display the value using {{ student.mark }}, the value 0 will indeed show as "0" and an empty input will show as empty.
Thanks.
NOTE : 0 is treated as false.
In your controller define
$scope.student.mark = null;
Use condition
ng-disabled="student.mark == null && student.mark < 0"
I would suggest you to use form for that, something like that:
<form name="formName" ng-submit="someMethod(student)" autocomplete="off"
novalidate>
<input type="number" min="0" max="20"
ng-model="student.mark" placeholder="e.g. 12"
ng-required="true" />
<button type="submit" value="Send" ng-disabled="formName.$invalid || <something else here>" />
</form>
I tried a few more things and actually testing if the value is null did the trick:
<button ng-disabled="!student || student.mark === null">Send</button>

Disable input conditionally (Vue.js)

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'"
/>

Categories

Resources