How to create dynamic functionality using Javascript and HTML? - javascript

I'm creating a page which has multiple order buttons (One for each menu item). When an order is placed I want to call a Javascript function to change only the order button pressed rather than every button with the ID. There has to be better implementation for these function calls... Anyone?
function orderFood1(helpVal) {
if (document.getElementById("food1").innerHTML === "Order") {
document.getElementById("food1").innerHTML = "✅";
// Alert waiter
} else {
document.getElementById("food1").innerHTML = "Order";
// Cancel Request
}
}
function orderFood2(helpVal) {
if (document.getElementById("food2").innerHTML === "Order") {
document.getElementById("food2").innerHTML = "✅";
// Alert waiter
} else {
document.getElementById("food2").innerHTML = "Order";
// Cancel Request
}
}
function orderFood3(helpVal) {
if (document.getElementById("food3").innerHTML === "Order") {
document.getElementById("food3").innerHTML = "✅";
// Alert waiter
} else {
document.getElementById("food3").innerHTML = "Order";
// Cancel Request
}
}
<button type="button" id="food1" onclick="orderFood1()" class="btn btn-primary">Order</button>
<button type="button" id="food2" onclick="orderFood2()" class="btn btn-primary">Order</button>
<button type="button" id="food3" onclick="orderFood3()" class="btn btn-primary">Order</button>

They all look to do nearly the same thing, so you can use only a single function. To identify which button was clicked, you can examine the clicked button from the listener - the target of the event. Also, best to avoid inline handlers - attach the listeners properly using Javascript instead.
Since you're only inserting text, it'd be more appropriate to retrieve and assign to the textContent of the element, rather than its innerHTML.
const handleOrder = ({ target }) => {
if (target.textContent === 'Order') {
target.textContent = '✅';
console.log('Alerting waiter');
} else {
target.textContent = "Order";
console.log('Canceling request');
}
};
for (const button of document.querySelectorAll('button')) {
button.addEventListener('click', handleOrder);
}
<button type="button" class="btn btn-primary">Order</button>
<button type="button" class="btn btn-primary">Order</button>
<button type="button" class="btn btn-primary">Order</button>

I think you can create the following html code:
<button type="button" id="food1" onclick="orderFood('food1')" class="btn btn-primary">Order</button>
<button type="button" id="food2" onclick="orderFood('food2')" class="btn btn-primary">Order</button>
Which means that you use only single orderFood function, that gets the ID of the button element as a parameter.
And then your JS code could be something like this:
function orderFood(foodId) {
if (document.getElementById(foodId).innerHTML === "Order") {
document.getElementById(foodId).innerHTML = "✅";
// Alert waiter
} else {
document.getElementById(foodId).innerHTML = "Order";
// Cancel Request
}
}

Related

Delay Button Submit Javascript

I'm trying to add adelay on my submit button in javascript.
But it just seems to freeze and no longer commits any action after clicking on it.
Does anyone have an explanation ?
function Progress() {
var button = document.getElementById("Button");
var form = document.getElementById("new_video")
form.onsubmit = function() {
return false;
}
button.onclick = function() {
setTimeout(function() {
form.submit();
}, 2000);
return false;
}
}
<input type="submit" name="commit" value="Upload" class="btn btn btn-primary" onclick="Progress()" id="Button" data-disable-with="Upload" disabled="">
// Cache your Form Elements
const EL_form = document.querySelector("#myForm");
const EL_formSubmitBtn = EL_form.querySelector("#Button");
const Progress = (evt) => {
evt.preventDefault(); // Prevent Browser Submit action
EL_formSubmitBtn.disabled = true; // Disable the submit button
setTimeout(function() {
EL_form.submit(); // Or do AJAX stuff here
EL_formSubmitBtn.disabled = false; // Enable the submit button
}, 2000);
};
// Use Element.addEventListener instead of inline JS
// Don't attach handlers to button, rather use the Form "submit" Event:
EL_form.addEventListener("submit", Progress);
<form id="myForm" action="demo.php">
<input id="Button" type="submit" value="Upload" class="btn btn btn-primary">
</form>
PS: Don't capitalise names of regular functions that do not actually return an Object - or are not a Class by definition, use rather progress as your function name. Or rather be more descriptive, it's actually a formSubmitHandler
You could try this:
var button = document.getElementById("Button");
var form = document.getElementById("new_video");
button.onclick = function(event) {
event.preventDefault();
setTimeout(form.submit, 2000);
}
and
<input type="submit" name="commit" value="Upload" class="btn btn btn-primary" id="Button" data-disable-with="Upload">
Hope this helps.

javascript loop through each value of the button and get the return value of submitted button

Here is my buttons with different values.
<div id="RAM_BtnGroup" class="btn-group" role="group" aria-label="Basic example" name='ram'>
<button type="button" value="8GB" class="btn btn-outline-success">8GB </button>
<button type="button" value="16GB" class="btn btn-outline-success">16GB </button>
<button type="button" value="32GB" class="btn btn-outline-success">32GB </button>
<button type="button" value="64GB" class="btn btn-outline-success">64GB </button>
Price: <span id="totalCost"></span>
So when I randomly click on different buttons, I'm still getting back the value of 8GB.
var ram = document.querySelector("button[type=button]");
ram.addEventListener('click', calculateTotal)
So how should I click on different buttons in order to get different values?
Should I get the value of button regards to something like this? But it is not working in this way.
var ram = document.querySelector("button[value=8GB][value=16GB][value=32GB][value=64GB]");
million thanks to the suggested solution, it's good enough but my calculateTotal function still not counting on the ram.Can you guide me how to fix this out. Here is my code. I am pretty sure that unitcost, additional and qty run smoothly, but after added in ramcost to get the value of ram, it seem to not returning any total price of all items.
var ram = document.querySelectorAll('button[type="button"]');
ram.forEach((ramm) => {
ramm.addEventListener('click', calculateTotal)
});
var ram_price = {};
ram_price['8GB'] = 200;
ram_price['16GB'] = 300;
ram_price['32GB'] = 400;
ram_price['64GB'] = 500;
function calculateTotal
() {
var ramcost = ram_price[ramm.value];
var unitCost = product_price[productEl.value];
var additionalCost = size_price[sizeEl.value] || 0;
var qty = quantityEl.value || 0;
totalCostEl.textContent = `Total cost: $${(unitCost + additionalCost + ramcost) * qty}`;
}
Can you please check this difference,
queryselector_class:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_queryselector_class
as well as
queryselectorall_class:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_queryselectorall_class
I think it will help.
You have to attach the click event to every button. querySelector() returns only the first matching element, while querySelectorAll() returns all matching elements. That's why you need to use the latter:
var ram = document.querySelectorAll("button[type=button]");
ram.forEach((r) => {
r.addEventListener('click', calculateTotal)
});
function calculateTotal(e) {
console.log(e.target.value);
}
<button type="button" value="8GB" class="btn btn-outline-success">8GB </button>
<button type="button" value="16GB" class="btn btn-outline-success">16GB </button>
<button type="button" value="32GB" class="btn btn-outline-success">32GB </button>
<button type="button" value="64GB" class="btn btn-outline-success">64GB </button>
<div id='container'></div>
I hope this helps, you can create a class ButtonToPress and then instance buttons. Its working
class ButtonToPress {
constructor(n) {
this.n = n;
const button = document.createElement('button');
button.onclick = this.print.bind(this);
button.innerText = this.n
document.getElementById('container').appendChild(button);
}
print() {
console.log(this.n);
}
}
let buttons = [];
for (let i = 8; i < 128; i *= 2) {
buttons[i] = new ButtonToPress(i + 'GB');
console.log(buttons[i]);
}

how to call one javascript function from several similar html events

i'm calling this javascript function from a button inside html but i need to replicate the button in several places. Using the same javascript function for all the buttons doesn't seem possible to me as it kept performing the action on the first button alone, i tried renaming the function by adding digits but that will be stressful and make my code excessively bulky.
please help.
//HTML button
<a href="#" title="Comment" class="lk-btn" onclick="openForm()">
// button 1
function openForm() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
// button 2
function openForm1() {
document.getElementById("myForm1").style.display = "block";
}
function closeForm1() {
document.getElementById("myForm1").style.display = "none";
}
//button 3
function openForm2() {
document.getElementById("myForm1").style.display = "block";
}
function closeForm1=2() {
document.getElementById("myForm1").style.display = "none";
}
You can call the same function from multiple buttons this way.
You have to assign an id to each button in your HTML code and pass it to your javascript function when you call it.
HTML Code
<button type="button" onclick="openForm(this)" id="1">Button1</button>
<button type="button" onclick="openForm(this)" id="2">Button2</button>
<button type="button" onclick="openForm(this)" id="3">Button3</button>
JS Function
function openForm(elem) {
alert("Calling openForm() from Button " + elem.id);
}
Update : To use without assigning the IDs
<button type="button" onclick="openForm()" >Button1</button>
<button type="button" onclick="openForm()" >Button2</button>
<button type="button" onclick="openForm()" >Button3</button>
function openForm() {
alert("Calling openForm()");
}

Cancel on confirm still submits form

I have a form with a submit and cancel button and I want to show a different confirm message bepending on which button is clicked so this is what I've come up with.
function confirmDialog(buttonId) {
switch (buttonId) {
case "cancel":
var result = confirm("cancel message");
submitForm(result);
break;
case "submit":
var result = confirm("Submit message");
submitForm(result);
break;
}
};
And my submitForm function looks like
function submitForm(result) {
console.log(result); //this is false when I click cancel in the confirm box
if (result && $("#myform").valid()) {
$("#myform").submit();
}
else {
return false;
}
};
Now my issue is that when I click cancel the form still gets submited. Can someone tell me what I'm doing wrong please. I have return false; in my else condition so I really don't know why it still submits the forms.
I've looked at the following questions but I'm still facing the issue
jQuery Still Submits Ajax Post Even When “Cancel” is clicked on Confirm Dialog
javascript confirm (cancel) still submits form when returning false
Edit: Cancel button html as requested
<button type="submit" id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
Further Edit
I call the confirmDialog function in the click event the appropriate button as follows:
$("#cancel").click(function () {
var buttonId = $(this).attr("id");
confirmDialog(buttonId)
});
your button have default behavior of submit
replace
<button type="submit" id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
with
<button id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
... Edit after your update Try this code ....
replace your code
function submitForm(result) {
console.log(result); //this is false when I click cancel in the confirm box
if (result && $("#myform").valid()) {
$("#myform").submit();
}
else {
return false;
}
};
with
function submitForm(result) {
console.log(result); //this is false when I click cancel in the confirm box
if (result && $("#myform").valid()) {
$("#myform").submit();
}
else {
const element = document.querySelector('myform');
element.addEventListener('submit', event => {
event.preventDefault();
console.log('Form submission cancelled.');
});
}
};
----- Alternative working code if you consider changing your HTML structure ---
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
</head>
<body>
<form id="MyForm">
<button id="btnSubmit" class="btn btn-primary">Submit</button>
<button id="btnCancel" class="btn btn-danger">Cancel</button>
</form>
<script type="text/javascript">
$(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
$('#MyForm').submit();
});
$("#btnCancel").click(function (e) {
e.preventDefault();
var result = confirm("Sure Cancel?");
if (result) {
const element = document.querySelector('#MyForm');
element.addEventListener('submit', function (e) {
e.preventDefault();
});
alert("Form Submission Canceled");
}
else {
$("#MyForm").submit();
alert("Form Submitted");
}
});
})
</script>
</body>
</html>
Your <button> tag's type attribute seems to have submit as its value, just remove the type="submit" attribute in your HTML code and keep it just <button id="cancel".... />
<button id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
This will resolve your issue. Hope this helps!
The form submit is only omitted when "onsubmit" gets "false" from the Javascript handler.
Try this
"return submitForm..." (instead of just "submitForm...")
(2. Remove semicolons after function's closing brackets)
Update
Maybe the problem is the combination of input type=submit and $("#myform").submit();
If <form onsubmit=... receives no false (for example from a function return), the form will be submitted.
If <input type=submit onclick=... receives no false (for example from a function return), the button action (form submission) will be performed.
Raw (unchecked) solution option without using input type=submit:
HTML
<form id="myform" onsubmit="formValidation()">
<button value="Submit" onclick="buttonHandler(true)">
<button value="Cancel" onclick="buttonHandler(false)">
</form>
JS
function formValidation()
{
return $("#myform").valid();
}
function buttonHandler(isSubmit)
{
if (isSubmit ==== true)
{
if (confirm(submitMessage) === true)
{
$("#myform").submit();
}
}
else
{
if (confirm(cancelMessage) === true)
{
$("#myform").submit();
}
}
}
You can get this to work if you use an input tag instead of button tag and retain your styles by keeping your classes. e.g.
<input id="SomeId"
class="btn btn-danger btn-block"
onclick="return confirm('Are you sure you want to delete: X');"
value="Delete" />
I had similar problem and solved it with click event, which is very similar to your problem.
Try this:
$("#cancel").click(function () {
var buttonId = $(this).attr("id");
confirmDialog(buttonId);
return false;
});
Hope it helps.
Your tag's type attribute seems to have submit as its value, just remove the type="submit" attribute in your HTML code and keep it just
<button id="cancel".... />

Jquery form not saved

If a user tries to leave a page without saving it they get a message telling them.
But they also get it if they have saved the form too.
$("#locForm").change(function () {
mod = 1;
});
window.onbeforeunload = function confirmExit() {
if (mod == 1) {
return "information not saved.";
}
}
$("input[name='commit']").click(function () {
mod = 0;
});
This is my save button:
<button type="submit" class="btn btn-sample btn-md reset" id="send" name="commit"><b>Save</b></button>
How can it only warn user if they haven't saved the form?
You're using the wrong selector. Use:
$("button[name='commit']")

Categories