I'm trying to make a conditional function based on the result of a javascript confirm dialog box.
It seems to return true regardless of what I click. Anyone see what I am doing wrong?
$(function () {
$("#Language").change(function () {
var a = $(this).val();
if (a == 3) {
confirm("Selecting a bilingual calendar will effect the billing. ")
if (confirm) { console.log("test"); }
}
});
});
if(confirm) really isn't doing anything for you (because it doesn't exist). Try this:
// Save the response in a var called userResponse
var userResponse = confirm("Selecting a bilingual calendar will effect the billing. ")
if (userResponse) { console.log("test"); }
You could also shorten the code a bit by simply putting the confirm in your if statement:
// confirm() returns true or false. So, when evaluated your if simply says
// if(true) or if(false), depending on the answer.
if (confirm("Selecting a bilingual calendar will effect the billing. ")) {
console.log("test");
}
$(function () {
$("#Language").change(function () {
var a = $(this).val();
if (a == "3") { // notice the quotation marks
// notice this variable
var confirmed = confirm("Selecting a ... billing.");
if (confirmed) { console.log("test"); }
}
});
});
Related
The input named alternativa-*** will have the *** changed in the PHP that comes before. I'm not using a form on PHP only a onClick statement calling the respondeQuestao function. But this code seems to not work. Someone have any suggestion.
$(document).ready(function() {
function respondeQuestao(qid,resposta) {
var alternativa = document.getElementsByName('input[name = "aternativa-"' + qid ']:checked').value;
document.getElementById("demo").innerHTML = 5 + 6;
if(alternativa==resposta) {
$("#botao-questao"+qid).hide();
};
if(alternativa!=resposta) {
};
};
})
Defining a function within the jQuery Ready statement limits the accessibility - define it outside of the jQuery Ready statement but call it when you need it.
function respondeQuestao(qid, resposta) {
var alternativa = $("INPUT[name^='alternativa-']:checked").val();
$("#demo").html(5+6);
if (alternativa == resposta) {
$("#botao-questro" + qid).hide()
} else {
//
}
}
Call the function inside jQuery:
$(function() {
respondeQuestao("id", 11);
});
I hope this helps.
I have two multiselect menus where I'm trying to get a total of how many children are present in each multiselct on load, then update the numbers, based on a click event which will push from one to the other, or vice versa.
The onload portion is working fine. I'm getting the results I'd expect and the counts are accurate.
The problem I'm having is updating both counts once the click event triggers. My counts never change.
Here's my code along with a fiddle:
var activeUser = $('.activeUsers');
var eligibleUser = $('.eligibleUsers');
var availableUserCount = $("#availableUsers option").length;
var eligibleUserCount = $("#eligibleUsers option").length;
activeUser.html(availableUserCount);
eligibleUser.html(eligibleUserCount);
$('#availableUsers').click(function () {
return !$('#availableUsers option:selected').remove().appendTo('#eligibleUsers');
activeUser.length(function() {
return availableUserCount();
});
eligibleUser.length(function() {
return eligibleUserCount();
});
});
$('#eligibleUsers').click(function () {
return !$('#eligibleUsers option:selected').remove().appendTo('#availableUsers');
activeUser.length(function() {
return availableUserCount();
});
eligibleUser.length(function() {
return eligibleUserCount();
});
});
http://jsfiddle.net/mujaji/8gkLyfe3/3/
What am I doing wrong?
There seems to be 3 problems with your code.
You are using return in the fist line of the click event. So the following code will never be executed (Get rid of that and only return if you cannot find any options)
There is no method called length for a div element. (Use .text() instead)
When you are returning the length inside the function return availableUserCount(); it will return you the cached value. (You need to reselect the element again)
So your code should technically look like this (further refactoring can still be made)
var activeUser = $('.activeUsers');
var eligibleUser = $('.eligibleUsers');
var availableUserCount = $("#availableUsers option").length;
var eligibleUserCount = $("#eligibleUsers option").length;
activeUser.html(availableUserCount);
eligibleUser.html(eligibleUserCount);
$('#availableUsers').click(function () {
!$('#availableUsers option:selected').remove().appendTo('#eligibleUsers');
activeUser.text(function() {
return $("#availableUsers option").length;
});
eligibleUser.text(function() {
return $("#eligibleUsers option").length;
});
});
$('#eligibleUsers').click(function () {
!$('#eligibleUsers option:selected').remove().appendTo('#availableUsers');
activeUser.text(function() {
return $("#availableUsers option").length;
});
eligibleUser.text(function() {
return $("#eligibleUsers option").length;
});
});
Check Fiddle
$("#availableUsers option").length doesn't dynamically change with the number of options. Once you set it up top, it's 40 forever. This does what you want:
$('#availableUsers').click(function () {
$('#availableUsers option:selected').remove().appendTo('#eligibleUsers');
activeUser.text($("#availableUsers option").length);
eligibleUser.text($("#eligibleUsers option").length);
});
Although it's not efficient to re-query every time when you could do
availableUserCount--; eligibleUserCount++;
And keep track of it manually.
Best solution (sic) :D
/*JQUERY FUNCTIONS*/
var activeUser = $('.activeUsers');
var eligibleUser = $('.eligibleUsers');
var eligibleUserCount = function(){eligibleUser.html($("#eligibleUsers option").length)};
var availableUserCount = function(){activeUser.html($("#availableUsers option").length)};
eligibleUserCount();
availableUserCount();
$('#availableUsers').click(function () {
$('#availableUsers option:selected').remove().appendTo('#eligibleUsers');
availableUserCount();
eligibleUserCount()
});
$('#eligibleUsers').click(function () {
$('#eligibleUsers option:selected').remove().appendTo('#availableUsers');
availableUserCount();
eligibleUserCount()
});
http://jsfiddle.net/8gkLyfe3/5/
Using return in the first line of the functions prevents any other code from executing in that block.
Check out my fiddle for a functionalized way to perform this
function setUserCounts(){
availableUserCount = $("#availableUsers option").length;
eligibleUserCount = $("#eligibleUsers option").length;
activeUser.html(availableUserCount);
eligibleUser.html(eligibleUserCount);
}
http://jsfiddle.net/8gkLyfe3/6/
Essentially, we add this function and then call it from within the click handlers, while also removing the
I have this javascript code
function editRerenderFix() {
console.log("edit render start");
textAreaFix();
console.log("edit render middle");
setupDates();
console.log("edit render end");
}
/** Function to auto expand out the text area to hold all content **/
function textAreaFix() {
jQuery('textarea').on( 'change keyup keydown paste cut', function (event){
jQuery(this).height(100);
jQuery('textarea').each(function() {
jQuery(this).height(jQuery(this).prop('scrollHeight'));
});
});
return null;
}
/** Function to fix and set the custom date/time picker **/
function setupDates() {
jQuery('.dateFormat').remove();
var inputs = jQuery('.inputDate');
jQuery(inputs).each(function() {
var input = jQuery(this).val().split('/')[2];
if(input.length > 4) {
input = input.split(" ")[0];
}
if(input < '2015') {
jQuery(this).val("");
}
});
console.log("Setup Dates function ran");
jQuery('.inputDate').datetimepicker();
}
This function is called using the onComplete ajax method. The problem is that when it runs only textAreaFix() is called. In the console only "edit render start" and "edit render middle" show up.
The reason that "Setup Date function ran" first is because I have this function,
jQuery(document).ready(function() {
jQuery.material.init();
textAreaFix();
setupDates();
tourStep();
easterEgg();
});
How can I get the setupDates() function called?
EDIT:
I added more debugging to setupDates(),
/** Function to fix and set the custom date/time picker **/
function setupDates() {
jQuery('.dateFormat').remove();
var inputs = jQuery('.inputDate');
console.log(inputs);
jQuery(inputs).each(function() {
var input = jQuery(this).val().split('/')[2];
console.log(input);
if(input.length > 4) {
console.log("Input > 4");
input = input.split(" ")[0];
console.log(input);
}
if(input < '2015') {
console.log("Fix 2015 dates");
jQuery(this).val("");
}
});
console.log("Setup Dates function ran");
jQuery('.inputDate').datetimepicker();
}
When I run this I get,
I am not sure where the "undefined" comes from though.
My guess is that it is displaying undefined because the loop is repeating and jQuery(this).val().split('/')[2] is causing a problem. Maybe console.log on this and this.val() right at the beginning of the loop's block? – James Nearn 30 mins ago
I have the following code which changes the text in a certain element on click depending on the text value present in the element at the time the event is fired.
http://jsfiddle.net/TNDhL/
$('#left').on('click', function (){
if ($("#textContainer:contains('something')").length) {
$('#textContainer').text('third text replacement');
$('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
$('#textContainer').text('now the next item');
$('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
$('#textContainer').text('new text here');
$('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
$('#textContainer').text('something');
$('.elsewhere').text('text here');
}
});
$('#right').on('click', function (){
if ($("#textContainer:contains('something')").length) {
$('#textContainer').text('new text here');
$('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
$('#textContainer').text('now the next item');
$('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
$('#textContainer').text('third text replacement');
$('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
$('#textContainer').text('something');
$('.elsewhere').text('text here');
}
});
Please see fiddle above for working version.
I'd like to find a way to make this more manageable in order to make extending this further easier. Is there a better way to handle this case? Condensing this into a function and using variables to store the value of #textContainer would be more ideal. Any suggestions?
Seems like a perfect case for a closure which can track your progress with a simple counter.. Could look something like this:
var myTextRotator = (function () {
var myPhraseArray = ["first phrase", "second phrase"],
counter = 0;
return {
clickLeft: function () {
counter -= 1;
return myPhraseArray[counter]; //return array item or do your processing here
},
clickRight: function () {
counter += 1;
return myPhraseArray[counter]; //return array item or do your processing here
}
};
}());
Tie the clickLeft and clickRight methods to an jQuery .on(). May have to add a conditional in there so the counter doesn't go below 0 or above the array length.
You would use this like:
$(".left").on("click", function () {
myTextRotator.clickLeft();
});
$(".right").on("click", function () {
myTextRotator.clickRight();
});
Just started with knockout and need to implement page change warning. Following is the code snippet. I just need an alert pop up as warning if any change is made on the page.
function parseViewModel() {
var viewModel = JSON.parse(getState());
viewModel.checking = ko.observable(false);
viewModel.Slider = new ko.observable(100 - viewModel.Slider);
viewModel.CausalsList = buildHierarchy(viewModel.Causals);
viewModel.Causals["-1"] = "Total Marketing Budget";
viewModel.GeographiesList = ko.observableArray(gl);
viewModel.Geographies["0"] = "All Geographies";
viewModel.ProductsList = ko.observableArray(pl);
viewModel.Products["0"] = "All Products";
.
.
.
return viewModel;
}
function bindModel() {
model = parseViewModel();
ko.dirtyFlag = function (root, isInitiallyDirty) {
var result = function () { },
_initialState = ko.observable(ko.toJSON(root)),
_isInitiallyDirty = ko.observable(isInitiallyDirty);
result.isDirty = ko.computed(function () {
return _isInitiallyDirty() || _initialState() !== ko.toJSON(root);
});
result.reset = function () {
_initialState(ko.toJSON(root));
_isInitiallyDirty(false);
};
return result;
};
model.dirtyFlag = new ko.dirtyFlag(model);
model.isDirty.subscribe(function () {
alert("Page change warning!");
});
ko.applyBindings(model, $('#const').get(0));
ko.applyBindings(model, $('#buttonDiv').get(0));
}
Referred Ryan Niemeyer's blog. Unfortunately, it's not working anymore. Any insights please?
You would want to subscribe to model.dirtyFlag.isDirty in your case rather than model.isDirty.
One way to do is by using customBinding. I'm not that familiar with KO either but this might be something you're interested on.
Basically you would do is :-
ko.bindingHandlers.myFunction = {
update : function(){
//do something
}
}
http://knockoutjs.com/documentation/custom-bindings.html
And call it on your element using :-
<h1 data-bind="myFunction:{}"></h1>
Also, a jsfiddle to show how it works. (If you change the value of the First Name and focus out of it then the customBinding gets triggered. )
http://jsfiddle.net/3vuTk
Not sure if it's the best practice though.