At the bottom of the jsfiddle here, I have this HTML:
<input type="text" id="BLAboxPaymentAmount" value="2">
</br>
<input type="text" id="BLAboxSection5Total" value="3">
..and this jQuery:
$(document).on("focusout", '[id$=boxSection5Total]', function (e) {
var totalvalue = $(this).val();
//alert("boxSection5Total val is " + totalvalue);
var paymenttotalvalue = $('[id$=boxPaymentAmount]').val();
//alert("Payment Total val is " + paymenttotalvalue);
if (totalvalue !== paymenttotalvalue) {
alert("The value in 'Total' does not equal the previous value in 'Payment Total'");
} else {
alert("values ARE equal");
}
});
It works fine in the jsfiddle, but the event is not firing in my Sharepoint page - I enter a value in boxPaymentAmount ("5"), enter another in boxSection5Total ("6"), tab off of boxSection5Total, and I see no alert, as I should, based on this jQuery, which is virtually identical to what's in the jsfiddle:
$(document).on("focusout", '[id$=boxSection5Total]', function (e) {
alert("focusout event has fired");
var totalvalue = $(this).val();
var paymenttotalvalue = $('[id$=boxPaymentAmount]').val();
if (totalvalue !== paymenttotalvalue) {
alert("The value in 'Total' does not equal the previous value in 'Payment Total'");
}
});
So the event is not even being fired - why not?
I ran the page in Chrome and F12d, looking for err msgs in the console, but found none.
UPDATE
For A. (not "The") Wolff:
This is how I create the elements in the code-behind:
boxPaymentAmount = new TextBox
{
CssClass = "dplatypus-webform-field-input"
};
I also changed the "textarea" to "text" in the HTML in the jsfiddle.
UPDATE 2
For Jonathen (not Russell) Crowe:
I changed my jQuery to the following:
$(document).on("blur", "[id$=boxSection5Total]", function (e) {
alert("blur event has fired");
console.log("blur event has fired");
var totalvalue = $(this).val();
var paymenttotalvalue = $('[id$=boxPaymentAmount]').val();
if (totalvalue !== paymenttotalvalue) {
alert("The value in 'Total' does not equal the previous value in 'Payment Total'");
console.log("The value in 'Total' does NOT equal the previous value in 'Payment Total'");
}
else {
console.log("The value in 'Total' DOES equal the previous value in 'Payment Total'");
}
});
...and still see nothing in the console from this event handler.
UPDATE 3
I have many other functions/handlers that fire just fine; so why this one doesn't is a conundrum. Maybe if I show what I've got (eliding some of the gory details), it may shed some light on what's going on (the failing function is the last/at the bottom):
$(document).ready(function () {
console.log('The ready function has been reached; Requester and Payee Status sections should be slid up'); /* This is a "sanity check" so it can be verified that this jQuery script is running/ran */
});
/* NOTE: Things that need to take place after all the elements have been constructed need to go here; the ready function can be too early */
$(window).load(function () {
$('[id$=_AddressRows]').slideUp();
$('[id$=panelSection2]').slideUp();
$('[id$=panelSection3]').slideUp();
$('[id$=ddlPayToVendor]').hide();
});
/* NOTE: this checkbox is only visible if they are not already authenticated; If they select "Yes" (self-identify as UCSC Faculty, Staff, or Student), prompt them to log in */
$(document).on("change", '[id$=ckbxUCSCFacultyStaffOrStudent]', function () {
var ckd = this.checked;
. . . code elided for brevity
});
/* If user selects "payment for self" (they are seeking payment for themselves, as opposed to someone else), omit (invisibilize) sections 2 and 3 on the form TODO: Should I change these from "change" to "click" */
$(document).on("click", '[id$=rbPaymentForSelf]', function () {
if (this.checked) {
. . . code elided for brevity
}
});
/* If user selects "payment for someone else" (they are seeking payment for someone else, as opposed to themselves), make sections 2 and 3 on the form visible */
$(document).on("click", '[id$=rbPaymentForSomeoneElse]', function () {
if (this.checked) {
. . . code elided for brevity
}
});
$(document).on("click", '[id$=rbPaymentToIndividual]', function () {
if (this.checked) {
$('[id$=ddlPayToVendor]').slideUp();
$('[id$=ddlPayToIndividual]').slideDown();
}
});
$(document).on("click", '[id$=rbPaymentToVendor]', function () {
if (this.checked) {
$('[id$=ddlPayToIndividual]').slideUp();
$('[id$=ddlPayToVendor]').slideDown();
}
});
// Refactor this to populate the elements below (description, account codes, tax 1099); may pull from Lists rather than use the hardcoded vals, but if need to do the latter, see http://jsfiddle.net/clayshannon/x8npcpss/3/
$(document).on("change", '[id$=ddlPayToIndividual]', function () {
var value = $(this).val();
. . . code elided for brevity
});
// Refactor this ... (see comment above)
$(document).on("change", '[id$=ddlPayToVendor]', function () {
var value = $(this).val();
. . . code elided for brevity
});
/* Disallow anything other than 0..9 in the "SSN or ITIN" textbox */
$(document).on("keypress", '[id$=txtbxSSNOrITIN]', function (e) {
var k = e.which;
if (k < 48 || k > 57) { e.preventDefault(); }
});
$(document).on("click", '[id$=btnAddFoapalRow]', function (e) {
var textboxHeight = 15;
. . . code elided for brevity
});
$(document).on("keyup", "[id$=explainPaymentTextBox]", function (e) {
console.log("explainPaymentTextBox keyup reached");
while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
$(this).height($(this).height() + 1);
};
});
HERE IS THE RECALCITRANT ONE (DOESN'T FIRE):
/* Verify that amount in "Total" equals amount in Section 1 "Payment Amount"; this is not working at present; I first tried "focusout" instead of "blur" but neither event fires... */
$(document).on("blur", "[id$=boxSection5Total]", function (e) {
alert("boxSection5Total's blur event has fired");
console.log("boxSection5Total's blur event has fired");
var totalvalue = $(this).val();
var paymenttotalvalue = $('[id$=boxPaymentAmount]').val();
if (totalvalue !== paymenttotalvalue) {
alert("The value in 'Total' does not equal the previous value in 'Payment Total'");
console.log("The value in 'Total' does NOT equal the previous value in 'Payment Total'");
}
else {
console.log("The value in 'Total' DOES equal the previous value in 'Payment Total'");
}
});
Did you try using blur instead of using focusout? The difference between those two events can be found here and, in your case, you only want to capture the event for the textarea because it doesn't have any items inside it.
It was a "rookie mistake" - I had forgotten to assign the ID to the element. Once I changed the code from this:
boxSection5Total = new TextBox()
{
CssClass = "dplatypus-webform-field-input"
};
this.Controls.Add(boxSection5Total);
...to this:
boxSection5Total = new TextBox()
{
CssClass = "dplatypus-webform-field-input",
ID = "boxSection5Total"
};
this.Controls.Add(boxSection5Total);
...I saw the alert about entering the event.
So the UPDATE shows the faulty code, although it would take someone accustomed to creating the html elements dynamically in C# to catch it.
For "full disclosure," here is the jQuery as it now stands (working as designed):
$(document).on("blur", "[id$=boxSection5Total]", function (e) {
var totalvalue = $(this).val();
var paymenttotalvalue = $('[id$=boxPaymentAmount]').val();
if (totalvalue !== paymenttotalvalue) {
console.log("The value in 'Total' does not equal the previous value in 'Payment Total'");
alert("The value in 'Total' does NOT equal the previous value in 'Payment Total'");
}
else {
console.log("The value in 'Total' DOES equal the previous value in 'Payment Total'");
}
});
This "dawned on me" when I "inspected element" in the F12 tools and saw:
<input name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ctl153" type="text" class="dplatypus-webform-field-input">
(no ID).
Related
Is it possible to identify if the value of radio button has not changed?
Currently I am trying to change the confirmation message of submit button on button changed, and do not want any message if the value has not changed. I have something like this now:
$('input[type="radio"]').change(function() {
var selected = $('input:checked[type="radio"]').val();
if(selected == 'true') {
$("#submit_button").data("confirm", "foo");
} else if(selected == 'false') {
$('#fee').hide();
$("#submit_button").data("confirm", "bar");
}
This will change confirm message to foo if button selected is true, and bar if button selected is false. However, what if I want to return nothing (no message), if radio button by default is true, and selected is true?
You can start a variable outside the event:
var radioChanged = 0;
And, in your event increase it:
$(':radio').change(function() {
radioChanged += 1;
// your code ...
});
Then, later on:
if (radioChanged > 0) {
alert('Change function occurred ' + radioChanged + ' times.');
} else {
alert('Radio button not changed.');
}
As i understand your expected behaviour, check if any radio has no more its default checked value:
$('form').on('submit', function() {
var anyRadioChanged = !!$(this).find('input[type="radio"]').filter(function() {
return $(this).is(':checked') != this.defaultChecked;
}).length; // '!!' to get boolean but it doesn't really matter here
if(anyRadioChanged) {
// show message(???)
}
})
you can hide message element just adding display: none to it or use jquery hide method
$('#someElementId').hide();
or
$('#someElementId').css("display","none")
I have a input that generates a number upon another input keyup. however it should only generate this number when my checkbox is checked. if it doesn't it shouldn't generate there nothing. but instead it generates me the number if the checkbox is check or not .. even though the function exists only in the checked mode.. i have no idea what went wrong:
the checkbox
<div class="col-md-6">
<div class="switch switch-primary">
<input class="multi-transaction" type="checkbox" name="switch" data-plugin-ios-switch="">
</div>
</div>
jQuery
$('.multi-transaction').click(function () {
var sum = $('.amount-czk');
if($(this).prop("checked") == true){
sum.prop("disabled", false); // check
sum.css('border-color', '#ccc');
sum.val(0);
$('.amount-czk').on('keyup', function () {
var amount = parseInt($('.give-me-money').val()); // amount to pay in eur example 520
var amount_wr = parseInt($('.amount-czk').val()); // type how much we got in any currency
$('.currency-czk').val((amount_wr / amount ? amount_wr / amount : 0).toFixed(2));
});
//curchange(true);
}
else if($(this).prop("checked") == false){
console.log('do nothing');
}
});
Instead of only giving me the console.log the input keyup function stays working..
Don't bind event handlers inside another handlers, they will multiply soon causing strange issues. Try something like this instead:
$('.multi-transaction').click(function () {
var sum = $('.amount-czk');
if ($(this).prop("checked") == true) {
sum.prop("disabled", false); // check
sum.css('border-color', '#ccc');
sum.val(0);
//curchange(true);
} else if ($(this).prop("checked") == false) {
console.log('do nothing');
}
});
$('.amount-czk').on('keyup', function () {
if ($('.multi-transaction').prop('checked')) {
var amount = parseInt($('.give-me-money').val()); // amount to pay in eur example 520
var amount_wr = parseInt($('.amount-czk').val()); // type how much we got in any currency
$('.currency-czk').val((amount_wr / amount ? amount_wr / amount : 0).toFixed(2));
}
});
Just try in if condition...
if($(this).prop('checked')) {
// something when checked
} else {
// something else when not
}
In my limited understanding of jQuery, I don't understand what is happening here.
I have two divs, each with a class of "required". The 1st div contains a set of checkboxes, while the second contains radio buttons. The object is to highlight the appropriate div background if no objects in either set are selected.
The 2nd set, however (the radio buttons), does have a button pre-selected by default, so should never be highlighted.
Here is what is happening:
Both sets are being looped through twice. At the end of the 1st div (checkbox) loop, the div is correctly highlighted. The radio button items are them checked and the default checked button is recognized and that div is not highlighted. Then, the first div items are again gone through. At the end of this - and BEFORE the 2nd div is looped through for the second time, the 2nd div is highlighted. I am assuming that the cause here, even though it is correctly looping through the checkboxes, it is associating them with the id of the radiobuttons. What I need to do is prevent this second loop-through.
$(document).ready(function () {
$('#Submit').click(function () {
$('div.Required', '#JobForm').each(function () {
var FieldName = this.id;
var FieldLength = FieldName.length
var CheckError = true;
$("input:checkbox").each(function () {
if (this.checked) {
CheckError = false;
}
});
if (CheckError) {
ErrorList += FieldName + ' requires a selection\n';
this.style.backgroundColor = "#FFC0C0";
}
CheckError = true;
$("input:radio").each(function () {
if (this.checked) {
CheckError = false;
}
});
if (CheckError) {
ErrorList += FieldName + ' requires a selection\n';
this.style.backgroundColor = "#FFC0C0";
}
});
if (Error) {
$('#Submit').val('Submit');
alert(ErrorList)
return false;
} else {
document.JobForm.submit();
}
});
});
Thanks to adeneo's suggestions, I was able to limit the double div looping, which also allowed me to eliminate the additional error message. As adeneo stated, since there are two div's, as originally written, the code was looping through both input types each time.
As written below, the first loop loops through the checkboxes, while the second loops through the radio buttons.
$(document).ready(function()
{
$('#Submit').click(function ()
{
$('div.Required','#JobForm').each(function()
{
var FieldName = this.id;
var FieldLength = FieldName.length
var CheckError = true;
$("input:checkbox", this).each(function ()
{
if(this.checked){CheckError=false;}
});
$("input:radio", this).each(function ()
{
if(this.checked){CheckError=false;}
});
if(CheckError){ErrorList += FieldName+' requires a selection\n'; this.style.backgroundColor="#FFC0C0";}
});
if(Error)
{
$('#Submit').val('Submit');
alert(ErrorList)
return false;
}
else
{
document.JobForm.submit();
}
});
});
You're not iterating over each DIV twice, but you're iterating over all the inputs the same number of times as you have matching DIV's
$('#Submit').click(function () {
// loop over the DIV's, lets say two times if there are two elements
$('div.Required', '#JobForm').each(function () {
// ..... other code
// the code below selects all the checkboxes, both times
$("input:checkbox").each(function () {
if (this.checked) {
CheckError = false;
}
});
// the code below selects all the radiobuttons, both times
$("input:radio").each(function () {
if (this.checked) {
CheckError = false;
}
});
// .......more code
});
});
Limit the selection of inputs with context or find()
$("input:checkbox", this).each(function () { ...
or
$(this).find("input:checkbox").each(function () { ...
also, your conditions don't make sense, you keep setting CheckError to a boolean, and on the next line you're checking for that boolean, and you'll never get a different result
CheckError = true;
if (CheckError) { ...
is like doing
if (true) { ...
I have this two HTML Form buttons with an onclick action associated to each one.
<input type=button name=sel value="Select all" onclick="alert('Error!');">
<input type=button name=desel value="Deselect all" onclick="alert('Error!');">
Unfortunately this action changes from time to time. It can be
onclick="";>
or
onclick="alert('Error!');"
or
onclick="checkAll('stato_nave');"
I'm trying to write some javascript code that verifies what is the function invoked and change it if needed:
var button=document.getElementsByName('sel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
if( button.getAttribute("onclick") != "checkAll('stato_nave');" &&
button.getAttribute("onclick") != ""){
//modify button
document.getElementsByName('sel')[0].setAttribute("onclick","set(1)");
document.getElementsByName('desel')[0].setAttribute("onclick","set(0)");
} //set(1) and set(0) being two irrelevant function
Unfortunately none of this work.
Going back some steps I noticed that
alert( document.getElementsByName('sel')[0].onclick);
does not output the onclick content, as I expected, but outputs:
function onclick(event) {
alert("Error!");
}
So i guess that the comparisons fails for this reason, I cannot compare a function with a string.
Does anyone has a guess on how to distinguish which function is associated to the onclick attribute?
This works
http://jsfiddle.net/mplungjan/HzvEh/
var button=document.getElementsByName('desel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
var click = button.getAttribute("onclick");
if (click.indexOf('error') ) {
document.getElementsByName('sel')[0].onclick=function() {setIt(1)};
document.getElementsByName('desel')[0].onclick=function() {setIt(0)};
}
function setIt(num) { alert(num)}
But why not move the onclick to a script
window.onload=function() {
var button1 = document.getElementsByName('sel')[0];
var button2 = document.getElementsByName('desel')[0];
if (somereason && someotherreason) {
button1.onclick=function() {
sel(1);
}
button2.onclick=function() {
sel(0);
}
}
else if (somereason) {
button1.onclick=function() {
alert("Error");
}
}
else if (someotherreason) {
button1.onclick=function() {
checkAll('stato_nave')
}
}
}
Try casting the onclick attribute to a string. Then you can at least check the index of checkAll and whether it is empty. After that you can bind those input elements to the new onclick functions easily.
var sel = document.getElementsByName('sel')[0];
var desel = document.getElementsByName('desel')[0];
var onclick = sel.getAttribute("onclick").toString();
if (onclick.indexOf("checkAll") == -1 && onclick != "") {
sel.onclick = function() { set(1) };
desel.onclick = function() { set(0) };
}
function set(number)
{
alert("worked! : " + number);
}
working example: http://jsfiddle.net/fAJ6v/1/
working example when there is a checkAll method: http://jsfiddle.net/fAJ6v/3/
Basically I need to check if the value is changed in a textbox on the 'blur' event so that if the value is not changed, I want to cancel the blur event.
If it possible to check it the value is changed by user on the blur event of an input HTML element?
I don't think there is a native way to do this. What I would do is, add a function to the focus event that saves the current value into a variable attached to the element (element.oldValue = element.value). You could check against that value onBLur.
Within the onblur event, you can compare the value against the defaultValue to determine whether a change happened:
<input onblur="if(this.value!=this.defaultValue){alert('changed');}">
The defaultValue will contain the initial value of the object, whereas the value will contain the current value of the object after a change has been made.
References:
value vs defaultValue
You can't cancel the blur event, you need to refocus in a timer. You could either set up a variable onfocus or set a hasChanged variable on the change event. The blur event fires after the change event (unfortunately, for this situation) otherwise you could have just reset the timer in the onchange event.
I'd take an approach similar to this:
(function () {
var hasChanged;
var element = document.getElementById("myInputElement");
element.onchange = function () { hasChanged = true; }
element.onblur = function () {
if (hasChanged) {
alert("You need to change the value");
// blur event can't actually be cancelled so refocus using a timer
window.setTimeout(function () { element.focus(); }, 0);
}
hasChanged = false;
}
})();
Why not just maintaining a custom flag on the input element?
input.addEventListener('change', () => input.hasChanged = true);
input.addEventListener('blur', () =>
{
if (!input.hasChanged) { return; }
input.hasChanged = false;
// Do your stuff
});
https://jsfiddle.net/d7yx63aj
Using Jquery events we can do this logic
Step1 : Declare a variable to compare the value
var lastVal ="";
Step 2: On focus get the last value from form input
$("#validation-form :input").focus(function () {
lastVal = $(this).val();
});
Step3:On blur compare it
$("#validation-form :input").blur(function () {
if (lastVal != $(this).val())
alert("changed");
});
You can use this code:
var Old_Val;
var Input_Field = $('#input');
Input_Field.focus(function(){
Old_Val = Input_Field.val();
});
Input_Field.blur(function(){
var new_input_val = Input_Field.val();
if (new_input_val != Old_Val){
// execute you code here
}
});
I know this is old, but I figured I'd put this in case anyone wants an alternative. This seems ugly (at least to me) but having to deal with the way the browser handles the -1 index is what was the challenge. Yes, I know it can be done better with the jquery.data, but I'm not that familiar with that just yet.
Here is the HTML code:
<select id="selected">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
Here is the javascript code:
var currentIndex; // set up a global variable for current value
$('#selected').on(
{ "focus": function() { // when the select is clicked on
currentIndex = $('#selected').val(); // grab the current selected option and store it
$('#selected').val(-1); // set the select to nothing
}
, "change": function() { // when the select is changed
choice = $('#selected').val(); // grab what (if anything) was selected
this.blur(); // take focus away from the select
//alert(currentIndex);
//setTimeout(function() { alert(choice); }, 0);
}
, "blur": function() { // when the focus is taken from the select (handles when something is changed or not)
//alert(currentIndex);
//alert($('#selected').val());
if ($('#selected').val() == null) { // if nothing has changed (because it is still set to the -1 value, or null)
$('#selected').val(currentIndex); // set the value back to what it originally was (otherwise it will stay at what was newly selected)
} else { // if anything has changed, even if it's the same one as before
if ($('#selected').val() == 2) { // in case you want to do something when a certain option is selected (in my case, option B, or value 2)
alert('I would do something');
}
}
}
});
Something like this. Using Kevin Nadsady's above suggestion of
this.value!=this.defaultValue
I use a shared CSS class on a bunch of inputs then do:
for (var i = 0; i < myInputs.length; i++) {
myInputs[i].addEventListener('blur', function (evt) {
if(this.value!=this.defaultValue){
//value was changed now do your thing
}
});
myInputs[i].addEventListener('focus', function (evt) {
evt.target.setAttribute("value",evt.target.value);
});
}
Even if this is an old post, I thought i'd share a way to do this with simple javascript.
The javascript portion:
<script type="text/javascript">
function HideLabel(txtField){
if(txtField.name=='YOURBOXNAME'){
if(txtField.value=='YOURBOXNAME')
txtField.value = '';
else
txtField.select();
}
}
function ShowLabel(YOURBOXNAME){
if(txtField.name=='YOURBOXNAME'){
if(txtField.value.trim()=='')
txtField.value = 'YOURDEFAULTVALUE';
}
}
</script>
Now the text field in your form:
<input type="text" id="input" name="YOURBOXNAME" value="1" onfocus="HideLabel(this)"
onblur="ShowLabel(this)">
And bewn! No Jquery needed. just simple javascript. cut and paste those bad boys. (remember to put your javascript above the body in your html)
Similar to #Kevin Nadsady's post, the following will work in native JS functions and JQuery listener events. Within the onblur event, you can compare the value against the defaultValue:
$(".saveOnChange").on("blur", function () {
if (this.value != this.defaultValue) {
//Set the default value to the new value
this.defaultValue = this.value;
//todo: save changes
alert("changed");
}
});
The idea is to have a hidden field to keep the old value and whenever the onblur event happens, check the change and update the hidden value with the current text value
string html = "<input type=text id=it" + row["cod"] + "inputDesc value='"
+ row["desc"] + "' onblur =\"if (this.value != document.getElementById('hd" + row["cod"].ToString() +
"inputHiddenDesc').value){ alert('value change'); document.getElementById('hd" + row["cod"].ToString() +
"inputHiddenDesc').value = this.value; }\"> " +
"<input type=hidden id=hd" + row["cod"].ToString() + "inputHiddenDesc value='" + row["desc"] + "'>";