Change text of button if it has a display of none? - javascript

I have a list of of checkboxes that are being used a search fields for a database. When someone clicks a checkbox it will show a button with the text from the label of that checkbox. However, I need that button to be have empty text when it is not visible (in the case of someone clicking the checkbox to hide the button).
Here's my code:
$(document).ready(function() {
$('#locationAll').click(function() {
var value = $('#locationAll').parent().text();
$('#location-all-button').html(value + " ×").toggle('fast');
});
});
$(document).ready(function() {
$('.search-popup').click(function() {
$(this).hide('fast');
});
if ($('.search-popup').css('display') == 'none') {
$(this).text("");
};
});
button {
background-color: lightgray;
border-radius: 20px;
display: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="checkbox" value="all" id="locationAll" />All
</label>
<br>
<br>
<button class="search-popup btn" id="location-all-button"></button>
For some reason I can't make the button stay hidden before the checkbox on the example here but that isn't a problem in my full code. if you need more info let me know I might have missed something.

Ok so I changed a few things. I made this work for any checkbox that follows the naming scheme I made really quickly. The scheme is the id of the button = the "button-"+id. Also I hiding all buttons with a class right form the start to set their default state.
$(document).ready(function()
{
\\change to allow all checkboxes to trigger
$('input[type=checkbox]').click(function()
{
\\change the id so it match a button when add "button-" to the start
\\this allows me to target the matching button with any chechbox
$('#button-'+$(this).attr('id')).toggle('fast');
});
$('.search-popup').click(function()
{
$(this).hide('fast');
\\ sets the check box to false so it not checked when you close it
$("#"+$(this).text().replace("  ×","")).attr('checked', false);
});
\\hides all buttons right form the start
$('button.search-popup').each(function()
{
$(this).hide();
});
});
<label>
<input type="checkbox" value="all" id="All" />All
</label>
<br>
<br>
<button class="search-popup btn" id="button-All">All  ×</button>
now if you want to create and remove buttons when a checkbox has changed state you can add an if state meant in that checks to see if the button with the matching id exists or not,!$(tag).size().

Related

handing focus from input element to button

On clicking a button, I want an input element to get focus. When the input element looses focus, I want the button to receive focus. Here is a simple example.
<body>
<button id="b1"
onclick="document.getElementById('i1').focus();">1</button>
<input id="i1" type="text"
onblur="document.getElementById('b1').focus();"/>
<button id="b2"
onclick="document.getElementById('i2').focus();">2</button>
<input id="i2" type="text"
onblur="document.getElementById('b2').focus();"/>
</body>
When I click any of the buttons, the input element gets focus. This works as desired. When I leave any of the two inputs by clicking on the canvas, the focus does not go to the button. This is my main issue.
When I leave the first input with tab, all browsers pass the focus to the first button. But when I leave the second button with tab, only firefox passes the focus to the second button. Chrome and opera don't show a focus. I am puzzled as to why the second button is treated differently.
You don't need to use JavaScript. HTML and CSS is enough. Use label tag and convert it's look like button. :)
label.btn{
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
padding: 1px 6px;
border:1px solid
}
<label class="btn" for="i1" id="b1">1</label>
<input id="i1" type="text"/>
<label class="btn" for="i2" id="b2">2</label>
<input id="i2" type="text" />
If you add a :focus style in your CSS, you can see it works fine. I've moved your JS out of the HTML markup for visibility and added some listeners for keyboard users.
Caution: Forcing focus back to the button interferes with the page's natural flow, so I probably wouldn't advise unless you have it attached to some input validation that fires when needed; else, how do keyboard users move to the next element?
const inputOne = document.getElementById('i1');
const btnOne = document.getElementById('b1');
const inputTwo = document.getElementById('i2');
const btnTwo = document.getElementById('b2');
// Listen for click to button one
btnOne.addEventListener('click', function() {
inputOne.focus();
})
// Make sure we listen for keyboard users
btnOne.addEventListener('keydown', function(event) {
if(event.keyCode === 90) {
inputOne.focus();
}
})
// Leaving input one
inputOne.addEventListener('blur', function() {
btnOne.focus();
})
// Listen for click to button two
btnTwo.addEventListener('click', function() {
inputTwo.focus();
})
// Make sure we listen for keyboard users
btnTwo.addEventListener('keydown', function(event) {
if(event.keyCode === 90) {
inputTwo.focus();
}
})
// Leaving input two
inputTwo.addEventListener('blur', function() {
btnTwo.focus();
})
:focus {
border: 1px solid red;
}
<button id="b1">1</button>
<input id="i1" type="text"/>
<button id="b2">2</button>
<input id="i2" type="text" />

How to slide to particular HTML element using javascript?

How to set focus and slide down to the html when button is clicked . How to slide to particular HTML element using javascript?
p:focus, p:active {
color: green;
}
p {
min-height: 250px;
}
<body>
<input type="button" onclick="getfocus()" value="Get focus">
<input type="button" onclick="losefocus()" value="Lose focus">
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p id="myAnchor">Click the buttons to give focus and/or remove focus from the link above.</p>
<script>
function getfocus() {
document.getElementById("myAnchor").focus();
}
function losefocus() {
document.getElementById("myAnchor").blur();
}
</script>
</body>
Adding tabindex="0" to p#myAnchor solves the issue
tabindex="0" means that the element should be focusable in sequential
keyboard navigation, after any positive tabindex values and its order
is defined by the document's source order.
function getfocus() {
document.getElementById("myAnchor").focus();
}
function losefocus() {
document.getElementById("myAnchor").blur();
}
p:focus,
p:active {
color: green;
}
p {
min-height: 200px;
}
<input type="button" onclick="getfocus()" value="Get focus">
<input type="button" onclick="losefocus()" value="Lose focus">
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<p tabindex="0" id="myAnchor">Click the buttons to give focus and/or remove focus from the link above.</p>
If by get focus you mean get there:
function getfocus() {
document.getElementById("myAnchor").scrollIntoView();
}
and if by loose focus if you mean going back to the top:
function looseFocus(){
window.scrollTo(0, 0);
}
but <p> is not focusable.
If you really want focus you need an anchor <p><a id="myAnchor" href="#">Click the buttons to give focus and/or remove focus from the link above.</a></p>

Toggle border around checkbox label on click using jquery or javascript

I have an app that prints out the contents of a list (using Python/Flask). Each item is a checkbox input, however I've hidden the checkboxes with CSS. Visually I'm trying to make it so when the user clicks the label text, the item is marked checked (hidden) and a border shows up around the text to confirm.
Once all selections have been made, the submit button sends everything back to Flask for processing. The functionality is all there and working. I am just having the hardest time with the visual aspect of toggling the border.
HTML (There are actually two columns like this but for simplicity I'll just put one):
<form action="/choices" method="post">
<div class="left-col-results">
{% for i in range(0, toplen) %}
<label class="left-label-check">
<input class="form-check-input-left" type="checkbox"
name="checked" value="{{ top[i] }}">{{ top[i] }
</label>
<br>
{%endfor%}
</div>
The main problem seems to be the following jquery. I found this on another post and it does what I want visually, however the e.preventDefault kills the checkbox functionality:
$('.left-label-check').on('click', function(e){
e.preventDefault();
$(this).toggleClass('text-border');
});
If I remove it:
$('.left-label-check').on('click', function(){
$(this).toggleClass('text-border');
});
It no longer adds the border! Any help is greatly appreciated.
****UPDATE:
Finally got it working. I didn't have the correct ajax link.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
And used this syntax to toggle the class:
<label for="idl{{i}}" class="choice">{{ top[i] }}</label>
$(document).ready(function(){
$('label.choice').click(function(){
$(this).toggleClass("text-border");
});
});
Now it works as planned.
Because you hide input so you can put tags in different way.
If you put <label> after <input> and use for=<input_id> in label then you don't need JS and you can do it only with CSS:
input:checked + label {border: 1px solid red}
Code
from flask import Flask, render_template_string
app = Flask(__name__)
#app.route('/')
def index():
return render_template_string('''
<style>
input:checked + label {border: 1px solid red}
</style>
<form action="/choices" method="post">
<div class="left-col-results">
{% for item in top %}
<input id="id{{ loop.index }}" class="form-check-input-left" type="checkbox" name="checked" value="{{ item }}">
<label for="id{{ loop.index }}" class="left-label-check">{{ item }}</label>
<br>
{%endfor%}
</div>
</form>''', top=['a', 'b', 'c'])
app.run()
I think maybe this is what you are looking for, although this is the VanillaJS way of doing it:
var leftLableCheck = document.querySelector('.left-label-check');
var checkbox = document.querySelector('[type=checkbox]');
leftLableCheck.addEventListener('click', function() {
this.setAttribute('class', 'text-border left-label-check')
});
checkbox.addEventListener('click', function(e) {
e.stopPropagation();
});
Basically, we grab the parent label element, and the child checkbox element first:
var leftLableCheck = document.querySelector('.left-label-check');
var checkbox = document.querySelector('[type=checkbox]');
Then, we attach 'click' event listeners to each, but we stop the propagation of the click event on the checkbox itself so it doesn't bubble back up and run the code in our label listener twice:
leftLableCheck.addEventListener('click', function() {
this.setAttribute('class', 'text-border left-label-check')
});
checkbox.addEventListener('click', function(e) {
e.stopPropagation();
});
Here's a link to a CodePen where you can see it working. I don't hide the checkbox, that way you can see it get's checked and unchecked.
Button Text Box CodePen

How to use jQuery overlay to get radio buttons to the popup window?

I am following this tutorial and designed and alert window(including online demo),
http://jquerytools.org/demos/overlay/modal-dialog.html
I could modify the source code and added radio buttons to the alert message.Source code is given bellow(you don't have to go through the whole code.Just see the place where I have added radio buttons and place where I access the value of the radio button),
<!DOCTYPE html>
<html>
<!--
This is a jQuery Tools standalone demo. Feel free to copy/paste.
http://flowplayer.org/tools/demos/
Do *not* reference CSS files and images from flowplayer.org when in
production Enjoy!
-->
<head>
<title>jQuery Tools standalone demo</title>
<!-- include the Tools -->
<script src="jquery.tools.min.js"></script>
<!-- standalone page styling (can be removed) -->
<link rel="shortcut icon" href="/media/img/favicon.ico">
<link rel="stylesheet" type="text/css"
href="/media/css/standalone.css"/>
<style>
.modal {
background-color:#fff;
display:none;
width:350px;
height:250px;
padding:15px;
text-align:left;
border:2px solid #333;
opacity:0.8;
-moz-border-radius:6px;
-webkit-border-radius:6px;
-moz-box-shadow: 0 0 50px #ccc;
-webkit-box-shadow: 0 0 50px #ccc;
}
.modal h2 {
background:url(/media/img/global/info.png) 0 50% no-repeat;
margin:0px;
padding:10px 0 10px 45px;
border-bottom:1px solid #333;
font-size:20px;
}
</style>
</head>
<body><!-- the triggers -->
<p>
<button class="modalInput" rel="#yesno">Yes or no?</button>
<button class="modalInput" rel="#prompt">User input</button>
</p>
<!-- yes/no dialog -->
<div class="modal" id="yesno">
<h2>This is a modal dialog</h2>
<p>
You can only interact with elements that are inside this dialog.
To close it click a button or use the ESC key.
</p>
<!-- yes/no buttons -->
<p>
<button class="close"> Yes </button>
<button class="close"> No </button>
</p>
</div>
<!-- user input dialog -->
<div class="modal" id="prompt">
<h2>This is a modal dialog</h2>
<p>
You can only interact.
</p>
<!-- input form. you can press enter too -->
<form>
//Added radio buttons
<input type="radio" name="sex" value="male" id="male"> Male<br />
<input type="radio" name="sex" value="female" id="female"> Female<br />
<button type="submit">Submit</button>
</form>
<br />
</div>
<script>
$(document).ready(function() {
var triggers = $(".modalInput").overlay({
// some mask tweaks suitable for modal dialogs
mask: {
color: '#ebecff',
loadSpeed: 200,
opacity: 0.9
},
closeOnClick: false
});
var buttons = $("#yesno button").click(function(e) {
// get user input
var yes = buttons.index(this) === 0;
// do something with the answer
triggers.eq(0).html("You clicked " + (yes ? "yes" : "no"));
});
$("#prompt form").submit(function(e) {
// close the overlay
triggers.eq(1).overlay().close();
// get user input
var input = $("input", this).val(); // this input value always return 'male' as the output
// do something with the answer
triggers.eq(1).html(input);
// do not submit the form
return e.preventDefault();
});
});
</script>
</body>
</html>
This demo has two alert windows. I am talking about the alert message which has the text input.In my example I have remove text input and added two radio buttons.
But when I click the 'submit' button It always return me 'male' as the output
Can anyone please help me to solve this problem? I need to get the output of the radin buttons to variable 'input'
Use this to pop up the box. In the HTML keep the radio button.
<table style="width: 100%; border: 0px;" cellpadding="3" cellspacing="0">
<tr>
<td class="web_dialog_title">Email this Article</td>
<td class="web_dialog_title align_right">
Close
</td>
</tr>
<TR><TD>
Use radio button.
</TD></TR>
</table>
<script type="text/javascript">
$(document).ready(function ()
{
$("#btnShowSimple").click(function (e)
{
ShowDialog(false);
e.preventDefault();
});
$("#btnClose").click(function (e)
{
HideDialog();
e.preventDefault();
});
$(document).keyup(function(e) {
if (e.keyCode == 27) {
HideDialog(); }
});
});
function ShowDialog(modal)
{
$("#overlay").show();
$("#dialog").fadeIn(300);
if (modal)
{
$("#overlay").unbind("click");
}
else
{
$("#overlay").click(function (e)
{
HideDialog();
});
}
}
function HideDialog()
{
$("#overlay").hide();
$("#dialog").fadeOut(300);
}
you changed text type input with radio type input . so you must change
var input = $("input", this).val();
with this one
var input = $("input:checked", this).val();
perdickss provides a very good answer for this example.
But that will not work if you have multiple inputs in the page. So you should use something like this:
var input = $("input[name=FIELD_NAME]:checked", this).val();
Where FIELD_NAME is the name you have for the inputs you want to check. In this case the code would look like:
var input = $("input[name=sex]:checked", this).val();
As you wrote in your code:
<form>
<input type="radio" name="sex" value="male" id="male"> Male<br />
<input type="radio" name="sex" value="female" id="female"> Female<br />
<button type="submit">Submit</button>
</form>
There are two input fields in your #prompt form, so when you get value with this code:
var input = $("input", this).val();
You will always get value of first matched element (which is male).
All you have to do is specify checked input using :checked selector, I suggest you additionally to add input's name:
var input = $("input[name=sex]:checked", this).val();

Javascript OnMouseOver and Out disable/re-enable item problem

I wanted to have some radio buttons that disabled when the mouse went over and enabled again when it went out (just for fun).
<form>
<input type="radio" name="rigged" onMouseOver="this.disabled=true" onMouseOut="this.disabled=false">
</form>
When the mouse goes on it it does what it should be when it goes back off the button wont re-enable. Also, how do I make it default to enable so that when you refresh the page it doesn't stay disabled.
Thanks in advance.
You could achieve the same effect by wrapping your radio buttons in a div tag and setting the onmouseover and onmouseout events.
<div id="container" onmouseout="this.disabled=false" onmouseover="this.disabled=true">
<input name="rigged" type="radio">
</div>
The above solution only works in IE, for a solution that works in FireFox do the following.
<script type="text/javascript">
function toggleDisabled(el) {
try {
el.disabled = el.disabled ? false : true;
}
catch(E){
}
if (el.childNodes && el.childNodes.length > 0) {
for (var x = 0; x < el.childNodes.length; x++) {
toggleDisabled(el.childNodes[x]);
}
}
}
</script>
*This javaScript function was borrowed from here: Enable or disable DIV tag and its inner controls using Javascript
<div id="container" onmouseover="toggleDisabled(this)" onmouseout="toggleDisabled(this)">
<input name="rigged" type="radio">
</div>
The inputs do not fire the mouseout events because they are disabled.
So you have to wrap it in a div and catch the div's events.
If you want pure javascript, use Phaedrus's example "toggleDisabled" script.
If you want jQuery and not-so-newbie friendly:
<html>
<head>
<title>Page</title>
<script src="jquery-1.3.2.min.js"></script>
<script>
$(function() {
function toggleDisabled(d) {
var disable = d;
this.disableChildren = function() { $(this).children().each(function() { this.disabled = d; }); }
}
$("form .radios").hover(new toggleDisabled(true).disableChildren, new toggleDisabled(false).disableChildren);
});
</script>
</head>
<body>
<form>
<div class="radios">
<input type="radio" name="rigged" value="1"/> Item One<br />
<input type="radio" name="rigged" value="2"/> Item Two<br />
<input type="radio" name="rigged" value="3"/> Item Three<br />
<input type="radio" name="rigged" value="4"/> Item Four
</div>
</form>
</body>
</html>
I had a similar problem with wanting an image to expose, and then go regular when the mouse left the image. I was using jQuery and ended up hooking into mouseenter and mouseout, instead of the events you are using. You might want to try those.
$('#rigged').mouseenter(function() {
$(this).disabled = true;
}).mouseout(function() {
$(this).disabled = false;
});
Something like that.
Again, that's using jQuery.
(You'll have to give the input radio button the id 'rigged')
I think when it's becoming disabled, it's not going to fire any events.
You could try a few things.
On mouseover, make an invisible div overlay the radio box. This will make it impossible to use. Then on the mouseout of this invisible div, remove the div.
You could play with mouse x and y coords, and see if they overlay your radio elements. This isn't an optimal solution though.
Markup for the first, in jQuery, would go something like this
$('#rigged').after('<div id="overlay" style="display: none;"></div>'); // make this the size of the radio button and/or associated label (if present). also, maybe with absolute and relative positioning, make sure it will overlap the radio element
$('#rigged').bind('mouseover', function() {
$('#overlay').show();
});
$('#overlay').live('mouseout', function() {
$(this).hide();
});
You'll need to adapt this to work with multiple elements.

Categories