e.preventDefault() behvaing differently - javascript

I have a very simple jQuery UI spinner as follows:
<input value="2" class="form-control ui-spinner-input" id="spinner" aria-valuemin="2" aria-valuemax="24" aria-valuenow="2" autocomplete="off" role="spinbutton" type="text">
Using jQuery I set the above text box readonly true/false. The readonly and value is set based on the checkbox a user selects and that function looks like
function checkBoxes() {
var $targetCheckBoxes = $("#BoxFailure,#InstallationFailure");
$targetCheckBoxes.change(function () {
var isChecked = this.checked;
var currentElement = this;
var $radioButton = $('.usage-failure-type-radio');
$targetCheckBoxes.filter(function () {
return this.id !== currentElement.id;
}).prop('disabled', isChecked);
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked);
$radioButton.first().prop('checked', isChecked);
$radioButton.not(':checked').toggle(!isChecked).parent('label').toggle(!isChecked);
$('.usage-before-failure > div > span.ui-spinner > a').toggle(!isChecked);
});
}
Now what I'm trying to achieve is when the #spinner input is readonly and if the user presses the back space I want to prevent the default behaviour e.g. do navigate away from the page. For this I thought I'd do the following:
$('.prevent-default').keydown(function (e) {
e.preventDefault();
});
Which works fine if the input has the class prevent-default on page load. However, if I add it in my checkBoxes function in the following line
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).toggleClass('prevent-default')
Then I press the backspace it ignores e.prevenDefault();
But if I do
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).keydown(function (e) { e.preventDefault(); });
Then it works absolutely fine.
Can someone tell me why this is happening please.
The reason I want to use a separate function with a class name is because I have various inputs which get set to read only based on different check/radio values.

Can someone tell me why this is happening please
This is because of the DOM parser and the timing when JavaScript is executed.
If you already have an element with a class prevent-default in your DOM before JS is executed, then the JavaScript will recognise and handle it correctly. If you instead add the class afterwards with JS, then you have to re-initialise the keydown-event again to make it work.
To re-initialise you will need something like this:
function checkBoxes() {
var $targetCheckBoxes = $("#BoxFailure,#InstallationFailure");
$targetCheckBoxes.change(function () {
...
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).toggleClass('prevent-default');
// assign new keydown events
handleKeyDown();
...
});
}
function handleKeyDown() {
// release all keydown events
$('#spinner').off( "keydown", "**" );
$('.prevent-default').keydown(function (e) {
e.preventDefault();
// do more stuff...
});
}

Related

Global click event blocks element's click event

This should happen
If the user clicks on one of the two input boxes, the default value should be removed. When the user clicks elswhere on the webpage and one text field is empty, it should be filled with the default value from the data-default attribute of the spefic element.
This happens
When somebody clicks somewhere on the page and the field is empty, the field will be filled with the right value, but when somebody clicks in the field again the text isn't removed. It seems like the $(document) click event is blocking the $(".login-input") click event, because the $(".login-input") is working without the $(document) click event.
JSFiddle
A sample of my problem is provieded here: JSFiddle
Tank you for helping!
When you click on the input, the script is working, but since the input is in the document, a click on the input is a click on the document aswell. Both function will rune, document is the last one.
That is called event bubblingand you need to stop propagation :
$(document).ready(function () {
$(".login-input").click(function (e) {
e.stopPropagation()
$(this).val("");
});
});
Fiddle : http://jsfiddle.net/kLQW9/3/
That's not at all how you solve placeholders, you do it like so :
$(document).ready(function () {
$(".login-input").on({
focus: function () {
if (this.value == $(this).data('default')) this.value = '';
},
blur: function() {
if (this.value == '') this.value = $(this).data('default');
}
});
});
FIDDLE
Preferably you'd use the HTML5 placeholder attribute if really old browsers aren't an issue.
EDIT:
if you decide to do both, check support for placeholders in the browser before applying the javascript :
var i = document.createElement('input'),
hasPlaceholders = 'placeholder' in i;
if (!hasPlaceholders) {
// place the code above here, the condition will
// fail if placeholders aren't supported
}
Try below code
$(document).ready(function () {
$(".login-input").click(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").each(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
Check fiddle
Why not to use focus and blur events?
$(document).ready(function () {
$(".login-input").focus(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
http://jsfiddle.net/kLQW9/5/
P.S. In yours, and this code, on focus all data fro input will be cleared. If you need to clear only default text, add proper condition for that.

How can I update a input using a div click event

I've got the following code in my web page, where I need to click on the input field and add values using the number pad provided! I use a script to clear the default values from the input when the focus comes to it, but I'm unable to add the values by clicking on the number pad since when I click on an element the focus comes from the input to the clicked number element. How can I resolve this issue. I tried the following code, but it doesn't show the number in the input.
var lastFocus;
$("#test").click(function(e) {
// do whatever you want here
e.preventDefault();
e.stopPropagation();
$("#results").append(e.html());
if (lastFocus) {
$("#results").append("setting focus back<br>");
setTimeout(function() {lastFocus.focus()}, 1);
}
return(false);
});
$("textarea").blur(function() {
lastFocus = this;
$("#results").append("textarea lost focus<br>");
});
Thank you.
The first thing I notice is your selector for the number buttons is wrong
$('num-button').click(function(e){
Your buttons have a class of num-button so you need a dot before the class name in the selector:
$('.num-button').click(function(e){
Secondly, your fiddle was never setting lastFocus so be sure to add this:
$('input').focus(function() {
lastFocus = this;
...
Thirdly, you add/remove the watermark when entering the field, but ot when trying to add numbers to it (that would result in "Watermark-text123" if you clicked 1, then 2 then 3).
So, encalpsulate your functionality in a function:
function addOrRemoveWatermark(elem)
{
if($(elem).val() == $(elem).data('default_val') || !$(elem).data('default_val')) {
$(elem).data('default_val', $(elem).val());
$(elem).val('');
}
}
And call that both when entering the cell, and when clicking the numbers:
$('input').focus(function() {
lastFocus = this;
addOrRemoveWatermark(this);
});
and:
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
addOrRemoveWatermark(lastFocus);
$(lastFocus).val($(lastFocus).val() + $(this).children('span').html());
});
You'll see another change above - you dont want to use append when appends an element, you want to just concatenate the string with the value of the button clicked.
Here's a working branch of your code: http://jsfiddle.net/Zrhze/
This should work:
var default_val = '';
$('input').focus(function() {
lastFocus = $(this);
if($(this).val() == $(this).data('default_val') || !$(this).data('default_val')) {
$(this).data('default_val', $(this).val());
$(this).val('');
}
});
$('input').blur(function() {
if ($(this).val() == '') $(this).val($(this).data('default_val'));
});
var lastFocus;
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
var text = $(e.target).text();
if (!isNaN(parseInt(text))) {
lastFocus.val(lastFocus.val() + text);
}
});
Live demo
Add the following function:
$('.num-button').live( 'click', 'span', function() {
$currObj.focus();
$currObj.val( $currObj.val() + $(this).text().trim() );
});
Also, add the following variable to global scope:
$currObj = '';
Here is the working link: http://jsfiddle.net/pN3eT/7/
EDIT
Based on comment, you wouldn't be needing the var lastFocus and subsequent code.
The updated fiddle lies here http://jsfiddle.net/pN3eT/28/

Check if input was not changed

It is possible to check if a input was not changed using change() event?
I'm working with <input type='file' /> and i want to warning the user that no changes was made on his own action.
Right now, i just made a normal change() event:
// fire the thumbnail (img preview)
$("#file-input").on("change", function () {
readURL(this); // create the thumbnail
});
what i'm missing ?
Prev Solutuib:
well, i found a workaround for this, the real problem is that i give a option to the user to hide the thumbnail, and if he wants, open again...
but the thumbnail will only open when the user select a image, that's the problem, because the change event fire this option to open, so, if no change, no thumbnail open.
so, when i hide the thumbnail, i change the input file for a new one, making the change event always fire.
Use a variable to store the last value of the input, and compare to the current value on change event, if they are the same, no change was made :
var last_value = $("#file-input").val();
$("#file-input").on("change", function () {
if (this.value === last_value) alert('no change');
last_value=this.value;
});
EDIT: Or you can always just replace the input tag with another, like this SO answer suggest :
var $c = $("#container");
var $f1 = $("#container .f1");
function FChange() {
alert("f1 changed");
$(this).remove();
$("<input type='file' class='f1' />").change(FChange).appendTo($c);
}
$f1.change(FChange);
<input type="file" id="file-input" data-url="intial-value" />
$("#file-input").on("change", function () {
if($(this).val() != $(this).data('url'){
//value has changed
$(this).data('url', $(this).val())
}
else{
return false;
}
});
$("#file-input").on("change", function () {
if($(this).data('last-val')){
// do something
} else {
$(this).data('last-val',$(this).val());
//do something else
}
});

activate readonly back after editing the input jquery

how can i activate the readonly back after finishing the edit of the input ?
this is my code for now :
<script type="text/javascript">
$(document).ready(function () {
$("input").bind('click focus', function(){
$('input').each(function(){
$(this).attr("readonly", false);
});
});
});
</script>
an input like this :
<input type="text" class="m" readonly="readonly" id="anchor_text">
i think something with focusout, i need to put readonly back when i go to the next input, so the edited input can't be change unless i hit again click on it.
try:
$("input").bind('click focus', function(){
$(this).attr("readonly", false);
}).bind('blur', function(){
$(this).attr("readonly", true);
});​
demo : http://jsfiddle.net/DkCvu/1/
I'm sorry, but I'm struggling to see the point of this. If I get this right, you want the input field not to be editable until it is clicked or selected by the user (which is basically how input fields work anyhow: you can't change their value unless you select them). After these input fields loose their focus, they should go back to being read only. If this is the case, you're over complicating things. However, that is none of my business. The best way to get this done IMO, is by delegating the event.
I therefore put together a couple of fiddles, on pure JS, on jQuery. Both are far from perfect, but should help you on your way.
Regular JS (fiddle here):
var dv = document.getElementById('inputDiv');
if (!dv.addEventListener)
{
dv.attachEvent('onfocusin',switchRO);
dv.attachEvent('onfocusout',switchRO);
}
else
{
dv.addEventListener('focus',switchRO,true);
dv.addEventListener('blur',switchRO,true);
}
function switchRO (e)
{
var self;
e = e || window.event;
self = e.target || e.srcElement;
if (self.tagName.toLowerCase() === 'input')
{
switch (e.type)
{
case 'onfocusin':
case 'focus':
self.removeAttribute('readonly');
break;
default:
self.setAttribute('readonly','readonly');
}
}
return true;
}
In jQuery, this might look something like this (jQuery with .on, jsfiddle here):
$('#inputDiv input').on(
{
focus: function()
{
$(this).removeAttr('readonly');
},
blur: function()
{
$(this).attr('readonly','readonly');
}
});
​
I posted both jQuery and pure JS, because I find it both informative and educational to know what goes on behind the screens in jQuery.

Check/Uncheck checkbox with JavaScript

How can a checkbox be checked/unchecked using JavaScript?
Javascript:
// Check
document.getElementById("checkbox").checked = true;
// Uncheck
document.getElementById("checkbox").checked = false;
jQuery (1.6+):
// Check
$("#checkbox").prop("checked", true);
// Uncheck
$("#checkbox").prop("checked", false);
jQuery (1.5-):
// Check
$("#checkbox").attr("checked", true);
// Uncheck
$("#checkbox").attr("checked", false);
Important behaviour that has not yet been mentioned:
Programmatically setting the checked attribute, does not fire the change event of the checkbox.
See for yourself in this fiddle:
http://jsfiddle.net/fjaeger/L9z9t04p/4/
(Fiddle tested in Chrome 46, Firefox 41 and IE 11)
The click() method
Some day you might find yourself writing code, which relies on the event being fired. To make sure the event fires, call the click() method of the checkbox element, like this:
document.getElementById('checkbox').click();
However, this toggles the checked status of the checkbox, instead of specifically setting it to true or false. Remember that the change event should only fire, when the checked attribute actually changes.
It also applies to the jQuery way: setting the attribute using prop or attr, does not fire the change event.
Setting checked to a specific value
You could test the checked attribute, before calling the click() method. Example:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
Read more about the click method here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
to check:
document.getElementById("id-of-checkbox").checked = true;
to uncheck:
document.getElementById("id-of-checkbox").checked = false;
We can checked a particulate checkbox as,
$('id of the checkbox')[0].checked = true
and uncheck by ,
$('id of the checkbox')[0].checked = false
Try This:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');
I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.
So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.
Using vanilla js:
//for one element:
document.querySelector('.myCheckBox').checked = true //will select the first matched element
document.querySelector('.myCheckBox').checked = false//will unselect the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
//iterating over all matched elements
checkbox.checked = true //for selection
checkbox.checked = false //for unselection
}
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});
});
</script>
For single check try
myCheckBox.checked=1
<input type="checkbox" id="myCheckBox"> Call to her
for multi try
document.querySelectorAll('.imChecked').forEach(c=> c.checked=1)
Buy wine: <input type="checkbox" class="imChecked"><br>
Play smooth-jazz music: <input type="checkbox"><br>
Shave: <input type="checkbox" class="imChecked"><br>
If, for some reason, you don't want to (or can't) run a .click() on the checkbox element, you can simply change its value directly via its .checked property (an IDL attribute of <input type="checkbox">).
Note that doing so does not fire the normally related event (change) so you'll need to manually fire it to have a complete solution that works with any related event handlers.
Here's a functional example in raw javascript (ES6):
class ButtonCheck {
constructor() {
let ourCheckBox = null;
this.ourCheckBox = document.querySelector('#checkboxID');
let checkBoxButton = null;
this.checkBoxButton = document.querySelector('#checkboxID+button[aria-label="checkboxID"]');
let checkEvent = new Event('change');
this.checkBoxButton.addEventListener('click', function() {
let checkBox = this.ourCheckBox;
//toggle the checkbox: invert its state!
checkBox.checked = !checkBox.checked;
//let other things know the checkbox changed
checkBox.dispatchEvent(checkEvent);
}.bind(this), true);
this.eventHandler = function(e) {
document.querySelector('.checkboxfeedback').insertAdjacentHTML('beforeend', '<br />Event occurred on checkbox! Type: ' + e.type + ' checkbox state now: ' + this.ourCheckBox.checked);
}
//demonstration: we will see change events regardless of whether the checkbox is clicked or the button
this.ourCheckBox.addEventListener('change', function(e) {
this.eventHandler(e);
}.bind(this), true);
//demonstration: if we bind a click handler only to the checkbox, we only see clicks from the checkbox
this.ourCheckBox.addEventListener('click', function(e) {
this.eventHandler(e);
}.bind(this), true);
}
}
var init = function() {
const checkIt = new ButtonCheck();
}
if (document.readyState != 'loading') {
init;
} else {
document.addEventListener('DOMContentLoaded', init);
}
<input type="checkbox" id="checkboxID" />
<button aria-label="checkboxID">Change the checkbox!</button>
<div class="checkboxfeedback">No changes yet!</div>
If you run this and click on both the checkbox and the button you should get a sense of how this works.
Note that I used document.querySelector for brevity/simplicity, but this could easily be built out to either have a given ID passed to the constructor, or it could apply to all buttons that act as aria-labels for a checkbox (note that I didn't bother setting an id on the button and giving the checkbox an aria-labelledby, which should be done if using this method) or any number of other ways to expand this. The last two addEventListeners are just to demo how it works.
I agree with the current answers, but in my case it does not work, I hope this code help someone in the future:
// check
$('#checkbox_id').click()

Categories

Resources