jQuery - cancel change event on confirmation dialog for a Dropdown - javascript

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.

Related

animate if a checkbox isn't checked and a user tries to proceed

This is what I have so far
$(document).on('click', '.signin', function() {
if ($('#signinbox').prop('checked') == true) {
window.location.href = '/api/login';
}
}
What I'm trying to achieve: If a user tries to log in without checking the box, then it invokes the shake animation in animate.css to give them feedback.
Effectively, it seems you're just needing a conditional. Below, I'm casting the checkbox's checked attribute state to a Boolean and based on that, appropriating the desired action. In particular, I'm only navigating to the login URL if it is checked. The window.location.href line is only hit if the checkbox is checked.
Note, I haven't actually tested this code, but this seems like the barebones structure for what you're looking for.
$(document).on('click', '.signin', function() {
const $signInBox = $('#signinbox');
if (!$signInBox.prop('checked')) {
return $signInBox.addClass('animated shake');
} else
return window.location.href = '/api/login';
}
});
You can do something like this:
If the checkbox is not checked, you can add the animated classes and then remove it after some time, like this:
$(document).on('click', '.signin', function() {
if ($('#signinbox').prop('checked') == true) {
window.location.href = '/api/login';
} else {
$('.signin').addClass('animated shake');
setTimeout(function() {
$('.signin').removeClass('animated shake');
}, 1000);
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button type="button" class="signin">Login</button>
<input type="checkbox" id="signinbox">
</div>
Alright, the jist of what you want to do is to add the class 'shake' when the checkbox hasn't been checked and remove the class when the animation ends
var checkbox = document.getElementById('checkbox');
var form = document.getElementById('form');
form.addEventListener('animationend', function(e){
e.target.classList.remove('shake');
})
document.getElementById('login').addEventListener('click', function(e){
e.preventDefault();
e.stopPropagation();
if(!checkbox.checked){
form.classList.add('shake');
} else {
console.log('logged in!');
}
})
https://jsfiddle.net/o3spo0qL/

Disable and enable function in Jquery

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?

jQuery/Javascript Checkbox

i want do something like this with a checkBox. if the user clicks on the checkbox, it should change its state (checked -> unchecked and vv. ).
my code:
$('#checkBoxStandard').change(function() {
clickedFormBoxen('standard');
});
function clickedFormBoxen(active){
if(active == 'standard'){
if( $('#checkBoxStandard').is(":checked")){
$('#checkBoxStandard').prop("checked", false);
}else{
$('#checkBoxStandard').prop("checked", true);
}
console.log('ac: '+$('#checkBoxStandard').is(':checked'));
}
Unfortunately, the checkbox will not be unchecked again. The fist time, the checkbox is getting checked, but if i click on it again, nothing happens, it's still checked.
I wish to use this code so i can change the state of the checkbox by function call and not just by user interaction.
Please help me and sorry for my english^^
Try
$('#checkBoxStandard').removeAttr("checked");
You mean something like this? (jsFiddle)
HTML
<input type="checkbox" id="checkbox">
<label for="checkbox">Hey,check me!</label>
JavaScript
var respond = true;
function manualCheck(state)
{
respond = false;
$('#checkbox').prop("checked", state);
}
$('#checkbox').change(function ()
{
if (!respond)
{
respond = true;
return;
}
// Your code
}
As i've mentionend in my comment to your question, with your function clickedFormBoxen you effectively revert the effect of a user interaction on the checkbox element. Thus it seems that you have to call the change handler from a click handler on your checkbox element (i've streamlined the code a bit):
function clickedFormBoxen(active) {
if (active == 'standard') {
$('#checkBoxStandard').prop("checked", !($('#checkBoxStandard').prop("checked")));
}
}
$(document).ready( function(){
$('#checkBoxStandard').change( function(e) {
clickedFormBoxen('standard');
1;
});
$('#checkBoxStandard').click(function(e) {
$('#checkBoxStandard').change();
1;
});
});

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
}
});

Using jquery to monitor form field changes

Trying to learn some jquery to implement an autosave feature and need some assistance. I have some code to monitor the status of form fields to see if there has been any change. Everything works, but I need to only monitor the changes in a specific form, not all form inputs on the page. There is a search box and a newsletter form on the same page and when these form fields are changed, they are detected as well, which I need to filter out somehow or better yet, only target the specific form.
$(function(){
setInterval("CheckDirty()",10000);
$(':input').each(function() {
$(this).data('formValues', $(this).val());
});
});
function CheckDirty()
{
var isDirty = false;
$(':input').each(function () {
if($(this).data('formValues') != $(this).val()) {
isDirty = true;
}
});
if(isDirty == true){
alert("isDirty=" + isDirty);
}
}
Just add a class to the form and use it to filter
$('.form :input').each(function() {
$(this).data('formValues', $(this).val());
});
EDIT
Just a suggestion, you can attach the change event directly to the form
live demo here : http://jsfiddle.net/jomanlk/kNx8p/1/
<form>
<p><input type='text'></p>
<p><input type='text'></p>
<p><input type='checkbox'></p>
</form>
<p><input type='text'></p>
<div id='log'></div>
$('form :input').change(function(){
$('#log').prepend('<p>Form changed</p>')
});
You can easily improve this by adding a timer and making it save every xx seconds.
var $jq= jQuery.noConflict();
$jq(function() { $jq('#extensibleForm').data('serialize',$jq('#extensibleForm').serialize());
});
function formHasChanged(){
if($jq('#extensibleForm').serialize()!=$jq('#extensibleForm').data('serialize')){
alert("Data Changed....");
return (false);
}
return true;
}
what's your form's id?
you just need to make your selector more specific :)
instead of $(':input').each(function() {
use
$('#yourFormId').find(':input').each(function() {
You can use the .change() function and then use $(this) to denote you want to work with just the field that is actively being changed.
$('#myForm input[type="text"]').change(function() {
$(this)...
});
Edit: #myForm is your form ID so you can target a specific form. You can even specify just type="text" fields within that form, as in my example.
Here you can see it working: http://jsfiddle.net/paska/zNE2C/
$(function(){
setInterval(function() {
$("#myForm").checkDirty();
},10000);
$("#myForm :input").each(function() {
$(this).data('formValues', $(this).val());
});
$.fn.checkDirty = function() {
var isDirty = false;
$(this).find(':input').each(function () {
if($(this).data('formValues') != $(this).val()) {
isDirty = true;
}
});
if(isDirty == true){
alert("isDirty=" + isDirty);
}
};
});
I think you can use a class to select the type of input you want.
<input class="savethis" ... />
Then in jQuery use this.
$(':input .savethis').each(function() { ...
You can specify an id attribute (say theForm) to your form element and then select only those input fields inside it.
then try selecting with
$(':input', '#theForm')
I respect all the working answers but for me I think using the focus event might be much better than change event. This is how I accomplished my watchChange() function is JS:
var changeInterval = 0;
var changeLength = 0; //the length of the serverData
var serverData = {value:''}; //holds the data from the server
var fieldLength = 0; //the length of the value of the field we are tracking
var frequency = 10000;
function watchChange() {
$input.on('focus', function() {
var $thisInput = $(this);
//we need the interval value so that we destroy
//setInterval when the input loses focus.
changeInterval = setInterval(function() {
changeLength = serverData.value.length;
fieldLength = $thisInput.val().length;
//we only save changes if there is any modification
if (changeLength !== fieldLength) {
$.ajax({
url: 'path/to/data/handler',
dataType: 'json',
data: "data=" + $thisInput.val(),
method: 'post'
}).done(function(data) {
serverData = data;
}); //end done
} //end if
}, frequency); //end setInterval
//and here we destroy our watcher on the input
//when it loses focus
}).on('blur', function() {
clearInterval(changeInterval);
});
}
Even though this approach seems to be naive but it gave me what I wanted!

Categories

Resources