I want to assign a click handler for button in the page load function. I then want to handle the actual click of the button at a later time with the following code snippet:
$("#finish").off('click').on('click', function () {
var sku = $("#productSKU").val();
var name = $("#productName").val();
var affiliateId = $("#AffiliateID").val();
var Errors = "";
var category = null;
var defaultName = $('#defaultImgName').val();
if ($("#childCategories_" + categoryLevel).length == 0) {
category = $("#categoryList").val();
}
else if ($("#childCategories_" + categoryLevel).val() == 0) {
category = null;
}
else {
category = $("#childCategories_" + categoryLevel).val();
}
if (!sku) {
Errors += "<li> You can not add a product without an Item Code</li>";
}
if (!name) {
Errors += "<li> You can not add a product without a Name</li>";
}
if (!category) {
Errors += "<li> You can not add a product without a Category</li>";
}
if (Errors != "") {
cua({ text: Errors, type: 'danger' })
}
else {
data.formData = { productName: name, productSKU: sku, affiliateID: affiliateId, categoryID: category, defaultImgName: defaultName }
data.submit();
}
});
How do I assign the click event handler in the page load, and then trigger the actual event of the click later on?
Reason for this is it's causing errors where the button is unresponsive if an image is not uploaded, which I found to be caused by an event handling problem.
$(document).ready(function(){
$("#finish").on('click', yourfunctionhere)
});
You can put your code in a seperate function, so if you want to turn it off, then on again you can do it with just 1 line of code.
$("#finish").on('click', yourfunctionhere)
To execute the function you can trigger the click (when the handler is on):
$("#finish").trigger('click');
(thanks #putvande for reminding)
Related
This is an on-click function for the identifier button. This function will trigger a popup design function when the user clicks on some feature on the map. I want this click functionality on that feature to be suppressed when the user clicks the identifier button a second time. This means the identifier button should act like a start-stop switch.
This function is inside useEffect() and the #IdentifierClick is the id for the button which is in return{} part which will trigger the click event.
const IdentifierClick = () => {
console.log("working");
// clicktimes = clicktimes+1;
// console.log("Button click times ",clicktimes)
if((enableIdentify == false))
{
initialMap.on('singleclick', function (evt)
{
console.log(evt, "printevt");
var myLayerChecked;
console.log(layerlist, "printlayerlist");
for (let i = 0; i <= 4; i++)
{
layerlist[1].values_.layers.array_[i].values_.layers.array_.forEach(arrayItem => {
myLayerChecked = arrayItem.state_.visible;
console.log("myLayerChecked", myLayerChecked);
// console.log(layerlists,"printlayerlist");
if (myLayerChecked == true) {
document.getElementById('popup-content').innerHTML = '<p class="identifier_p"><b>Identifier Details</b></p>';
console.log("My Array Data", arrayItem.values_.source)
designHtml(evt, arrayItem.values_.source, arrayItem.values_.title);
enableIdentify = true;
}
else
{
console.log("No Layer is checked");
}
});
}
})
}
else {
}
});
The intialMap.on('singleclick',function()) should be enabled and disabled by IdentifierClick function when we click to trigger the function. Please help me achieve this task.
On a checkbox change event, one of a javascript bind the toggle action.
Later on(in a different script) I want to change toggle action based on a condition.
Ex.
script 1:
$(document).ready(function () {
var shipFields = $('.address1 input');
$("input[name = 'same_as_bill']").on("change", function (evt) {
toggleFields(shipFields, !$(this).is(":checked"));
});
function toggleFields(fields, show) {
var inputFields = $("li", fields).not(".sameas, .triggerWrap");
inputFields.toggle(show);
}
}
Script 2:
$(document).ready(function () {
$('li.sameas input').click(function (sender) {
var target = $(sender.target);
var selectedCountryValue = $('li.country select', target.closest('fieldset')).val();
// determine data method based on country selected
if (selectedCountryValue === "xxx") {
ShowAddress(true, target);
} else {
ShowAddress(false, target);
}
});
function kleberShowAddress(show, target) {
if (show) {
$('li.address).hide();
} else {
$('li.address).show();
}
}
});
Issue I have here is, my site load the script 1 first and then the script 2. So by the time script 2 performs the action, toggle action is queued and will trigger that after the changes from script 2, that will revert the changes which I want.
Is there a way to remove the action in the queue? or stop happening first request. I do not want to use .unbind() which will stop triggering script 1 function. I just want to stop the action when ever it meets the condition in script 2.
Please note: above functions are trimmed to show less codes.
add var isActive = true; and use it to check in first script.
In script 2, you can call isActive = false any time you want to disable the first script's function or isActive = true for re-enable them.
Your code will look like:
//script1
var isActive = true;
$(document).ready(function() {
var shipFields = $('.address1 input');
$("input[name = 'same_as_bill']").on("change", function(evt) {
if (isActive) {
toggleFields(shipFields, !$(this).is(":checked"));
}
});
function toggleFields(fields, show) {
if (isActive) {
var inputFields = $("li", fields).not(".sameas, .triggerWrap");
inputFields.toggle(show);
}
}
});
//script2
$(document).ready(function() {
isActive = false;
$('li.sameas input').click(function(sender) {
var target = $(sender.target);
var selectedCountryValue = $('li.country select', target.closest('fieldset')).val();
// determine data method based on country selected
if (selectedCountryValue === "xxx") {
ShowAddress(true, target);
} else {
ShowAddress(false, target);
}
});
function kleberShowAddress(show, target) {
if (show) {
$('li.address').hide();
} else {
$('li.address').show();
}
}
});
I have this code which asks a question; askQuestion()
which runs as the page loads and runs again when a button with id wb_option_button is clicked.
But I noted that at the first click, its runs well, but the second click never never run. I want to know what is wrong with it (in case), and how to do it work.
var q_selected;
var q_number = 1;
var questionDiv = $('.wb_questions');
var optionDiv = $('div#wb_options');
function askQuestion()
{
questionDiv.html(questions[q_number]['question']);
optionDiv.html('<button class="wb_option_button" id="wb_option_button" title="click to answer">'+questions[q_number]['options'][0]+'</button>'+
'<button class="wb_option_button" id="wb_option_button" title="click to answer">'+questions[q_number]['options'][1]+'</button>'+
'<button class="wb_option_button" id="wb_option_button" title="click to answer">'+questions[q_number]['options'][2]+'</button>'+
'<button class="wb_option_button" id="wb_option_button" title="click to answer">'+questions[q_number]['options'][3]+'</button>'
);
}
function checkAnswer(q_answer)
{
if(q_selected === q_answer)
{
return true;
}
}
function isCheckpoint()
{
if(checkpoints[q_number]!=null)
{
return true;
}
else
{
return false;
}
}
askQuestion();
$('button.wb_option_button').click(function(){
q_selected = $(this).text();
if(checkAnswer(questions[q_number]['answer'])===true)
{
if(isCheckpoint()===true)
{
showRank(q_number);
}
else
{
q_number+=1;
//alert(q_number);
askQuestion();
// showStage();
return q_number;
}
}
else
{
alert("You failed");
}
});
var questions is an object, var checkpoints ia also an object.
All of your buttons have the same ID. When you get an Element by id, it will only return the first element it finds with this id. If you want to get multiple elements you have to get them with another selector, ie. by className or any other means then by ID.
Edit : You are in fact selecting the buttons by className. The problem is that when you call askQuestion() again, the click listener is not added to the new buttons, so you might want to move the click event assignment inside askQuestion
Hope this helps.
After a little more digging, I arrived at this solution which works perfectly.
Thank you all for your help!!!
$('.wb_options').on('click','.wb_option_button',function(){
q_selected = $(this).text();
if(checkAnswer(questions[q_number]['answer'])===true)
{
if(isCheckpoint()===true)
{
showRank(q_number);
}
else
{
q_number+=1;
askQuestion();
alert(q_number);
// showStage();
//return q_number;
}
}
else
{
alert("You failed");
}
});
(Fiddle: http://jsfiddle.net/qdP3j/)
I have this div:
<div id="addContactList"></div>
I use AJAX and change its innerHTML with something like:
<div id="<%= data[i].id %>">
<img src="<%= picture %>">
<button class="addAsFriend">Add as Friend</button>
</div>
In my JS, I have
$('#addContactList').on('click', '.addAsFriend', function () {
$(this).text('Request sent!');
$(this).attr('disabled','disabled');
});
What happens is that when I click on a button for the first time, I see that the click function ran; "Request sent!" is being shown but it immediately reverts back to the initial button. When I click a second time, it works fine.
I tried using event.stopPropagation and preventDefault but same issue happens.
As stated, it probably comes from the AJAX part:
Basically, I have 3 input fields on a page, and users can enter data in them. If there is data in the fields, they are posted and I use the data to query the database. There is a delay function of 250ms to prevent posting immediately every time a letter is typed.
var addContactsList = document.getElementById('addContactList');
$('#addContactForm').on('keyup change', function () {
var self = this;
// Add a short delay to not post for every letter typed quickly
delay(function() {
var userSearchData = {};
userSearchData.userId = 23;
$.each(['email', 'username', 'fullName'], function (_, el) {
var val = $(self).find('input[name="' + el + '"]').val();
if (val.length >= 3) {
userSearchData[el] = val;
}
});
if ( !isEmpty(userSearchData) ) {
$.post('/post/addContact', { userSearchData: userSearchData }, function (data) {
if (data) {
new EJS({url: '/templates/addAContact.ejs'}).update('addContactList', { data: data })
} else {
addContactsList.innerHTML = '';
}
});
} else {
addContactsList.innerHTML = '';
}
}, 225 );
});
It's because of the "keyup change". Change was being triggered again when clicking elsewhere (the add friend button).
Now though the problem is when people use the autocomplete feature using the mouse, it will not trigger because change isn't there anymore.
As you noticed, the change event fires when your input field loses focus (when you click on the button). You can keep the change event, and check if the change event is firing while the input field is focussed
$('#addContactForm').on('keyup change', function () {
if (!$(document.activeElement).is('input')) return; //add this line
In my application after tapping on a one button it gives and alert.There are two button on alert window: 1. Cancel 2. Ok
I have tried to tap on OK by using the solution given on the forum but it dosen't work.
UIATarget.onAlert = function onAlert(alert) {
var title = alert.name();
UIALogger.logWarning("Alert with title '" + title + "' encountered!");
if (title == "Attention")
{
alert.buttons()["OK"].tap();
return true; // bypass default handler
}
return false; // use default handler
}
Function for handling alert dosen't called.Can anyone help me on this issue?
Thanks in advance.
UIATarget.onAlert = function onAlert(alert)
{
UIATarget.localTarget().delay(1);
UIALogger.logMessage("alertShown");
target.captureScreenWithName("AlertCaptured");
return true;
}
app.alert().buttons()["OK"].tap();
My solution to this problem was to add an one second delay after the function that handles the alert. You can not end your script with that function.
UIATarget.onAlert = function onAlert(alert) {
var title = alert.name();
UIALogger.logWarning("Alert with title '" + title + "' encountered.");
if (title == "Are you sure you want to delete this?") {
alert.buttons()["Delete"].tap();
return true; //alert handled, so bypass the default handler
}
return false;
}
target.delay(1);