I am new to Javascript.
I have 2 buttons on and off.
Have to set the variable flag to 1 when it is on and set the variable to 0 when it is off.
If flag==1, on button should be displayed; when flag==0, Off button should be displayed.
HTML:
<button class="on">ON</button>
<button class="off">OFF</button>
I tried the below code, but it did not work.
JS:
var flag = 0;
if (flag == 0) {
$('.on').hide();
} else {
$('.off').hide();
}
Could anyone please help?
Thanks
var flag = false;
$(function() {
$('.on').click(e => {
$('.on').hide();
$('.off').show();
flag = true;
console.log({
flag
});
});
$('.off').click(e => {
flag = false;
$('.off').hide();
$('.on').show();
console.log({
flag
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="on">ON </button>
<button class="off">OFF </button>
You could make this as simple as having a function to configure both buttons which also takes a callback to be called every time the state changes.
Something like:
function configureToggle(onButton, offButton, initialState, onChange){
if(initialState == 0)
offButton.hide();
else onButton.hide();
onButton.click(() => {
onButton.hide();
offButton.show();
onChange(1);
})
offButton.click(() => {
onButton.show();
offButton.hide();
onChange(0);
})
}
configureToggle($(".on"),$(".off"), 0, value => {
console.log("Current state is ",value);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="on" > ON </button>
<button class="off"> OFF </button>
here is a solution for that
$('button').on('click',function(){
$('button').toggleClass('hide')
});
.hide{
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="on"> on </button>
<button id="off" class="hide" > off </button>
Related
I used the code below to increment and decrement an input field by 1. I need to disable the minus (-) button by default. If the initial value is 5, the user should not decrease the value less than 5. If they go to 6, enable the minus button to decrease. But, they should not decrease less than 5.
The code works sometimes. Randomly, the button is disabled and isn’t able to decrease even from 10 to 9, 8, 7.
Please let me know whether this solution will work or need to change any other.
let $noofpaxinput = $('#txtnoofpax');
$noofpaxinput.val(5);
let intialvalue = $noofpaxinput.val();
$('.noofpax').click(function() {
if ($(this).hasClass('increasepax')) {
$noofpaxinput.val(parseInt($noofpaxinput.val()) + 1);
$('.decreasepax').prop('disabled', false);
} else if ($noofpaxinput.val() >= intialvalue) {
let getPaxVal = $noofpaxinput.val(parseInt($noofpaxinput.val()) - 1);
if (getPaxVal <= intialvalue) {
$('.decreasepax').prop('disabled', true);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fee-amount">
<button type="button" disabled="disabled" class="noofpax decreasepax">-</button>
<input id="txtnoofpax" type="text" value="5">
<button type="button" class="noofpax increasepax">+</button>
</div>
You could listen to input change and detect whether to disable the decrease button
Remember to parseInt because your input type is text. If you not parse it, '10' < '5' will return true
let $noofpaxinput = $("#txtnoofpax")
$noofpaxinput.val(5)
let intialvalue = $noofpaxinput.val()
$noofpaxinput.on('change', function () {
if (Number($noofpaxinput.val()) <= Number(intialvalue)) {
$(".decreasepax").prop("disabled", true)
} else {
$(".decreasepax").prop("disabled", false)
}
})
$(".noofpax").click(function () {
if ($(this).hasClass("increasepax")) {
$noofpaxinput.val(Number($noofpaxinput.val()) + 1).trigger("change")
}
if ($(this).hasClass("decreasepax")) {
$noofpaxinput.val(Number($noofpaxinput.val()) - 1).trigger("change")
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fee-amount">
<button type="button" disabled="disabled" class="noofpax decreasepax">-</button>
<input id="txtnoofpax" type="text" value="5">
<button type="button" class="noofpax increasepax">+</button>
</div>
You need to check the value of .txtnoofpax inside the click function event to get it everytime the user click.
And then you need to use a else in your last condition.
var noofpaxinput = $('#txtnoofpax'), noofpaxinputInitVal = $(noofpaxinput).val();
$(noofpaxinput).on("input", function(){
checkNoofpaxinput($(noofpaxinput).val(), noofpaxinputInitVal);
});
$('.noofpax').click(function(){
var txtnoofpaxValue = $(noofpaxinput).val();
if ($(this).hasClass('increasepax')){
$(noofpaxinput).val(parseInt(txtnoofpaxValue)+1);
} else if ($(this).hasClass('decreasepax')){
$(noofpaxinput).val(parseInt(txtnoofpaxValue)-1);
}
checkNoofpaxinput($(noofpaxinput).val(), noofpaxinputInitVal);
});
function checkNoofpaxinput(fromValue, Tovalue) {
if (parseInt(fromValue) <= parseInt(Tovalue)) {
$('.decreasepax').prop('disabled', true);
} else {
$('.decreasepax').prop('disabled', false);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<div class="fee-amount">
<button type="button" disabled="disabled" class="noofpax decreasepax">-</button>
<input id="txtnoofpax" type="text" value="5">
<button type="button" class="noofpax increasepax">+</button>
</div>
I want that until the Copy List To Below get clicked I want to disable to Save button.
Currently this is the Copy List To Below button
<button type="button" className={classes["copy-btn"] + " btn-cancel mt-3"} onClick={(event) => this.copyData(event)}>Copy List To Below {_.size(this.state.protestList) > 1 ? _.size(this.state.protestList) + " Groups" : 'Group'} </button>
And this is my Save button
<button type="submit" className={classes["save-btn"] + " btn-save"} onClick={(event) => this.saveData(event)}>Save</button>
And below is the respected functions
saveDate = (event, data) => {
if(event) {
//Do something
}
else {
//Return Error
}
}
copyData = (event, data) => {
if(event) {
//Do something
}
else {
//Return Error
}
}
As I said only if Copy is done then only save button should be able get clicked
Give two ids and add click event and toggle button disable property like this. Make it simple. Your buttons has unnecessary attributes, please remove those.
CORE JAVASCRIPT
<button type="button" id="coptBtn" class ="btn-cancel mt-3" >Copy List To Below</button>
<button id="saveBtn" type="submit" class="" >Save</button>
var coptBtn = document.getElementById('coptBtn');
var saveBtn = document.getElementById('saveBtn');
saveBtn.disabled = true;
coptBtn.addEventListener('click', (evt) => {
saveBtn.disabled = false;
});
REACT JS
var App = React.createClass({
getInitialState() {
return {isDisable: false}
},
handleClick(e) {
this.setState({isDisable: true})
},
render() {
return <div>
<button type="button" onClick={this.handleClick} >Copy List To Below</button>
<button type="button" disabled={!this.state.isDisable}>Save</button>
</div>
}
});
Try this code..
copyData() {
//your existing code
this.setState({copied: true})
}
<button type="submit" disable={!this.state.copied} className={classes["save-btn"] + " btn-save"} onClick={(event) => this.saveData(event)}>Save</button>
I want to hide my submit button without mouse click & show message.
when main balance less then form input withdraw amount.
Then automatic hide submit button and show message that insufficient balance
Html Code:
<div id="message"></div>
<div class="form-group">
<center><button type="submit" id="withdraw_button" class="btn btn-info btn-rounded w-md waves-effect waves-light m-b-5">Withdraw</button></center>
</div>
Jquery Code:
<script type="text/javascript">
$(document).ready(function(){
var main_balance = $("#main_balance").val();
$('#withdraw_amount').blur(function(){
var input_amount = $(this).val();
if (input_amount.length != 0) {
if (input_amount > main_balance) {
// When insinuation balance then hide button automatic
$('#withdraw_button').hidden();
// Show message
// how can i see it
}
}
});
});
How can solve this problem. current i use laravel framework.
I think you looking for that.
i basically set your main balance to 20 and if input greater than 20, than submit button will hide. also you can add message in if or else condition as per your requeirements.
$(document).ready(function(){
var main_balance = 20;
$('#withdraw_amount').keyup(function(){
var input_amount = $(this).val();
if (input_amount.length != 0) {
if (input_amount > main_balance) {
// When insinuation balance then hide button automatic
$('#withdraw_button').hide();
// Show message
$('#message').html('insufficient balance');
// how can i see it
} else {
$('#withdraw_button').show();
$('#message').html('');
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="message"></div>
<div class="form-group">
<input type="number" name="withdraw_amount" id="withdraw_amount">
<center><button type="submit" id="withdraw_button" class="btn btn-info btn-rounded w-md waves-effect waves-light m-b-5">Withdraw</button></center>
</div>
try adding else in your function:
if (input_amount > main_balance) {
//When insinuation balance then hide button automatic
$('#withdraw_button').hide();
alert('Insufficient balance!');
}else{
$('#withdraw_button').show();
}
Please update your jquery
<script type="text/javascript">
$(document).ready(function(){
var main_balance = $("#main_balance").val();
$('#withdraw_amount').blur(function(){
var input_amount = $(this).val();
if (input_amount.length != 0) {
if (input_amount > main_balance) {
// When insinuation balance then hide button automatic
$('#withdraw_button').hide();
// Show message
// how can i see it
} else {
$('#withdraw_button').show();
}
}
});
$('body').click(function(){
$('#withdraw_button').hide();
});
});
Bind multiple events to avoid click outside to fire event.
$("#withdraw_amount").bind("keyup change", function(e)
here is your modified code
$(document).ready(function(){
var main_balance = Number($("#main_balance").val());
//$('#withdraw_amount').keyup(function(){
$("#withdraw_amount").bind("keyup change", function(e) {
var input_amount = Number($(this).val());
if (input_amount.length != 0) {
if (input_amount > main_balance) {
// When insinuation balance then hide button automatic
$('#withdraw_button').hide();
$('#message').text("insufficient balance");
// Show message
// how can i see it
} else {
$('#message').text("");
$('#withdraw_button').show();
}
}
});
});
demo
My question is different and didn't get any solution.Question is when i click on active modal opens for 1 sec and then page refresh and change status active to inactive.
I want to keep modal open when i click on active then after hitting send from modal page reloads and change status to inactive.
My Modal:
<div class="modal fade text-left" id="small" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel19"
aria-hidden="true">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<form method="post">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<div class="modal-header">
<h4 class="modal-title" id="heading-name">Reason</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label class="receiver" for="to">To: </label>
</div>
<div class="form-group">
<textarea type="text" class="form-control" name="message" id="message"></textarea>
</div>
</div>
<input type="hidden" name="message_value" id="message_value">
<div class="modal-footer">
<button type="button" class="btn grey btn-outline-secondary" data-dismiss="modal">
Close
</button>
<button type="submit" class="btn btn-outline-primary" data-target="myModalLabel19"
data-toggle="modal">Send
</button>
</div>
</form>
</div>
</div>
</div>
For Loop:
for (var i = 0; i < response.data.length; i++) {
if (response.data[i]['status'] == 1) {
operatorStatus = "Active";
statusColor = "<button class='btn btn-primary' onclick='fn_statusUpdate("+response.data[i]['id']+",0);reason("+response.data[i]['id']+")'>Active</button>";
} else {
operatorStatus = "Active";
statusColor = "<button class='btn btn-danger' onclick='fn_statusUpdate("+response.data[i]['id']+",1)'>Inactive</button>";
}
}
Function:
function reason(id) {
$('.receiver').text('To: ' + id);
$('#message_value').val(id);
console.log((JSON.stringify(id)));
$('#small').modal('show');
}
Pseudo Code
Okay, rather than re-writing the code for you, I'm just gonna write some pseudo code for you, simply because I'm not sure about how it all works or how it all ties together, etc...
So, you want to be able to do some stuff and remember the values prior to the page being refreshed, as far as I'm aware. So, I'd do something like this...
On load
...
if (sessionStorage.getItem('key') != null) {
// Show modal or set state to active or whatever...
} else {
// Hide modal and set state to inactive or whatever...
}
On State Change
....
if (state.active) {
// Do something...
} else {
// Do something else...
}
Explanation
I think you get where I'm going with this? If not it's really quite simple, if you have some value stored in session storage, then you can set the state to active and show the modal. I mean I think that's what you're trying to achieve?
Otherwise, just hide it all and set the state to inactive. I mean if you have many modals, then you could store an object into session storage using something like the code I've written below(keep in mind I've not tested this code):
const Session = {
get: key => {
try {
JSON.parse(sessionStorage.getItem(key));
} catch (e) {
return sessionStorage.getItem(key);
}
},
set: (key, data) => {
try {
sessionStorage.setItem(key, JSON.stringify(data));
} catch (e) {
sessionStorage.setItem(key, data);
}
}
};
So with this, you could just set some object, i.e. modalStates in you JavaScript, and then execute some check on load to check the state of each modal? I mean I'm not sure if you'd want to only allow only one modal to be active at any given time or if you'd want multiple to be active and open, etc...
Edit
Here's a simple demo, it won't work on here if I'm not mistaken, but if you try it on JSFiddle, I believe it should work without a problem. Again, this is just an example, it's merely here to give you an idea of how to solve your problem.
const dhtml = document.getElementById("demo");
const modal = document.getElementById("mdoal");
const btn = document.getElementById("change");
let state = {};
// Simple on error function.
const log = arg => {
console.clear();
console.log(arg);
};
// Simple get state function.
const getState = () => {
try {
if (JSON.parse(sessionStorage.getItem("demo")) != null) {
state = JSON.parse(sessionStorage.getItem("demo"));
} else {
state = {};
}
} catch (e) {
//log(e);
}
return state;
};
// Simple set state function.
const setState = () => {
try {
state = sessionStorage.setItem("demo", JSON.stringify(state));
} catch (e) {
//log(e);
}
};
// A simple on state change function.
const updateState = () => {
if (state.active == null) {
state.active = true;
} else {
state.active = !state.active;
}
setState();
log('State changed.');
};
// A simple render function.
const render = () => {
if (state.active == null || state.active == false) {
dhtml.textContent = 'Inactive';
modal.style.display = 'none';
} else {
dhtml.textContent = 'Active';
modal.style.display = 'block';
}
};
// A simple click handler for the change button.
const clickHandler = () => {
updateState();
getState();
render();
// window.location.reload(); // Simulate a http refresh/redirect.
};
// A simple on load function.
const onLoad = () => {
getState(); // Update the state object.
render(); // Initial render;
btn.onclick = clickHandler;
};
onLoad();
<div id="demo">
<p>Inactive</p>
</div>
<div id="mdoal" style="display: none">
<p>Hello World!</p>
</div>
<button id="change">state change</button>
You can use localStorage to achieve this basically, you don't have full code so I m assuming and and giving you an example:
function reason(id) {
$('.receiver').text('To: ' + id);
$('#message_value').val(id);
console.log((JSON.stringify(id)));
localStorage.setItem('isModalActive', '1'); // Add is modal active
$('#small').modal('show');
}
So now you set isModalActive 1 to users localStorage than you can check onload
$( document ).ready(function() {
if(localStorage.getItem('isModalActive') == '1'){
$('#small').modal('show');
}
});
Than when you closing to modal dont forget to change the value to 0
localStorage.setItem('isModalActive', '0'); // Add is modal not Active
Hope it helps.
I have several buttons belonging to the same class. I want to retrieve the value of the button I click on.
Here is my code:
var battons = document.getElementsByClassName("converting_video");
var number_of_buttons = battons.length;
function actual_url() {
while (number_of_buttons > 0) {
for (i = 1; i <= number_of_buttons; i++) {
function getting_url() {
battons[i].addEventListener("click", video_url)
}
function video_url(url) {
alert(url);
}
}
}
}
var battons = document.getElementsByClassName("class_btns");
var number_of_buttons = battons.length;
function actual_url() {
while (number_of_buttons > 0) {
for (i = 1; i <= number_of_buttons; i++) {
function getting_url() {
battons[i].addEventListener("click", video_url)
}
function video_url(url) {
alert(url);
}
}
}
}
<button class="class_btns" value='1'> results </button>
<button class="class_btns" value='2'> results </button>
<button class="class_btns" value='3'> results </button>
<button class="class_btns" value='4'> results </button>
This will allow you to get the value of any of the buttons clicked. Using jQuery's .click() event handler and $(this).val() will allow the value of the clicked button to be the value in the alert. Not sure what you are actually looking for with video_url etc, but this should point you in the right direction. You can then use the value from the click to do pass to your function rather than jusrt alerting i eg: ... video_url(btnVal) ...
$(document).ready(function(){
$('.class_btns').click(function(){
var btnVal = $(this).val();
alert(btnVal);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="class_btns" value='1'>results</button>
<button class="class_btns" value='2'>results</button>
<button class="class_btns" value='3'>results</button>
<button class="class_btns" value='4'>results</button>