jQuery click event only working after moving the mouse - javascript

I'm getting close to desperate here but I can't seem to find any solution to this. I basically have a problem with a click event that somehow acts as a drag event. Which is odd because, as far as I can tell, it really shouldn't.
Let me explain what's what. I have these simple radio buttons:
<div class="fruitButtons">
<input type="radio" name="radio" id="Apple">
<label for="Apple">Apple</label>
<input type="radio" name="radio" id="Banana">
<label for="Banana">Banana</label>
<input type="radio" name="radio" id="Citron">
<label for="Citron">Citron</label>
</div>
<br><b>selected:</b>
<div class="status">none</div>
I use jQuery UI to transform these regular buttons into a nice looking buttonset via $(".fruitButtons").buttonset();.
Now I need the possibility to reset the buttonset, i.e. to uncheck all buttons at once. Since I don't want a separate reset button for that, I need the reset to happen when you click on an already checked button. To me, this is the most intuitive way to handle these radio buttons.
This is the (obviously simplified) way it's supposed to work:
$(function() {
$(".fruitButtons").buttonset();
var uncheck = apple = banana = citron = 0;
$(".fruitButtons label").click(function(){
var name = $(this).text();
// see if button was previously checked
// if yes set var 'uncheck' to 1
if ((name == "Apple") && (apple)) uncheck = 1;
if ((name == "Banana") && (banana)) uncheck = 1;
if ((name == "Citron") && (citron)) uncheck = 1;
apple = banana = citron = 0;
if (!uncheck) {
if (name == "Apple") apple = 1;
if (name == "Banana") banana = 1;
if (name == "Citron") citron = 1;
// display name of currently checked button
$(".status").text(name);
}
else {
// unchecking the hidden input element
$(this).prev().prop("checked", false);
// resetting the buttonset to its initial state
$(this).parent().buttonset("refresh");
$(".status").text("none");
uncheck = 0;
}
});
});
Check out the Fiddle: http://jsfiddle.net/6yx0rqjf/6/
But here's the problem: The unchecking process does not work properly. In fact, it only works when you actually drag the mouse while clicking, i.e. if you move the mouse a little while the mouse button is depressed.
Updating the $(".status") part works perfectly every time you click the button, but unchecking it is only succesful if you move the mouse a little.
How is this possible? Is this a bug? I was able to reproduce this behavior on Firefox 40.0.3 and Chrome 45.0.2454.85. I also found this unresolved question that may be somehow related:
jQuery click event only working after moving the mouse in Chrome
So, can anyone help me fix this? Is that even possible?

I think the problem is that you're putting the click handler on the label, not the button itself. I moved it to the button, and adjusted the code, and it works correctly.
$(function() {
var uncheck = apple = banana = citron = 0;
$(".fruitButtons").buttonset();
$(".fruitButtons :radio").click(function(){
var name = $(this).next("label").text();
// see if button was previously checked
// if yes set var 'uncheck' to 1
if ((name == "Apple") && (apple)) uncheck = 1;
if ((name == "Banana") && (banana)) uncheck = 1;
if ((name == "Citron") && (citron)) uncheck = 1;
apple = banana = citron = 0;
if (!uncheck) {
if (name == "Apple") apple = 1;
if (name == "Banana") banana = 1;
if (name == "Citron") citron = 1;
// display name of currently checked button
$(".status").text(name);
}
else {
// unchecking the hidden input element
$(this).prop("checked", false);
// resetting the buttonset to its initial state
$(this).button("refresh");
$(".status").text("none");
uncheck = 0;
}
});
});
FIDDLE

Related

Uncheck a checkbox in dat.gui

When I change the option of a dropdown menu, I want all the checkboxes to be unchecked. Here's the code that I put inside a function that's called when the dropdown menu changes:
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == "checkbox") {
inputs[i].checked = false;
}
}
This does indeed uncheck the checkbox. However, to recheck the checkbox, it takes two clicks. It appears that dat.gui still thinks the checkbox is checked, so it takes one click to uncheck it, and one more to check it.
How do I make dat.gui update the checkboxes?
Edit: Here's the current state of the problem.
gui = new dat.GUI;
controllers = [];
var menu = {
'This is an example': false,
}
controllers[0] = gui.add(menu, 'This is an example').onFinishChange(
function(value) {console.log('example');} ).listen();
menu['This is an example'] = false;
With this code, the checkbox is unchecked, due to the .listen() call and setting the variable to false. However, it still takes two clicks for the check to show--one to "uncheck" the checkbox, and one to check it.
I've recently come across the same issue with having to click the checkbox twice to get the proper behavior, so here's what worked for me and will hopefully spare other readers a few minutes of head-scratching:
// the usual
var menu = { "foo":false };
// store this reference somewhere reasonable or just look it up in
// __controllers or __folders like other examples show
var o = menu.add(menu, "foo").onChange(function() { });
// some later time you manually update
o.updateDisplay();
o.__prev = o.__checkbox.checked;
First set up data binding by telling dat.gui to listen to the value you need to bind to by including .listen() after your .add()
gui = new dat.GUI;
controllers = [];
var menu = {
'This is an example': false,
}
controllers[0] = gui
.add(menu, 'This is an example')
.listen()
.onFinishChange(
function(value) {
console.log('example');
}
);
Then set your variable that dat.gui is controlling via the checkbox to false.
menu['This is an example'] = false;
Some more info about the details of dat.gui: http://dat-gui.googlecode.com/git-history/561b4a1411ed13b37be8ff974174d46b1c09e843/index.html

How do I create the html for the following enable/disable javascript to create a button to change the localstorage value?

I have the following javascript that cannot be changed.
Basically I need to make the UI for this, which is probably really basic html.
if(!localStorage.status) localStorage['status'] = 1;
toggle(2);
enable.onclick = function(){toggle(0)};
disable.onclick = function(){toggle(1)};
function toggle(n){
if((n == 0) && (enable.parentNode == list)){
list.removeChild(enable);
list.appendChild(disable);
localStorage.status = 1;
}else if((n == 1) && (disable.parentNode == list)){
list.removeChild(disable);
list.appendChild(enable);
localStorage.status = 0;
}else if((n == 2) && (!list.hasChildNodes())){
list.appendChild((localStorage.status == 1) ? disable : enable);
chrome.browserAction.setIcon({path: (localStorage.status == 1) ? "1.png" : "2.png"});
}else{
return;
}
}
I think what it's doing is creating and enable/disable button. But I'm not sure.
Basically I need the html to display enable or disable, and on click it changes and updates the localstorage value for 'status'.
Remember we can't change the javascript, I just need the html.
_
The quoted code requires variables enable and disable to be HTMLElement objects (so they can be appended to list, which I assume is a DIV) that accept click events. So pretty much any kind of element will do.
However, it looks like BUTTONs would make the most sense, so I'd suggest creating the elements in javascript as
var enable = document.createElement("button"); //create a <BUTTON>
enable.id = "enable";
enable.type = "button";
enable.textContent = "Enable"; //the displayed text
and similarly for disable. If you'd prefer not to add additional scripts to the page, the equivalent HTML markup to use is
<button id="enable" type="button">Enable</button>

Calling a function when checking a checkbox, onclick event doesn't fire when unchecking

I should probably start by mentioning that I am using Internet Explorer 6. I am calling a JavaScript function (tabModifiedHighlight) from an onChange event. The function works perfectly other places however, I have a couple of places on the page where it works when I check the checkbox, but the event doesn't even seem to fire when I uncheck it.
Here is the JavaScript function:
function tabModifiedHighlight(){
alert("alert");
var div, i, input, inputIndex, selects, selectIndex, selectedTab, highlighted;
var tabs = new Array("admissioninformation","diet","vitalsigns","activities","nursing","ivfluids","medications1","medications2","labs","respiratory","diagnostic","consultations");
for(i=0; i<(tabs.length); i++){
selectedTab = tabs[i]+'tab';
if (document.getElementById(selectedTab).className == "selectedtab"){
div = document.getElementById(tabs[i]),
input = div.getElementsByTagName('input'),
selects = div.getElementsByTagName('select');
break;
}
}
highlighted = false;
for (inputIndex = 0; inputIndex < input.length; inputIndex++){
if (input[inputIndex].checked == true){
highlighted = true;
}
}
for (inputIndex = 0; inputIndex < input.length; inputIndex++){
if (input[inputIndex].type == 'text' && input[inputIndex].value != ""){
highlighted = true;
}
}
for (selectIndex = 0; selectIndex < selects.length; selectIndex++){
if (selects[selectIndex].value != ""){
highlighted = true;
}
}
if (highlighted == true){
document.getElementById(selectedTab).style.backgroundColor = "#FF0";
}
else {
document.getElementById(selectedTab).style.backgroundColor = "#F0F0F0";
}
}
And here is the input that is calling it:
<input name="cbMedTylenolPO" id="cbMedTylenolPO" type="checkbox" value="PO" onClick="tylenolPoShowHide(); checkBoxHighlight(this, 'MedicationsRow2'); tabModifiedHighlight();" />
This page has multiple "tabs" which are just divs that are set to visible or hidden based on which one is selected. It seems consistent in that it works everywhere except for 2 of the tabs, and nowhere on those tabs. The only other difference I can see is that the ones that are not working are also showing or hiding divs within the tab, based on whether the checkbox is checked or not. I have added the alert at the very beginning of the function to see if it is firing or not, and it does when checking the checkbox, but not when unchecking.
I hope I made this clear, and any thoughts are appreciated!
As your code is not working only for two tabs, and working for all others its not an browser compatibility issue.
onClick if checkbox you are calling these 3 methods
tylenolPoShowHide(); checkBoxHighlight(this, 'MedicationsRow2');tabModifiedHighlight()
Note tabModifiedHighlight is last one..
if any of first two methods tylenolPoShowHide or checkBoxHighlight fails... then tabModifiedHighlight will not be called.
I will suggest to add alert as first and last line in both tylenolPoShowHide and checkBoxHighlight ...
It will help you find which one is actually failing then you can add that code here and we will be able to help you further

refer to another function by using radio Button

I am new with javascript and I have one question now. how can we refer to one function by using Radio button? I have list of countries and this list includes of population and area and density. I want to add radio button to my script when I select for example radio button "area" this function comes back to another function and extract the area of countries from the other function. I have written these functions but it works only for area. I need to add 3 radio button to this script
when I select for example the density button it refers to this function and extract the density of these countries and then the second function will change the colour. please help me
var myCantons = [];
myCantons[0] = ["Name Country","area kmĀ²","density",Population];
myCantons[102] = ["Germany",221.90,2696,117];
myCantons[106] = ["Italy",271.50,6510,485];
myCantons[107] = ["Denmark",141.31,2661,406];
myCantons[122] = ["Poland",286.25,3331,237];
myCantons[130] = ["Russia",124.49,5099,431];
function myInit(){
for(var i = 100; i < myCantons.length; i++){
if(typeof myCantons[i] != 'undefined'){
var myDensity = myCantons[i][2] ;
var myNewColor = '';
if(myDensity < 110){
myNewColor = 'yellow';
} else if (myDensity > 250){
myNewColor = 'red';
} else {
myNewColor = 'orange';
}
var mySvgId ='myCantonId'+(''+i).substr(1);
document.getElementById(mySvgId).setAttributeNS(null,'fill',myNewColor);
}
}
}
You might want to look into DOM events.
var handleChange = function (e) {
if(e.target.checked) {
// do something if the checkbox was selected
} else {
// do something if the checkbox was deselected
}
}
document.getElementById("myCheckbox").addEventlistener("change", handleChange, false);
You can attach a change event to any input element and monitor it's state. For checkboxes/radio buttons that would be the checked property. It is true if the input is selected.
We can put three radio buttons
<input type="radio" name="group1" id="area" value="area" onClick="myInit(this)"/>
<input type="radio" name="group1" id="density" value="density" onClick="myInit(this)" />
<input type="radio" name="group1" id="population" value="population" onClick="myInit(this)"/>
myInit function would be modified as follows to take argument of radio button object.
myInit(myradio)
{
if(myradio.checked == true && myradio.value=='area')
//Here logic for returning area will come
else if(myradio.checked == true && myradio.value=='density')
//Here logic for returning density will come
else if(myradio.checked == true && myradio.value=='population')
//Here logic for returning population will come
}

Dynamic label that changes based upon event handler

I have a snippet of HTML that is part of a form where there are two input's. Via CSS I have managed to make the label associated with each input to sit inside their corresponding input to act as a placeholder.
Now, with some standard JS (not JQuery I'm afraid), I wanted to capture the event that the user does (i.e. on a mouse click or keyboard press) on the input and dynamically change the look and feel of the label.
http://jsfiddle.net/8nBAQ/2/
The conditions that I need to meet are:
When a user clicks on the input for the first time. The label changes colour to a light grey. After click, if the user then enters a character, the label disappears and the character you have just pressed is displayed instead.
When a user clicks on the input for the first time. The label changes colour to a light grey. After click, if the user then clicks or tabs away from the input, the label changes colour back to it's original state of black.
After entering a few characters into the input, if the user decides to delete the whole set of characters by either pressing backspace deleting each character until none are left or highlighting the whole set of characters with a mouse and presses the delete key, the label appears but is in a light grey colour.
Any help you can offer with the JS would be great!
Thanks
-JaXL
Here is my solution. I added the following to the input tag and label
<label class="label-inside" for="input1" id="input1_label" title="Enter input 1">Input 1</label>
<ul class="form-input">
<li>
<input type="text" id="input1" name="myInput1" value="" autocomplete="off" title="Enter Input 1" onblur="handleBlur(this, document.getElementById('input1_label'))"
onkeydown="handleFirstClick(event, this, document.getElementById('input1_label'))"
onkeyup="handleKey(this, document.getElementById('input1_label'))" />
</li>
</ul>
And here is my Javascript
<script>
function handleBlur(input, label )
{
if ( !input.value || input.value.length == 0)
{
label.style.display = 'block';
label.style.color = 'black';
label.clickedBefore = false;
}
}
function handleFirstClick(e, input, label )
{
if ( !label.clickedBefore )
{
label.clickedBefore = true;
e.preventDefault();
label.style.color = 'red';
}
}
function handleKey(input, label)
{
console.log("handling key up : " + input.value.length);
label.style.display = 'none';
if (!input.value || input.value.length == 0 )
{
label.style.display = 'block';
label.style.color = 'red';
}
}
</script>
Let me know if something else is needed.
EDIT : adding code to add all handlers at once according to input_id.
window.onload = function(){
console.log("windows loaded");
var labels = {}
var all_labels = document.getElementsByTagName("label");
for ( var i = 0; i < all_labels.length; i++)
{
labels[all_labels[i].getAttribute("for")] = all_labels[i];
}
function attachHandlers( input_id )
{
var input = document.getElementById(input_id);
var label = labels[input_id];
input.onclick = function(e){handleFirstClick(e, input, label)};
input.onkeyup = function(e){handleKey(input, label)};
input.onblur = function(e){handleBlur(input, label)};
}
var attachInput = ["input1"];
for ( var j =0; j <attachInput.length; j++)
{
attachHandlers(attachInput[j]);
}
}

Categories

Resources