Javascript - Toggle Visibility - javascript

I am trying to display a button when the input is valid.
It doesn't work, it just displays all the buttons.
Here is the JavaScript:
var toggleVisibility = function ()
{
hasOccurred = validate(textEntry);
if (hasOccurred == false) {
$("addBtn").style.visibility = "visible";
$("deleteBtn").style.visibility = "hidden";
}
else if (hasOccurred == true) {
$("addBtn").style.visibility = "hidden";
$("deleteBtn").style.visibility = "visible";
}
}
This is the HTML for the buttons:
<button type="button" class="btn btn-success" id="addBtn" oninput="toggleVisibility()"><i class="glyphicon glyphicon-plus-sign"></i> Add to Array</button><br/>
<button type="button" class="btn btn-danger" oninput="toggleVisibility()" id="deleteBtn"><i class="glyphicon glyphicon-remove-sign"></i> Delete from Array</button><br/>
<button type="button" class="btn btn-info" id="sumBtn">Sum of Array</button>

You're using the $ as if you're using jQuery (but with incorrect CSS selectors). Without jQuery you need document.getElementById("...")
Note: I changed hasOccurred so that the snippet works.
var toggleVisibility = function() {
hasOccurred = false;
if (hasOccurred == false) {
document.getElementById("addBtn").style.visibility = "visible";
document.getElementById("deleteBtn").style.visibility = "hidden";
} else if (hasOccurred == true) {
document.getElementById("addBtn").style.visibility = "hidden";
document.getElementById("deleteBtn").style.visibility = "visible";
}
}
toggleVisibility();
<button type="button" class="btn btn-success" id="addBtn" oninput="toggleVisibility()"><i class="glyphicon glyphicon-plus-sign"></i> Add to Array</button>
<br/>
<button type="button" class="btn btn-danger" oninput="toggleVisibility()" id="deleteBtn"><i class="glyphicon glyphicon-remove-sign"></i> Delete from Array</button>
<br/>
<button type="button" class="btn btn-info" id="sumBtn">Sum of Array</button>

Related

How do I disable multiple buttons when I click a button

<script type="text/javascript">
function button1() {
var elem = document.getElementById("button1");
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
function button2() {
var elem = document.getElementById("button2");
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
function button3() {
var elem = document.getElementById("button3");
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
function button4() {
var elem = document.getElementById("button4");
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
function button5() {
var elem = document.getElementById("button5");
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
</script>
How do disable all the buttons if I select one button. Do I have to disable all the buttons one by one or is there a way to do all the buttons.
Alright, with whatever you have given, maybe you're looking for something like a radio button. I am using Bootstrap and jQuery - it's much easier than vanilla JavaScript to achieve something that you're trying to do:
$(function () {
$(".btn").click(function () {
$(".btn").prop("disabled", true);
$(this).prop("disabled", false).addClass("active");
$("p").text("You have clicked on button #" + $(this).data("id") + ".");
$(this).text("Selected");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous" />
<div class="p-5">
<button class="btn btn-primary button-1" data-id="1">Choose 1</button>
<button class="btn btn-primary button-2" data-id="2">Choose 2</button>
<button class="btn btn-primary button-3" data-id="3">Choose 3</button>
<button class="btn btn-primary button-4" data-id="4">Choose 4</button>
<button class="btn btn-primary button-5" data-id="5">Choose 5</button>
<p id="status" class="py-3"></p>
</div>
On clicking of any button above, the respective button will be activated and the others will be disabled.
Resetting...
Option One: Using the same button!
$(function () {
$(".btn").click(function () {
if ($(this).hasClass("active")) {
$(".btn").prop("disabled", false);
$("p").text("");
$(this).text("Choose " + $(this).data("id"));
} else {
$(".btn").prop("disabled", true);
$(this).prop("disabled", false).addClass("active");
$("p").text("You have clicked on button #" + $(this).data("id") + ".");
$(this).text("Selected");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous" />
<div class="p-5">
<button class="btn btn-primary button-1" data-id="1">Choose 1</button>
<button class="btn btn-primary button-2" data-id="2">Choose 2</button>
<button class="btn btn-primary button-3" data-id="3">Choose 3</button>
<button class="btn btn-primary button-4" data-id="4">Choose 4</button>
<button class="btn btn-primary button-5" data-id="5">Choose 5</button>
<p id="status" class="py-3"></p>
</div>
Option Two: Using a Cancel Button
$(function () {
$(".btn-primary").click(function () {
$(".btn-primary").prop("disabled", true);
$(this).prop("disabled", false).addClass("active");
$(".btn-info").prop("disabled", false);
$("p").text("You have clicked on button #" + $(this).data("id") + ".");
$(this).text("Selected");
});
$(".btn-info").click(function () {
$(".btn").prop("disabled", false);
$("p").text("");
$(".btn-primary").text(function () {
return "Choose " + $(this).data("id");
});
$(this).prop("disabled", true);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous" />
<div class="p-5">
<button class="btn btn-primary button-1" data-id="1">Choose 1</button>
<button class="btn btn-primary button-2" data-id="2">Choose 2</button>
<button class="btn btn-primary button-3" data-id="3">Choose 3</button>
<button class="btn btn-primary button-4" data-id="4">Choose 4</button>
<button class="btn btn-primary button-5" data-id="5">Choose 5</button>
<p id="status" class="py-3"></p>
<button class="btn btn-info" disabled>Cancel</button>
</div>
I hope the above two solutions are something that you're looking for! 😁
Always avoid repetitive code.
By "disabling all buttons", I guess you mean set their value back to "Choose".
<script type="text/javascript">
function buttonBehavior(num) {
// reset all buttons
let i=1;
while(document.getElementById("button"+i)!==null) {
document.getElementById("button"+i).value = 'Choose';
i++;
}
// set selected button
var elem = document.getElementById("button"+num);
if (elem.value=="Choose") elem.value = "Selected";
else elem.value = "Choose";
}
</script>

How do you make a button disabled at first when the page is rendered and then it will be enabled when 2 button is pressed

I want to make the third button graph disabled at first and after the first 2 buttons (button1 and button2) is pressed and hidden, third will be enabled and can click on it.
<button type="button" class="btn btn-primary" id="button1" onclick="dataButton1(); this.style.visibility= 'hidden'; this.disabled=true">Data1</button>
<button type="button" class="btn btn-primary" id="button2" onclick="dataButton2();this.style.visibility= 'hidden'; this.disabled=true">data2</button>
<button type="button" class="btn btn-primary " id="button3" onclick="chart1();this.style.visibility= 'hidden'; this.disabled=true">Graph</button>
Have a go with this
const dataButton1 = () => console.log("1")
const dataButton2 = () => console.log("2")
const chart1 = () => console.log("chart 1")
const container = document.getElementById("container");
const buttons = [...container.querySelectorAll("button")];
container.addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.id === "button1") {
dataButton1();
}
else if (tgt.id === "button2") {
dataButton2();
}
else if (tgt.id === "button3") {
chart1();
}
tgt.setAttribute("hidden",true); // hide
const show = buttons.map(btn => btn.getAttribute("hidden")); // cannot use hasAttribute here
if (show[0] && show[1] && !show[2]) buttons[2].removeAttribute("disabled");
})
<div id="container">
<button type="button" class="btn btn-primary" id="button1">Data1</button>
<button type="button" class="btn btn-primary" id="button2">Data2</button>
<button type="button" class="btn btn-primary" id="button3" disabled>chart</button>
</div>
First add disable attribute to third button. Then on each click of button 1 and 2 check for hasAttribute("disabled") of other button to see both of them are clicked (and disabled) or not
Here is working sample:
function dataButton1() {
if (document.getElementById("button2").hasAttribute("disabled"))
document.getElementById("button3").setAttribute("disabled", false);
}
function dataButton2() {
if (document.getElementById("button1").hasAttribute("disabled"))
document.getElementById("button3").removeAttribute("disabled");
}
<button type="button" class="btn btn-primary" id="button1"
onclick="dataButton1(); this.style.visibility='hidden'; this.disabled=true">
Data1
</button>
<button type="button" class="btn btn-primary" id="button2"
onclick="dataButton2();this.style.visibility= 'hidden'; this.disabled=true">
data2
</button>
<button disabled type="button" class="btn btn-primary " id="button3">
chart
</button>

Condense IF Statement As Seems Over Kill

New To JQuery, i have the following code which i think is a bit over kill as all i'm trying to do i match a returned value to a selection of buttons and add/remove a class.
HTML for days of the week buttons
<div class="form-horizontal" id="selectWeekdaysSection">
<div class="form-group">
<div class="col-md-offset-2 col-lg-4">
<button id="mon" name="weekdaysbutton" class="btn btn-default" type="button" value="Mon">Mon</button>
<button id="tue" name="weekdaysbutton" class="btn btn-default" type="button" value="Tue">Tue</button>
<button id="wed" name="weekdaysbutton" class="btn btn-default" type="button" value="Wed">Wed</button>
<button id="thur" name="weekdaysbutton" class="btn btn-default" type="button" value="Thur">Thur</button>
<button id="fri" name="weekdaysbutton" class="btn btn-default" type="button" value="Fri">Fri</button>
<button id="sat" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sat">Sat</button>
<button id="sun" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sun">Sun</button>
</div>
</div>
</div>
Gives this on the site
DataTable data
When i do call and get data back from my DataTable it pre-selects the days from the JSON. I have all this working but as i said seems over kill to have to keep repeating the IF just for a different button especially when i have to do this for days '01 - 31'
Jquery
var selectedDays = modifyRecordData.selectedDays;
var splitSelectedDays = selectedDays.split(',');
splitSelectedDays.forEach(day => {
let val = day.trim();
if(val == 'Mon') {
$('#mon').removeClass('btn-default');
$('#mon').addClass('btn-primary');
}
if (val == 'Tue') {
$('#tue').removeClass('btn-default');
$('#tue').addClass('btn-primary');
}
if (val == 'Wed') {
$('#wed').removeClass('btn-default');
$('#wed').addClass('btn-primary');
}
if (val == 'Thur') {
$('#thur').removeClass('btn-default');
$('#thur').addClass('btn-primary');
}
if (val == 'Fri') {
$('#fri').removeClass('btn-default');
$('#fri').addClass('btn-primary');
}
if (val == 'Sat') {
$('#sat').removeClass('btn-default');
$('#sat').addClass('btn-primary');
}
if (val == 'Sun') {
$('#sun').removeClass('btn-default');
$('#sun').addClass('btn-primary');
}
})
Console.Log of returned data
The technique you want to follow is called Don't Repeat Yourself, or DRY for short.
In this case the day is always the same as the id of the element you want to target, so you can manually build the selector string once from that. You can also use toggleClass() instead of alternate addClass() and removeClass() calls. Try this:
splitSelectedDays.forEach(day => {
let dayName = day.trim().toLowerCase();
$('#' + dayName).toggleClass('btn-default btn-primary');
})

How to change the button text to a number from an array

I'm working on a small project and I have an array with 4 numbers. I want to display them on 4 buttons. I tried this code but it doesn't seem to be working. Do you have any ideas where I could make a mistake ?
<div id="results">
<button type="button" class="btn btn-primary button-result" id="button1">Result</button>
<button type="button" class="btn btn-primary button-result" id="button2">Result</button>
<button type="button" class="btn btn-primary button-result" id="button3">Result</button>
<button type="button" class="btn btn-primary button-result" id="button4">Result</button>
</div>
var rnum1 = generateRandomNumber1();
var rnum2 = generateRandomNumber2();
var rnums = [rnum1, rnum2];
var rnumsSort = rnums.sort(function(a, b) {
return b - a
});
//pass the random numbers to the function
var data = generateRandomOperatorAndCorrectResult(rnumsSort[0], rnumsSort[1]);
//data=["+", [5]]
var operator = data[0];
var corResult = data[1][0][0];
var ranResult = [data[1][0][1], data[1][0][2], data[1][0][3]];
var allResults = data[1][0];
var sortAllResults = allResults.sort(function(a, b) {
return a - b
});
var buttonText = buttonResult();
function buttonResult() {
for (var i = 0; i < sortAllResults.length; i++) {
document.querySelectorAll(".button-result").textContent = sortAllResults[i];
}
}
You're attempting to set the textContent of a NodeList in this line:
document.querySelectorAll(".button-result").textContent= sortAllResults[i];
You need to select the index of the current button:
document.querySelectorAll(".button-result")[i].textContent= sortAllResults[i];
just a small working example how you can fill your Buttons.
const randomNumber = Math.floor(1000 + Math.random() * 9000);
[...myArray] = randomNumber.toString();
const insertResult = (origArray) => {
const myButtons = Array.from(document.getElementsByClassName('button-result'));
origArray.sort((a, b) => b - a);
myButtons.forEach((button, index) => button.textContent = myArray[index]);
};
insertResult(myArray);
<div id="results">
<button type="button" class="btn btn-primary button-result" id="button1">Result</button>
<button type="button" class="btn btn-primary button-result" id="button2">Result</button>
<button type="button" class="btn btn-primary button-result" id="button3">Result</button>
<button type="button" class="btn btn-primary button-result" id="button4">Result</button>
</div>

Calling 2 buttons functions in the same form PHP

I implemented a page with 2 buttons which call 2 different functions on their button clicks. But the any of the buttons are not working. They are just reload the same page. I'll put my code down below.
<form class="form-horizontal" id="add_product_form" method="post">
<script>
function submitForm(action)
{
document.getElementById('add_product_form').action = action;
document.getElementById('add_product_form').submit();
}
</script>
<div class="col-sm-12">
<input type="submit" onclick="return check_add_to_cart();" class="btn btn-danger btn-lg add-to-cart btn-block" value="Add To Cart">
<input type="submit" onclick=onclick="return check_add_to_quote();" class="btn btn-danger btn-lg add-to-quote btn-block" value="Add To quote">
</div>
Any help would be really appreciated. Thank you! Add_to_cart function which is mentioned above the page.
function check_add_to_cart(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
return true
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
function check_add_to_quote(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
return true
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
}
You can do following. Change typesubmit to button And as you already have submitForm() method. Call this method when you want to return true.
Change
<input type="submit" onclick="return check_add_to_cart();" class="btn btn-danger btn-lg add-to-cart btn-block" value="Add To Cart">
<input type="submit" onclick=onclick="return check_add_to_quote();" class="btn btn-danger btn-lg add-to-quote btn-block" value="Add To quote">
To
<input type="button" onclick="return check_add_to_cart();" class="btn btn-danger btn-lg add-to-cart btn-block" value="Add To Cart">
<input type="button" onclick=onclick="return check_add_to_quote();" class="btn btn-danger btn-lg add-to-quote btn-block" value="Add To quote">
And change your js functions to:
function check_add_to_cart(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
//return true
submitForm(""); //you can pass action in this if you want other page
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
function check_add_to_quote(){
var quantity = jQuery('#quantity').val();
var data = jQuery('#add_product_form').serialize();
if(jQuery.isNumeric(quantity) && quantity > 0){
//return true
submitForm(""); //you can pass action in this if you want other page
} else if(quantity < 1) {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be greater than 0.");?>');
return false;
}else {
jQuery('#cart_error').html('<?=display_error_str("Quantity must be a number.");?>');
return false;
}
}
And remove submitForm() definition between html and add it to script block

Categories

Resources