Click button containing some text - javascript

I want to create a "script" to click in a button everytime it contains 'PLACE BET'
i could do that easy with classes, but the problem is the button have the same classes, only thing different is the text.
<button type="button" name="button" style="z-index:10;" class="place_bet crash-button-bet bet_placed">PLACE BET</button>```
when i click:
```<button type="button" name="button" style="z-index:10;" class="place_bet crash-button-bet bet_placed">BETTING (44) (click to cancel)</button>```

if i understood you right you wanna add a event listener which change the inner HTML of The button.
If so:
<script>
function changeButton(){
if (document.getElementById('btnplacebet').textContent == "PLACE BET")
{
document.getElementById('btnplacebet').textContent = "BETTING (44) (click to cancel)";
}
else
{
document.getElementById('btnplacebet').textContent = "PLACE BET";
}
}
</script>
<button onclick="changeButton()" id="btnplacebet" type="button" name="button" style="z-index:10;" class="place_bet crash-button-bet bet_placed">PLACE BET</button>```

<script>
function changeButtonText(){
if (document.getElementById('btn-id').textContent == "PLACE BET")
{
document.getElementById('btn-id').textContent = "CLICK TO CANCEL";
}
else
{
document.getElementById('btn-id').textContent = "PLACE BET";
}
}
</script>
<button onclick="changeButtonText()" id="btn-id" type="button">PLACE BET</button>

Related

How to create dynamic functionality using Javascript and HTML?

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
}
}

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()");
}

Double submit, prevent default not working

I hope someone can help me.
I have two buttons on my page in my form. "Save" and "Publish". This is the HTML:
<button type="submit" class="button">Save</button>
<button type="button" class="button" name="publish" value="true" onclick="publishAlbum({{ album.id }}, '{{ album.title }}')">Publish</button>
The first one saves the album, the second one sends an e-mail to the owner. The second one ("Publish") needs to trigger a confirm first ("Are you sure?"). When you click "Ok", the form should submit, but if you click "Cancel" (in the confirm box), it should do nothing.
Here is my JS:
function publishAlbum(album_id, album_title)
{
var result = confirm('Are you sure you want to publish this album?');
if(!result)
{
return;
}
}
I tried literally everything (prevent default, return etc), but every time I click "Cancel", the form still submits and the e-mail is sent.
Can someone help me?
Publish
$('.publish-button').on('click',function(e){
e.preventDefault();
let albumId = $('#selectYourAlbumId');
let albumTitle = $('#selectYourAlbumTitle');
var result = confirm('Are you sure you want to publish this album?');
if(!result)
{
return;
}
// POST your form through an AJAX call
})
You need to get the event object somehow (e.g. by adding an event listener to the button). Then you are able to prevent the form submission, like so:
const album = {
id: 1,
title: 'Test',
};
document.querySelector('[name=publish]').addEventListener('click', function(e) {
if (!publishAlbum(album.id, album.title)) {
e.preventDefault();
}
});
function publishAlbum(album_id, album_title) {
var result = confirm('Are you sure you want to publish this album?');
if (!result) {
return false;
}
// do your stuff
return true;
}
<form action="https://example.org" method="POST">
<button type="submit" class="button">Save</button>
<input type="submit" class="button" name="publish" value="Publish" />
</form>
Assuming you have these buttons inside a form tag, you can try this:
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button type="submit" class="button">Save</button>
<button type="button" class="button" name="publish" value="true" onclick="publishAlbum()" id="myButton">Publish</button>
<script>
function publishAlbum() {
var txt;
if (confirm("Press a button!") == true) {
$("#myButton").trigger('submit');
} else {
txt = "You pressed Cancel!";
alert(txt)
}
}
</script>
</body>
</html>
I used this:
$(document).ready(function() {
$('#form-publish .button-publish').on("click", function(e) {
var c = confirm("Are you sure?");
if (c) {
return;
} else {
e.preventDefault();
}
});
});

Simple Javascript enable/disable button program?

I want a simple program that basically enables/disables buttons as each button is pressed.
So, there are three buttons. The left button is enabled at the start of the program and I want to disable it and enable the button next to it onclick. The same when I press on the second button.
Can anyone show me where I'm going wrong in my code?
<html>
<head>
<button id="func1" onclick="func(1)">func 1</button>
<button id="func2" disabled="false" onclick="func(2)">func 2</button>
<button id="func3" disabled="false" onclick="func()">func 3</button>
</head>
<body>
<script>
var number = '';
function func(number)
if(number == '1'){ //Sets button setting to disabled or enabled when wanted
after particular parts of the program are run.
document.getElementById('func1').disabled = true;
document.getElementById('func2').disabled = false;
document.getElementById('output').disabled = true;
}
else if(number == '2'){
document.getElementById('func1').disabled = true;
document.getElementById('func2').disabled = true;
document.getElementById('func3').disabled = false;
}
</script>
</body>
</html>
Thanks again :)
First things first, you need to move the buttons from <head> to <body>.
Now on to the problem at hand: your function was missing the {} brackets around it and your comment was broken into two lines, the second of which was causing a syntax error. Should work now:
<button id="func1" onclick="func(1)">func 1</button>
<button id="func2" disabled="false" onclick="func(2)">func 2</button>
<button id="func3" disabled="false" onclick="func()">func 3</button><script>
function func(number){
if(number == '1'){ //Sets button setting to disabled or enabled when wanted after particular parts of the program are run.
document.getElementById('func1').disabled = true;
document.getElementById('func2').disabled = false;
document.getElementById('output').disabled = true;
}
else if(number == '2'){
document.getElementById('func1').disabled = true;
document.getElementById('func2').disabled = true;
document.getElementById('func3').disabled = false;
}
}
</script>
I think better to use something universal, like this:
<html>
<body>
<button class="myButton" onclick="myHandler(this)" >func 1</button>
<button class="myButton" onclick="myHandler(this)" disabled>func 2</button>
<button class="myButton" onclick="myHandler(this)" disabled>func 3</button>
<script>
function myHandler (e) {
// Toggle disabled property of current button.
e.disabled = !e.disabled;
// Toggle disabled property for next sibling if it has class 'myButton'.
if (e.nextElementSibling.className === 'myButton') {
e.nextElementSibling.disabled = !e.nextElementSibling.disabled;
// Otherwise toggle first button with class 'myButton'.
} else {
var b = document.getElementsByClassName('myButton')[0];
b.disabled = !b.disabled;
}
}
</script>
</body>
</html>

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

Categories