Diable the button , enable button after another button clock - javascript

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>

Related

why doesn't my local storage works but, copy of same code works

i got two copies of the same code with slight variation but seems the second one isnt working.
I have tried using ChatGPT to identify issues however, nothing was found. But as far as i can see, it should work.
But, everything i refresh, its removed.
I want the buttons to stay there.
working code:
const todoList = document.querySelector(".todo-list");
const todoForm = document.querySelector(".add-todo");
const removeList = document.querySelector(".remove-List");
let items = JSON.parse(localStorage.getItem("todoList")) || [
{
title: "Write on, 'do not forget to', and press '+' to add",
done: false,
},
{
title: "press 'X' to remove",
done: false,
},
{
title: "search via 'search box'",
done: false,
},
{
title: "filter via 'all'",
done: false,
},
];
function addTodo(e) {
e.preventDefault();
const title = this.querySelector("[name=item]").value;
const todo = {
title,
done: false,
};
items.push(todo);
saveTodos();
this.reset();
}
function createList(list = [], listTarget) {
listTarget.innerHTML = list
.map((item, i) => {
return `<li>
<input type="checkbox" id="todo${i}" data-index="${i}"
${item.done ? "checked" : ""} />
<label for="todo${i}">${item.title}
<span class="font-size:30px" data-index="${i}">X</span>
</label>
</li>`;
})
.join("");
}
function toggleDone(e) {
if (!e.target.matches("input")) return;
const el = e.target;
const index = el.dataset.index;
items[index].done = !items[index].done;
saveTodos();
}
function removeSingle(e) {
if (!e.target.matches("span")) return;
const el = e.target;
const index = el.dataset.index;
items.splice(index, 1);
saveTodos();
if (items.length === 0) {
removeList.classList.add("hidden");
}
}
function saveTodos() {
localStorage.setItem("todoList", JSON.stringify(items));
createList(items, todoList);
showRemoveButton();
}
function removeData() {
items = [];
localStorage.removeItem("todoList");
createList(items, todoList);
removeList.classList.add("hidden");
}
function showRemoveButton() {
if (items.length > 1) return;
removeList.classList.remove("hidden");
}
todoList.addEventListener("click", toggleDone);
todoList.addEventListener("click", removeSingle);
todoForm.addEventListener("submit", addTodo);
removeList.addEventListener("click", removeData);
// Init list
createList(items, todoList);
<div class="ToDo-container">
<header class="app-header">
<div class="app-header1">
<div class="title">
<h1 class="app-title">ToDo List</h1>
</div>
<div class="select-button">
<select id="filter">
<option value="all">All</option>
<option value="completed">Completed</option>
<option value="incomplete">Incomplete</option>
</select>
</div>
</div>
<div class="search-header">
<input type="text" id="search" placeholder="Search Todos">
<button type="button" id="search-button" class="btn">Search</button>
</div>
</header>
<section class="app-body">
<div id="toDo">
<ul class="todo-list"></ul>
<form class="add-todo">
<input
type="text"
placeholder="Don't Forget to..."
name="item"
required
/>
<input type="submit" value="+" />
</form>
</div>
<button class="remove-List btn">Remove All</button>
</section>
</div>
// Add button function
function addButton() {
// Prompt for button link and name
var link = prompt("Enter the button link:");
var name = prompt("Enter the button name:");
// Create new button element
var newButton = document.createElement("button");
newButton.innerHTML = name;
newButton.setAttribute("onclick", "location.href='" + link + "'");
// Append new button to button container
document.getElementById("button-container").appendChild(newButton);
// Save buttons to local storage
saveButtons();
}
// Remove buttons function
function removeButtons() {
// Clear button container
document.getElementById("button-container").innerHTML = "";
// Save buttons to local storage
saveButtons();
}
// Save buttons to local storage
function saveButtons() {
// Get button container HTML
var buttonHTML = document.getElementById("button-container").innerHTML;
// Save button HTML to local storage
localStorage.setItem("buttons", buttonHTML);
}
// Load buttons from local storage on page load
window.onload = function () {
// Get button HTML from local storage
var buttonHTML = localStorage.getItem("buttons");
// Set button container HTML
document.getElementById("button-container").innerHTML = buttonHTML;
};
<div class="shortcuts-container">
<header class="shortcut-header">
<h1 class="shortcut-title">Quick Links</h1>
</header>
<section class="shortcut-body">
<form id="button-form">
<div id="button-container"></div>
<button type="button" onclick="addButton()">Add Button</button>
<button type="button" onclick="removeButtons()">Remove Buttons</button>
</form>
</section>
</div>
i want some help with identifying the bug in my code
As you have mentioned that your "second one" is not working, I have focused on the second piece of code. This peice of code adds a button for which we need to provide a link and name via alert box, which is technically supposed to be a hyperlink. I have added 2 buttons using that and refreshed page multiple times but the newly added buttons always stay. Local storage is working just fine.
Also, looking at your code, there is NO localStorage.removeItem() present. Hence the window.onload works fine. However, if you have any error logs in console of dev tools, please provide them for further debugging.
Also, if there is a way for you attach a video link of testing with dev tools console visible that would really help to understand why it doesn't work for you.

How to display the buttons based on the boolean condition?

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>

button is still clickable after call window.alert

I was trying to prevent multiple submit. To prevent to submit the same value, I called window.alert to stop the process and tell the user the input value is already registered. The problem is the submit seems to be clickable after the alert window opened. Because after clicking the button several times after the alert window opens, and I closed the alert window. the alert window immediately re-opened without any clicks. the submit button seems to clickable after the windo open. how to disable all input right after the alert window open?
I was trying to disable a button by setting the state. However, it didn't work.
HTML
<form onSubmit={(e) => submitHandler(e)}>
<input
name="words"
value={words}
placeholder="Enter Tag for search"
onChange={(e) => onChangeHandler(e)}
/>
{disable ? (
<h1>updating</h1>
) : (
<button type="submit" disable={disable}>
submit
</button>
)}
</form>
const submitHandler = (e) => {
e.preventDefault();
if (!words) {
return null;
}
setNewSearchWordsState({ ...newSearchWordsState, disable: true });
const newList = list.map((item, idx) => {
if (idx === id) {
item.searchWords.map((searchWord) => {
if (searchWord === words) {
setNewSearchWordsState({ ...newSearchWordsState, words: '' });
window.alert(`${words} already registered`);
}
item.searchWords.push(words.toLowerCase());
});
}
return {
...item,
};
});
updateSearchWords(newList);
setNewSearchWordsState({ words: '', disable: false });
};
You may want try this working sample https://codepen.io/cunlay/pen/BaaROPG
// HTML
<form onsubmit="submitHandler()">
<input id="words" onkeyup="changeHandler()" placeholder="Enter Tag for search" />
<button type="submit" id="btn" disabled=true>Submit</button>
</form>
//JAVASCRIPT
<script>
function changeHandler(){
var words = document.getElementById('words');
var btn = document.getElementById('btn');
var text = words.value;
if(!text){
btn.disabled = true;
}else{
btn.disabled = false;
}
}
function submitHandler(){
//Your code here
alert("submitted");
return false;
}
</script>

how i can keep modal open after click?

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.

Retrieve unique value of a button

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>

Categories

Resources