button is still clickable after call window.alert - javascript

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>

Related

How to enable disabled the submit button using JavaScript or jQuery?

I have a form Data in the HTML like the below,
Blade file:
<form method="post" action="someURL" id="register">
<input type="text" name="name" id="name" />
<div class="error">{{ $errors->first('name') }}</div>
<input type="email" name="email" id="email"/>
<div class="error">{{ $errors->first('email') }}</div>
<textarea name="body" id="message"> Enter your message here</textarea>
<div class="error">{{ $errors->first('message') }}</div>
<input type="submit" id="btnSubmit" disabled />
</form>
<script>
const button = document.querySelector("#btnSubmit");
const buttonExpirationDataKey = 'button-disabled-expiration';
let startButtonStateCheck = () => {
button.dataset.interval = setInterval(updateButtonState, 1000);
}
let updateButtonState = () => {
let expirationDate = new Date(button.dataset.enabledAt);
if (expirationDate < new Date()) {
button.disabled = false;
clearInterval(button.dataset.interval);
} else {
button.disabled = true;
}
}
let buttonDisableExpiration = localStorage.getItem(buttonExpirationDataKey);
if (!buttonDisableExpiration) {
// no button state in localStorage, enable button
button.disabled = false;
} else {
// button state held in localStorage, check every 1s for expiration to enable the button again
button.dataset.enabledAt = buttonDisableExpiration;
updateButtonState();
startButtonStateCheck();
}
button.addEventListener("click", () => {
var form = document.getElementById("register");
var fields = ["name", "email", "body"];
var i, l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if (form[fieldname].value === "") {
button.disabled = false;
}
else{
button.disabled = true;
let now = new Date();
let expirationTime = 1000 * 10;
let expirationDate = new Date(now.getTime() + expirationTime);
localStorage.setItem(buttonExpirationDataKey, expirationDate);
button.dataset.enabledAt = expirationDate;
startButtonStateCheck();
}
}
});
</script>
In controller::
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required',
]);
I have validated the fields in the controller.
The Submit button on click should check whether all the Input Values were given, If either one of the values is missing, the Submit button should be Enabled, even on click. I have given the validation in the controller
In my code, the submit button is disabled every time, when it is clicked even without the input values. But, it shows the error as This field is required near the input fields, when we click the submit button.
I need the submit button to be Disabled on click, when all the input values were given and then storing the button Enabled and Disabled in the Local storage.
When a user submits the form, without entering the form input, the button should be Enabled.
But, the submit button is not working as expected. It gets disabled, even without the form inputs
How could I do this? Could anyone please help?
Here first you will have to prevent the default action of the form so you need to use preventDefault() on event and than after all validations check you can manually submit or enable the button. But the main thing is that you need to disable the default behaviour to add your own custom checks.
Here is a fiddle to show :
https://jsfiddle.net/g6wfkj74/7/
Hope this helped

Prevent default on enter key with a button in Javascript

I have my HTML code:
<!DOCTYPE html>
<head>
<script src="../req.js"></script>
</head>
<link rel="stylesheet" href="style.css">
<html>
<body>
<h1> Recipes founder</h1>
<form class="example">
<input id ="query" type="text" placeholder="Insert a recipe.." name="search" value="">
<button id="searchRecipe" type="button" onkeydown="handler(e)" onclick="searchFile()"><i></i>Search</button>
</form>
<div id="content"></div>
</body>
</html>
and my js code associated with it:
function searchFile(e) {
// enter must do the same
const q = document.getElementById('query').value;
const total_q = `Title%3A${q}%20OR%20Description%3A${q}%20OR%20web%3A${q}`
fetch(
`http://localhost:8983/solr/recipe/select?indent=true&q.op=OR&q=${total_q}&rows=300`, { mode: 'cors' }
).then((res) => res.json())
// Take actual json
.then(({ response }) => appendData(response))
.catch(function (err) {
console.log(err)
});
}
function appendData(data) {
// clear previous research
document.getElementById("content").innerHTML = "";
let docs = data.docs;
// Take each element of the json file
for (elem of docs) {
var mainContainer = document.getElementById("content");
// title recipe
var a1 = document.createElement("a");
a1.setAttribute("href", elem.url);
var div = document.createElement("div");
div.innerHTML = elem.Title;
a1.appendChild(div);
// insert image of recipe and link for page in website
var a = document.createElement("a");
a.setAttribute("href", elem.Image);
var img = document.createElement("img");
// img.setAttribute("href", elem.url);
img.setAttribute("src", elem.Image);
a.appendChild(img);
// recipe description
var p = document.createElement("p");
p.innerHTML = elem.Description;
// Insert elements in dev
mainContainer.appendChild(a1);
mainContainer.appendChild(p);
mainContainer.appendChild(a);
}
}
function handler(event) {
if (event == "click") {
searchFile();
}
else if ((event.keyCode || event.which) == 13){
event.preventDefault();
event.cancelBubble = true;
event.returnValue = false;
event.stopPropagation();
event.preventDefault();
searchFile();
}
else {
console.log("Nothing")
}
}
What searchFile() and appendData() do is not important because they work. The target is when the user clicks on the search button or presses the enter key, searchFile() must be called. Clicking on the search button works, but the problem is when a user clicks enter, it navigates to http://localhost:8000/?search=SOMETHING (depends on what the user inserted) . I think it is the default behaviour of the enter key, I tried to prevent it using different codes but nothing works. I read that instead of using the event onkeypress we have to use onkeydown but I'm still in the same situation. I tried also to wait for the DOM to be loaded but nothing. Does someone have an idea about it?
Remove all the event handlers on the button
Make the button a submit button
Use the submit event on the form (this will trigger if the form submission is trigged by enter in the input or the button being clicked or enter being pressed over the button)
Prevent the default event behaviour (so the form data isn't submitted to a URL which the browser navigates to)
Don't bother doing any tests to try to figure out if it was a click or something else, all that matters if that the form was submitted.
const submitHandler = (event) => {
event.preventDefault();
alert("You can do your ajax search here");
};
document.querySelector('.example').addEventListener('submit', submitHandler);
<form class="example">
<input id="query" type="text" placeholder="Insert a recipe.." name="search" value="">
<button>Search</button>
</form>

sweet alert message in JavaScript is showing for a split second

When user press confirm button,
i need to check a few things using javascript and in a certain condition need to show sweet alert
in which, once the user will press ok (in the sweetalert message) it will redirect to another page.
but the alert is showing for a split second and not redirecting to the page(since i didnt press "ok").
javascript is called from onClick of a button in the view:
<div class="col">
<button type="submit" class="btn btn-primary form-control" onclick="ApprovePayment()">Create</button>
</div>
here is the javascript in the view :
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script src="https://cdn.tiny.cloud/1/h0b6kdvecrt66vsb30f5tpqd7ocxoezkzq6fcfbbvp0xrbfw/tinymce/5/tinymce.min.js"></script>
<script type="text/javascript">
function ApprovePayment() {
var val = document.getElementById("PaymentHistory_SentFromAddressId");
var selectedText = val.options[val.selectedIndex].text;
var amount = document.getElementById("PaymentHistory_Amount");
var value = parseFloat(amount.value);
var max = parseFloat(amount.getAttribute("data-val-range-max"));
var min = parseFloat(amount.getAttribute("data-val-range-min"));
if (!(value < min || value > max)) {
window.alert("amount validated");
if (selectedText.includes("- Paypal")) {
window.alert("in paypal")
}
else {
swal("Success!", "Payment Added To Your List, Admin will Approve once Payment Received!", "success")
.then((value) => {window.location.href = '/UserRole/PaymentHistory'; });
}
}
}
</script>
}
The onclick listner is defined on the submit button, when you click on the submit button the browser will perform the default action which is the form submit.
To prevent this you can use two approaches.
Add the listener on the form onsubmit.
Prevent the browser default action.
Change the button type from submit to 'button'.
Example for the second method.
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script src="https://cdn.tiny.cloud/1/h0b6kdvecrt66vsb30f5tpqd7ocxoezkzq6fcfbbvp0xrbfw/tinymce/5/tinymce.min.js"></script>
<script type="text/javascript">
function ApprovePayment(event) {
event.preventDefault(); // stop the default action
var val = document.getElementById("PaymentHistory_SentFromAddressId");
var selectedText = val.options[val.selectedIndex].text;
var amount = document.getElementById("PaymentHistory_Amount");
var value = parseFloat(amount.value);
var max = parseFloat(amount.getAttribute("data-val-range-max"));
var min = parseFloat(amount.getAttribute("data-val-range-min"));
if (!(value < min || value > max)) {
window.alert("amount validated");
if (selectedText.includes("- Paypal")) {
window.alert("in paypal")
}
else {
swal("Success!", "Payment Added To Your List, Admin will Approve once Payment Received!", "success")
.then((value) => {window.location.href = '/UserRole/PaymentHistory'; });
}
}
}
</script>
}

How can I make it so that when input field is empty, button does nothing?

I'm making a simple searcher in which the user enters a query, clicks search, and the program returns either the location of said element, or a "No results found" line.
I'm having trouble with the search button itself. It works perfectly fine when the element that is being searched exists, but if I click on it while the input is blank, it returns the "No results found" message. I would like it so that it does nothing.
I'm using mainly JavaScript. What I've tried so far is make an if statement to check the length of the input, and then select the element from the DOM and make it disabled when length is 0.
I have tried adding both console.log and alert() to check the state of the button (enabled/disabled), and they both work equally, no matter the length of the input value.
<button value="submit" id="button" data-key="13" onclick="clickFunction()">
</button>
function clickFunction() {
var input = document.getElementById('input_id').value;
var input = input.toLowerCase();
/* disables button if there is no input */
if ( input.length === 0 ) {
document.getElementById("button").disabled = true;
console.log("disabled");
} else if (input.length > 0) {
document.getElementById("button").disabled = false;
console.log("enabled");
}
}
I have also tried using jQuery ($("#button").attr("disabled", true)), but it's not working either.
Am I missing something?
You need to stop the click, disabling the button with click means you will not be able to enable it.
function clickFunction(evt) {
var input = document.getElementById('input_id').value.trim();
// if (!input.length) { evt.preventDefault(); }
if (!input.length) return false; // cancel click
return true
}
<form>
<input type="search" id="input_id" name="input_id" />
<button value="submit" id="button" data-key="13" onclick="clickFunction(event)">
</button>
</form>
but why use JavaScript, let HTML do it for you.
<form>
<input type="search" name="search" required />
<input type="submit" />
</form>
this should work
function validate(obj) {
if (obj.value.length > 0) {
document.getElementById("btnSave").disabled = false;
} else {
document.getElementById("btnSave").disabled = true;
}
}
<input type="text" id="txtName" onkeyup="validate(this)"/>
<button disabled id="btnSave">save</button>
You can modify your code in this manner:
function clickFunction() {
var input = document.getElementById('input_id').value;
input = input.toLowerCase();
if (input.length) {
// write your search logic here
} else {
// won't do anything
return false;
}
}
I hope it will help.

Disable button after adding task to task list

I would like to add some items to task list and disable button each time. When page loads it works fine.
I'd like to also disable button after adding each task.
If you add a new task and press submit button it works fine. But if the user choose pressing 'Enter' button instead of submit it becomes enabled.
What should it be done to disable submit button if the user prefers 'Enter' button instead of submit button ?
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', () => {
// By default, submit button is disabled
document.querySelector('#submit').disabled = true;
// Enable button only if there is text in the input field
document.querySelector('#task').onkeyup = () => {
document.querySelector('#submit').disabled = false;
};
document.querySelector('#new-task').onsubmit = () => {
// Create new item for list
const li = document.createElement('li');
li.innerHTML = document.querySelector('#task').value;
// Add new item to task list
document.querySelector('#tasks').append(li);
// Clear input field and disable button again
document.querySelector('#task').value = '';
document.querySelector('#submit').disabled = true;
// Stop form from submitting
return false;
};
});
</script>
<title>Tasks</title>
</head>
Body part of the html.
<body>
<h1>Tasks</h1>
<ul id="tasks">
</ul>
<form id="new-task">
<input id="task" autocomplete="off" autofocus placeholder="New Task" type="text">
<input id="submit" type="submit">
</form>
</body>
</html>
When you click the enter button, your onkeyup event handler changes the submit button disabled state to false, and the enter works.
Instead, listen to the input event of the #task box, and enable/disable the submit button according to the changes in the content. This will also handle the case in which submit is enabled after the text was deleted.
// Enable button only if there is text in the input field
document.querySelector('#task').addEventListener('input', (e) => {
document.querySelector('#submit').disabled = e.target.value === '';
});
Example:
// By default, submit button is disabled
document.querySelector('#submit').disabled = true;
// Enable button only if there is text in the input field
document.querySelector('#task').addEventListener('input', (e) => {
document.querySelector('#submit').disabled = e.target.value === '';
});
document.querySelector('#new-task').onsubmit = () => {
// Create new item for list
const li = document.createElement('li');
li.innerHTML = document.querySelector('#task').value;
// Add new item to task list
document.querySelector('#tasks').append(li);
// Clear input field and disable button again
document.querySelector('#task').value = '';
document.querySelector('#submit').disabled = true;
// Stop form from submitting
return false;
};
#submit:disabled {
opacity: 0.5;
}
<h1>Tasks</h1>
<ul id="tasks">
</ul>
<form id="new-task">
<input id="task" autocomplete="off" autofocus placeholder="New Task" type="text">
<input id="submit" type="submit">
</form>
When you press enter key the event listner keyup is firing. You have to put the enable of button here in conditions
document.querySelector('#task').onkeyup = (e) => {
if(e.which === 13){
return; // When user enter key press
}
document.querySelector('#submit').disabled = false;
};
I was watching Harvard CS50 Web Programming Course and I'd like to share another solution. This is not a part of homework, assignment etc. so I feel free to share solution.
Basically we enable button if there is text in the input field.
// Enable button only if there is text in the input field
document.querySelector('#task').onkeyup = () => {
if (document.querySelector('#task').value.length > 0)
document.querySelector('#submit').disabled = false;
else
document.querySelector('#submit').disabled = true;
};
// By default, submit button is disabled
document.querySelector('#submit').disabled = true;
// Enable button only if there is text in the input field
document.querySelector('#task').onkeyup = () => {
if (document.querySelector('#task').value.length > 0)
document.querySelector('#submit').disabled = false;
else
document.querySelector('#submit').disabled = true;
};
document.querySelector('#new-task').onsubmit = () => {
// Create new item for list
const li = document.createElement('li');
li.innerHTML = document.querySelector('#task').value;
// Add new item to task list
document.querySelector('#tasks').append(li);
// Clear input field and disable button again
document.querySelector('#task').value = '';
document.querySelector('#submit').disabled = true;
// Stop form from submitting
return false;
};
#submit:disabled {
opacity: 0.5;
}
<h1>Tasks</h1>
<ul id="tasks">
</ul>
<form id="new-task">
<input id="task" autocomplete="off" autofocus placeholder="New Task" type="text">
<input id="submit" type="submit">
</form>

Categories

Resources