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
}
});
Related
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...
});
}
I have a text input in html that is affected by a function exectued by .change() events from different radios and checkboxes. I'm trying to make it so that if a user types into the input, this function will no longer run when a .change() event happens in the aforementioned radios and checkboxes (the user must still be able to use these radios and checkboxes). However, if the user leaves the input blank and clicks away, the script will run again. I hope is possible.
Here is my take on this so far:
Using.prop('diabled' isnt viable because it completely disables the input, making the user unable to type in it, so I need another solution.
$(function() {
$('#burger-navn').on('input', function() {
$("#burger-navn").prop('disabled', true);
});
//When the input (#burger-navn) is typed into it should be "disabled"
$('#burger-navn').focusout(function() {
if ($(this).val().length == 0) {
$("#burger-navn").prop('disabled', false);
}
});
//But if its clicked out of while its blank, it should be able to run again.
$("#okseinput, #laksinput, #kyllinginput, #vegetarinput").change(function() {
if (!$("#burger-navn").not(':disabled')) { //condition that tests
navngenerator();
}
});
});
To solve this I simply created a separate input tag that I could add and remove disabled attribute from, and check if it has that attribute.
So in html:
<input id="burger-navn" type="text"/>
<input id="toggle" disabled="disabled" style="display:none"/>
jQuery:
var previousValue = $("#burger-navn").val();
$("#burger-navn").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
$("#toggle").prop('disabled', false);
}//This function will remove disabled from #toggle, when a user types into #burger-navn
});
$('#burger-navn').focusout(function() {
if ($(this).val().length == 0) {
$("#toggle").prop('disabled', true);
}
});
if ($("#toggle").is(':disabled')) {
navngenerator();
}
$("#okseinput, #laksinput, #kyllinginput, #vegetarinput").change(function() {
if ($("#toggle").is(':disabled')) {
navngenerator();
}
});
$(selector).on('change', function(event){
event.preventDefault();
event.stopPropagation();
// the selected field no longer does anything on change
});
is that what you are looking for?
I am facing one issue, I want to disable anchor click after one click. I have
on-click attribute set in my anchor tag. Below is my HTML
<a style="cursor:pointer;" id="someId" onclick="Myfuntion()">Verify</a>
After I click "Verify" I am changing anchors text to "Verifying..." and one more thing I am trying to disable this anchor to avoid click in between the verification logic going on.
I have tried event.preventdefault() and also added disabled attribute to anchor.
But nothing works.
Please help!
If you were using jQuery for this you could have done this more easly.
Here we add a new class to a link to show that it has been clicked already. We check this when a click is made.
<a style="cursor:pointer;" id="someId">Verify</a>
$('#someId').on('click',function(){
//Check if button has class 'disabled' and then do your function.
if(! $(this).hasClass('disabled')){
$(this).addClass('disabled');
Myfuntion();
$(this).removeClass('disabled');
}
});
Here is a demo as to how it could be done using Javascript.
//Pass the event target to the function
function Myfuntion(elem) {
//If the element has no "data-status" attribute
if (!elem.getAttribute("data-status")) {
//Set attribute "data-status=progress"
elem.setAttribute("data-status", "progress");
//Change the text of the element
elem.textContent = "Verifying...";
//The setTimeout(s) below is only for the demp purpose
//Lets say, your verification process takes 4 seconds
//When complte
setTimeout(function() {
//Remove the attribute "data-status"
elem.removeAttribute("data-status");
//Notify the use that verification is done
elem.textContent = "Verified";
//Again, this is only for demo purpose
setTimeout(function() {
//User may verify again
elem.textContent = "Verify";
}, 1000);
}, 4000);
}
return false;
}
Link to the demo
There are plenty of ways to do this; one simple approach is to just redefine the function itself:
var myFunction = function() {
alert('clicked');
// do whatever your function needs to do on first click, then:
myFunction = function() { // redefine it
// to no-op, or to another action
alert('second click');
}
}
<a onclick="myFunction()">click me</a>
I have a code like this:
$('#foo').on('click', function(e) {
//do something
});
$('form input').on('change', function(e) {
//do some other things
));
First and second events do actually the same things with the same input field, but in different way. The problem is, that when I click the #foo element - form change element fires as well. I need form change to fire always when the content of input is changing, but not when #foo element is clicked.
That's the question )). How to do this?
Here is the code on jsfiddle: http://jsfiddle.net/QhXyj/1/
What happens is that onChange fires when the focus leaves the #input. In your case, this coincides with clicking on the button. Try pressing Tab, THEN clicking on the button.
To handle this particular case, one solution is to delay the call to the change event enough check if the button got clicked in the meantime. In practice 100 milisecond worked. Here's the code:
$().ready(function() {
var stopTheChangeBecauseTheButtonWasClicked = false;
$('#button').on('click', function(e) {
stopTheChangeBecauseTheButtonWasClicked = true;
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
var self = this;
setTimeout(function doTheChange() {
if (!stopTheChangeBecauseTheButtonWasClicked) {
$(self).val($(self).val() + ' - changed!');
} else {
stopTheChangeBecauseTheButtonWasClicked = false;
}
}, 100);
});
});
And the fiddle - http://jsfiddle.net/dandv/QhXyj/11/
It's only natural that a change event on a blurred element fires before the clicked element is focused. If you don't want to use a timeout ("do something X ms after the input was changed unless in between a button was clicked", as proposed by Dan) - and timeouts are ugly - you only could go doing those actions twice. After the input is changed, save its state and do something. If then - somewhen later - the button is clicked, retrieve the saved state and do the something similar. I guess this is what you actually wanted for your UI behaviour, not all users are that fast. If one leaves the input (e.g. by pressing Tab), and then later activates the button "independently", do you really want to execute both actions?
var inputval = null, changedval = null;
$('form input').on('change', function(e) {
inputval = this.value;
// do some things with it and save them to
changedval = …
// you might use the value property of the input itself
));
$('#foo').on('click', function(e) {
// do something with inputval
});
$('form …').on('any other action') {
// you might want to invalidate the cache:
inputval = changedval;
// so that from now on a click operates with the new value
});
$(function() {
$('#button').on('click', function() {
//use text() not html() here
$('#wtf').text("I don't need to change #input in this case");
});
//fire on blur, that is when user types and presses tab
$('#input').on('blur', function() {
alert("clicked"); //this doesn't fire when you click button
$(this).val($(this).val()+' - changed!');
});
});
Here's the Fiddle
$('form input').on('change', function(e) {
// don't do the thing if the input is #foo
if ( $(this).attrib('id') == 'foo' ) return;
//do some other things
));
UPDATE
How about this:
$().ready(function() {
$('#button').on('click', function(e) {
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
// determine id #input is in focus
if ( ! $(this).is(":focus") ) return;
$(this).val($(this).val()+' - changed!');
});
});
I have a dropdown and I have the jQuery change function.
I would like to implement the change of the selected item as per the Confirmation dialog.
If confirms true i can proceed for selected change otherwise I have keep the existing item as selected and cancel the change event.
How can I implement this with jQuery?
jquery Function
$(function () {
$("#dropdown").change(function () {
var success = confirm('Are you sure want to change the Dropdown ????');
if (success == true) {
alert('Changed');
// do something
}
else {
alert('Not changed');
// Cancel the change event and keep the selected element
}
});
});
One thing to remember change function hits only after selected item changed
So better to think to implement this on onchange - but it is not available in jquery. Is there any method to implement this?
Well, as Vinu has rightly pointed out, jQuery's change event is only triggered once the value of the select has actually been changed. You would be better off doing something like this:
var prev_val;
$('#dropdown').focus(function() {
prev_val = $(this).val();
}).change(function() {
$(this).blur() // Firefox fix as suggested by AgDude
var success = confirm('Are you sure you want to change the Dropdown?');
if(success)
{
alert('changed');
// Other changed code would be here...
}
else
{
$(this).val(prev_val);
alert('unchanged');
return false;
}
});
Something like what I did here?
http://jsfiddle.net/Swader/gbdMT/
Simply save the value as soon as a user clicks the select box, and revert back to this value if the onchange confirmation returns false.
Here is the code from my fiddle:
var lastValue;
$("#changer").bind("click", function(e) {
lastValue = $(this).val();
}).bind("change", function(e) {
changeConfirmation = confirm("Really?");
if (changeConfirmation) {
// Proceed as planned
} else {
$(this).val(lastValue);
}
});
Use following code,I have tested it and its working
var prev_val;
$('.dropdown').focus(function() {
prev_val = $(this).val();
}).change(function(){
$(this).unbind('focus');
var conf = confirm('Are you sure want to change status ?');
if(conf == true){
//your code
}
else{
$(this).val(prev_val);
$(this).bind('focus');
return false;
}
});
Below code is implemented for radio button.I think this code with minor changes can be used for drop down also.
<input type="radio" class="selected" value="test1" name="test1"
checked="checked" /><label>test1</label>
<input type="radio" name="test1" value="test2" /><label>
test2</label>
<input type="radio" name="test1" value="test3" /><label>
test3</label>
</div>
$("input[name='test1']").change(function() {
var response = confirm("do you want to perform selection change");
if (response) {
var container = $(this).closest("div.selection");
//console.log(container);
//console.log("old sel =>" + $(container).find(".selected").val());
$(container).find(".selected").removeClass("selected");
$(this).addClass("selected");
//console.log($(this).val());
console.log("new sel =>" + $(container).find(".selected").val());
}
else {
var container = $(this).closest("div.selection");
$(this).prop("checked", false);
$(container).find(".selected").prop("checked", true);
}
});
As far as I know you have to handle it yourself, this might help:
<select onFocus="this.oldIndex = this.selectedIndex" onChange="if(!confirm('Are you sure?'))this.selectedIndex = this.oldIndex">
Simply do it like
$("#dropdown").change(function () {
var success = confirm('Are you sure want to change the Dropdown ????');
if (success == true) {
// do something
}
else {
return false; // will set the value to previous selected
}
});
Blurring, focusing and storing previous values seems a bit cumbersome. I solved this problem by attaching my listener not to the select, but to the option:
$("#id").on('mousedown','option',confirmChange);
then,
function confirmChange(e){
var value = $(this).val(),
c = confirm('Are you sure you want to change?');
if(c)
$(this).parent().val(value);//can trigger .change() here too if necessary
else
e.preventDefault();
}
Of course optimizations can be done, but this is the general idea.