HTML/JQuery: Disable span / button click (greying it out and disable click) - javascript

I have two spans that display certain information upon click, and I was unsure how I can grey out the spans to look like a disabled button when the other one is clicked. My code is below. I thought I could do something like $("#toggle-odd").attr("disabled", true") or $("toggle-odd").unbind("click") but neither seemed to give me the desired result.
$("document").ready(function(){
$("#odd").hide();
$("#even").hide();
});
$("#toggle-odd").click(function(){
$("#even").hide();
$("#odd").toggle();
});
$("#toggle-even").click(function(){
$("#odd").hide();
$("#even").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<span class="btn btn-contrast" style="background-color: green" href="#" id="toggle-odd"> Show Odd Objects </span>
<span class="btn btn-contrast" style="background-color: red" href="#" id="toggle-even"> Show Even Objects </span>
<p id="odd">
Odd
</p>
<p id="even">
Even
</p>

The span tag is made to display text. Here you should use buttons. If you want to disable the other button "graphically", just add a class ( I named it disabled). If you want to really disable it, add $("#your-button").attr("disabled","disabled");
In the following example I made sure that we can reactivate a button but if you want to keep it deactivated, you just have to extract the code of the first condition.
$("document").ready(function(){
$("#odd").hide();
$("#even").hide();
});
$("#toggle-odd").click(function(){
if($("#odd").css("display") == "none"){
$("#toggle-even").attr("disabled","disabled");
$("#toggle-even").addClass("disabled");
}else{
$("#toggle-even").removeAttr("disabled");
$("#toggle-even").removeClass("disabled");
}
$("#even").hide();
$("#odd").toggle();
});
$("#toggle-even").click(function(){
if($("#even").css("display") == "none"){
$("#toggle-odd").attr("disabled","disabled");
$("#toggle-odd").addClass("disabled");
}else{
$("#toggle-odd").removeAttr("disabled");
$("#toggle-odd").removeClass("disabled");
}
$("#odd").hide();
$("#even").toggle();
});
.disabled{
background-color: grey;
}
#toggle-odd{
background-color: green
}
#toggle-even{
background-color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<button class="btn btn-contrast" id="toggle-odd"> Show Odd Objects </button>
<button class="btn btn-contrast" id="toggle-even"> Show Even Objects </button>
<p id="odd">
Odd
</p>
<p id="even">
Even
</p>

Related

How to trigger click event with enter button?

I am building a very basic magic 8 ball type 'game' using vanilla javascript. I have a text field (for a user question) and a submit button underneath. At present, I have it working fine with a event listener for the submit button but am trying to also get the same result if a user was to click enter.
I saw on w3s that you can trigger a button click upon enter, as below...
// Get the input field
var input = document.getElementById("myInput");
// Execute a function when the user presses a key on the keyboard
input.addEventListener("keypress", function(event) {
// If the user presses the "Enter" key on the keyboard
if (event.key === "Enter") {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
});
...but I can't seem to translate that into my own project. HTML and JS for my project below; I am trying not to use nested functions at the moment just to help with my understanding (as advised by my course mentor).
JavaScript
let question = document.querySelector('#userQuestion');
let button = document.querySelector('#shakeButton');
let answer = document.querySelector('#answer');
let options = [
'It is certain.',
'Signs point to yes.',
'Concentrate and ask again.',
'My sources say no.',
]
// Generate a random number
function generateAnswer() {
let index = Math.floor(Math.random() * 4);
let message = options[index];
answer.textContent = message;
answer.style.fontSize = '18px';
setTimeout(timeOut, 3000);
};
// Timeout function
function timeOut() {
answer.textContent = '8';
answer.style.fontSize = '120px';
};
// Enter button trigers click event
function enterButton (event) {
if (event.key === "Enter") {
event.preventDefault();
button.click();
}
};
//Event listener for button click
button.addEventListener('click', generateAnswer);
question.addEventListener("keypress", enterButton);
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Magic 8 Ball, ask it anything and it will answer.">
<!-- Stylesheet & Font Awesome Links -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Orbitron:wght#800&family=Press+Start+2P&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css">
<link rel="stylesheet" href="assets/css/style.css" type="text/css">
<!-- Stylesheet & Font Awesome Links End -->
<title>Magic 8 Ball</title>
</head>
<body>
<nav class="navbar">
<div class="container-fluid">
<a class="navbar-brand ms-auto" href="#">dc games</a>
</div>
</nav>
<!-- Header -->
<header class="heading">
<h1>The Magic 8 Ball</h1>
<p>Shake the Magic 8 Ball and it will answer your question.</p>
</header>
<!-- Header End-->
<!-- Magic 8 Ball -->
<div class="ball-black">
<div class="ball-white">
<p id="answer">8</p>
</div>
</div>
<!-- Magic 8 Ball End -->
<!-- User Question -->
<div class="user-input">
<input type="text" class="form-control mb-2 mr-sm-2" id="inlineFormInputName2 userQuestion" placeholder="What is your question?" required>
<button type="button" class="btn" id="shakeButton">Shake!</button>
</div>
<!-- User Question -->
<!-- Footer -->
<footer>
<div class="copyright fixed-bottom">
<p>Copyright © dc games 2022</p>
</div>
</footer>
<!-- Footer End -->
<!-- JavaScript Links -->
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script type="text/javascript" src="assets/js/script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<!-- JavaScript Links End -->
</body>
</html>
You cannot have multiple Ids on a single DOMElement. If you remove inlineFormInputName2 from the id of the user question, your code will work.
You can only have multiple identifiers for a class.
classes are used for formatting with css and Ids to specifically identify an element.

Text input doesnt work inside Bootstrap popover

I have the following HTML to open a popup. Here the button works fine. It is clickable, but not an input. The text input seems to have a hidden disabled=true, but it's not.
What could be the problem?
const pop = new bootstrap.Popover(document.querySelector('[data-bs-toggle="popover"]'));
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<img src="https://via.placeholder.com/100"
data-bs-toggle="popover"
data-bs-offset="0,14"
data-bs-placement="top"
data-bs-html="true"
data-bs-content="<div class='input-group-sm'>
<input type='text' class='form-control' placeholder='https://...'/>
<button class='btn btn-primary'>Save</button></div>"
>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>

Check the state of buttons-checkbox

I want to make a checkbox that looks like a button: when it is checked, the button looks pressed; when it is unchecked, the button looks unpressed.
As I use bootstrap, naturally I think of using data-toggle="buttons-checkbox". But It does not seem very practical to verify the state of the checkbox. For example, .prop('checked') does not seem to work in the following code.
$('#input-checkbox').click(function () {
if ($("#input-checkbox").prop('checked')) {
alert("yes");
} else {
alert("no");
}
});
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="btn-group" data-toggle="buttons-checkbox">
<button type="button" class="btn btn-default active" id="input-checkbox">INPUT</button>
</div>
</body>
Does anyone know what's wrong there?
Add value attribute to your button. I changed btn-default to btn-primary and added a normal button on the side to state the difference.
$('#input-checkbox').click(function () {
if ($("#input-checkbox").attr('value')=="checked"){
$("#input-checkbox").attr('value','notchecked');
$("#input-checkbox").removeClass('active');
}
else {
$("#input-checkbox").attr('value','checked');
$("#input-checkbox").addClass('active');
}
});
.btn:focus,.btn:active {
outline: none !important;
}
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="btn-group" data-toggle="buttons-checkbox">
<button type="button" class="btn btn-primary active" value="checked" id="input-checkbox">INPUT</button>
<button type="button" class="btn btn-primary"> NPUT</button>
</div>
</body>

Jquery replace text without erasing the list

jQuery(document).ready(function($){
$("#firstshow .dropdown-menu li a").click(function(){
$('#firstshow button b').html(this);
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="firstshow">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown"><b>36</b>
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>12
</li>
<li>24
</li>
<li>36
</li>
</ul>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
The main idea is to make this code like the classic html select.
The reason I do this is because I didn't figure out how to change the blue hover in option menu.
Run code snippet and click the li content. As you see the next time the content is removing from my list and that is my problem. How can I keep the li data and not removing in my list?
Your inner-most statement should be:
$('#firstshow button b').text($(this).text());
The way you had it you used the a element object as the HTML code for the buttons text, but you don't want to assign the element, but its text. So:
Assign $(this).text()
Assign it with text() not with html() -- better practice.
It's about the part .html(this) in your code. The this variable is a reference to the dom object that is being clicked. When you set this as the html of the displayed select value, it moves the dom object and replaces whatever was displayed.
To overcome this set the displayed value to the text value of the element that is being clicked.
jQuery(document).ready(function($){
$("#firstshow .dropdown-menu li a").click(function(){
$('#firstshow button b').html($(this).text());
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="firstshow">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown"><b>36</b>
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>12
</li>
<li>24
</li>
<li>36
</li>
</ul>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

How to reset a jQuery UI slider to null with multiple jQuery libraries

I am having trouble resetting jQuery UI sliders.
I get this error:
MyProject.OrderInfo.Search.js:187 Uncaught TypeError: $(...).slider is not a function
I think our problem has something to do with having multiple jQuery/Javascript libraries, stepping over each other, but I am uncertain. Everything my team has been trying has not worked. We simply need to reset our sliders to have NULL values. We need to use NULL, so that we know the user has not touched the slider. That way, we can exclude it from our API call parameters.
How can I reset the slider values to NULL?
Here is what the code looks like:
[OrderInfo.cshtml] (script area, top section):
<link rel="stylesheet" href="~/Content/order.css" />
<link rel="stylesheet" href="~/Content/bootstrap.css" />
<link rel="stylesheet" href="~/Content/backgrid-paginator.css" />
<link rel="stylesheet" href="~/Content/backgrid-filter.css" />
<link rel="stylesheet" href="~/Content/backgrid.css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="~/Scripts/underscore.js"></script>
<script src="~/Scripts/jquery-2.2.0.js"></script>
<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="~/Scripts/backbone.js"></script>
<script src="~/Scripts/backbone.paginator.js"></script>
<script src="~/Scripts/backgrid.js"></script>
<script src="~/Scripts/backgrid-paginator.js"></script>
<script src="~/Scripts/backgrid-filter.js"></script>
<script src="~/Scripts/backgrid-select-filter.js"></script>
<script src="~/Scripts/MyProject.OrderInfo.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="~/Scripts/jquery.ui.touch-punch.js"></script>
[OrderInfo.cshtml] (body):
<div class="col-sm-7" id="divslider">
<div class="row filterHeader">
<div class="col-md-3 paddingZero">
<b>Tuition and Fees</b>
</div>
<div class="col-md-2 paddingZero">
<div class="input-group">
Min:
<span class="input-group-addon" id="MinOrderPrice"> </span>
</div>
</div>
<div class="col-md-5">
<div id="SliderOrderPrice"></div>
</div>
<div class="col-md-2 paddingZero">
<div class="input-group">
Max:
<span class="input-group-addon" id="MaxOrderPrice"> </span>
</div>
</div>
</div>
<!-- MORE HTML BODY CODE HERE, UI/search elements, DIVS, ETC ETC -->
<div class="row filterHeader">
<div class="col-md-3 paddingZero">
</div>
<div class="col-md-2 paddingZero">
</div>
<div class="col-md-4">
</div>
<div class="col-md-3 paddingZero">
<button class="btn btn-info" id="btnSearch" type="button">Search</button>
<button class="btn btn-primary" id="btnReset" type="button" style="min-width:71px">Reset</button>
</div>
</div>
</div>
<!-- END OF [OrderInfo.cshtml] BODY, ** NOTICE THE BOTTOM HAS A JS SCRIPT, EEEK!! ** -->
<script src="~/Scripts/MyProject.OrderInfo.Search.js"></script>
[MyProject.OrderInfo.Search.js] (a .JS file for searching Orders REST API):
//Declare slider variables as null and assign only in change function, to distinguish 'dirty' slider from a 'clean' slider
var minorderprice;
var maxorderprice;
//Tution and Fees slider
$("#SliderOrderPrice").slider({
range: true,
min: 0,
max: 50000,
values: [0, 50000],
step: 500,
slide: function (event, ui) {
$("#MinOrderPrice").html("$" + ui.values[0].toLocaleString());
if (ui.values[1] == 50000) {
$("#MaxOrderPrice").html("> $50,000")
}
else ($("#MaxOrderPrice").html("$" + ui.values[1].toLocaleString()))
},
change: function (event, ui) {
minorderprice = ui.values[0];
maxorderprice = ui.values[1];
}
});
$("#MinOrderPrice").html("$ 0");
$("#MaxOrderPrice").html("> $50,000");
$("#SliderOrderPrice").draggable(); //this is a hack to make the slider responsive on mobile devices (see touch-punch.js)
// Get the values of search checkboxes and sliders, after search button click
$("#btnSearch").click(function () {
//do a bunch of nifty things to produce a dynamic URL string, for REST API calls here. This works fine and is left out on purpose.
});
$("#btnReset").click(function () {
$('input:checkbox').removeAttr('checked'); //clear all checkboxes
$('#orderTerritory').prop('selectedIndex',0); //reset State/Territory dropdown to 'All States'
RenderJSGrid(); //re-draw grid
//how to reset slider values here?
$("#SliderOrderPrice").slider('values', 0, 50000); //this throws the error like the slider doesnt exist?
$("#SliderOrderPrice").slider('values', null, null); //would this work?
});
Notice there are references to:
<script src="~/Scripts/jquery-2.2.0.js"></script>
<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
We have to do this because our BackgridJS implementation uses jQuery 2.2.
The sliders want to use 'jquery-ui.js', which I believe depends upon 'jquery-1.10.2.js'.
When the user clicks the Reset button, the error occurs and javascript acts like the slider isn't loaded. But it is, I can see it working in the UI. Could it be that the Reset button event needs to move somewhere else?
Any ideas? Help?
UPDATE #1:
I tried #Noctane's suggestion, but I still get the same error, no matter where I put the Reset function. I can put it inline, I can put it in other scripts but it just never works unfortunately.
Here is what I tried:
<link rel="stylesheet" href="~/Content/order.css" />
<link rel="stylesheet" href="~/Content/bootstrap.css" />
<link rel="stylesheet" href="~/Content/backgrid-paginator.css" />
<link rel="stylesheet" href="~/Content/backgrid-filter.css" />
<link rel="stylesheet" href="~/Content/backgrid.css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="~/Scripts/underscore.js"></script>
<script src="~/Scripts/backbone.js"></script>
<script src="~/Scripts/backbone.paginator.js"></script>
<script src="~/Scripts/backgrid.js"></script>
<script src="~/Scripts/backgrid-paginator.js"></script>
<script src="~/Scripts/backgrid-filter.js"></script>
<script src="~/Scripts/backgrid-select-filter.js"></script>
<script src="~/Scripts/MyProject.OrderInfo.js"></script>
<script src="~/Scripts/jquery.ui.touch-punch.js"></script>
I have prepared a demo using jsFiddle, that uses jquery UI while utilizing both jquery v2.2.0 and jquery version 1.10.2, please have a look, you will see that as you move the slider it will set its changed value to the console, when you click reset it will set the slider to null.
See DEMO
You can achieve this with the following code:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" />
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<style>
#resetButton {
margin-top: 15px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
$( "#sliderTest" ).slider({
change: function( event, ui ) {
var s = ui.value;
console.log(s);
}
});
$("#resetButton").button({
icons: {
primary: "ui-icon-refresh"
}
});
$("#resetButton").click("click", function(event){
var s = $("#sliderTest").slider("value", null);
console.log(s);
});
</script>
<div id="sliderTest"></div>
<button id="resetButton">Reset</button>
You may need to re-arrange your includes in your application to get it to work. If you re-arrange the ones in the fiddle you will see the error you are getting, if you then switch them back to the way I have them arranged you will see it work.

Categories

Resources