jquery mobile popup - better way to retrieve data? - javascript

I'm using this simple popup correctly initialized along with corresponding popupafterclose handler, wrapped appropriate in content div. It just works. -
<div id="start-activity-popup" data-role="popup">
here is popup.
<button id="start">Start</button>
<button id="cancel">Cancel</button>
</div>
But if I had to retrieve values from popup or know which button
was pressed - do I need to write another handler for each - start and cancel buttons ?
Is there a better way ?

You can just write one handler:
$("#start-activity-popup button").click(function() {
var clicked = this.id; //this is the id of the clicked button
//do stuff
});

Related

Saving into Local Storage with a Click Event

Hello stackoverflow: I am working on getting a click event save into local storage. However, I get that it is undefined as the answer. This is what I have so far as my click event:
$(document).ready(function() {
$(".btnlocalStorage").on("click", function() {
event.preventDefault();
console.log("I am clicked!")
var myContent = $(this).(".btnlocalStorage").val();
localStorage.setItem("myContent", myContent);
//localStorage.setItem("myContent", JSON.stringify(myContent));
})
})
This is the HTML part of it, a button and a text area:
<textarea type="text" class="TextBoxColors-17 form-control" id="TextBoxStorage-17" aria-label="5:00 PM" aria-describedby="inputGroup-sizing-sm"></textarea>
<button class="btn btn-primary btnlocalStorage" type="button" todo="saveToDo-11am"><i class="fa fa-floppy-o" style="font-size:18px;"></i>
</button>
What should happen is that when I type any content into the text area, when I click the save button, this content should be saved into local storage. I am getting the key name, but the value/content undefined. Please, help me get this working. Thanks!
You're trying to get the value of your button instead of the value of the textarea with:
$(this)
Your code should look like this :
$(document).ready(function(){
$(".btnlocalStorage").on("click", function() {
localStorage.setItem("myContent", $(".TextBoxColors-17").val());
console.log(localStorage.getItem("myContent"));
})
});
EDIT :
This code only works for one specific textarea, if you want to make it work for multiple textareas followed by a button, you must use :
$(this).prev()
"this" refers to the button wich triggered the event and the prev() function allow you to get the element just before it.
Be careful, your local storage item must have a different name from one button to another, otherwise all buttons will override the same item content, for the example I took the ID of your textarea but it can be any iterated variable :
$(document).ready(function(){
$(".btnlocalStorage").on("click", function() {
localStorage.setItem($(this).prop("id"), $(this).prev().val());
console.log(localStorage.getItem($(this).prop("id")));
})
});

How to enable and disable document event handler (specifically click)

I have a button, clicking on which, I have to enable the click event handler on the entire document. Once someone clicks now, I want to capture the dom selector of that element and disable the event handler again.
Is this question asked already? I searched a lot but couldn't find anything relevant. There are a lot of solutions on enabling or disabling event handler on a particular element, but I have to do it over the entire document. Here is my code -
JavaScript -
<script>
var select_target = false;
$(document).click(function(event) {
if (select_target) {
element.style.backgroundColor = "#FDFF47";
var text = $(event.target).text();
console.log(text) //This text should be the DOM Selector, which I'm not able to retrieve
select_target = false
}
})
$('.select_target').click(function() {
select_target = true
})
</script>
HTML -
<!-- Lot of code from the other parts of the webpage -->
<button name="ignore" type="button" class="btn btn-primary btn-md m-1 select_target">
Select Target
</button>
<!-- Lot of code from the other parts of the webpage -->
This gives me Select Target as the output instead of the DOM Selector of the element, which I wasn't expecting to be the target button in the first place, but whatever I click after clicking the select target button.
I know the code looks clumsy, but any help would be appreciated. Thanks!
It looks like the following code does what I'm expecting. It's for everyone who wants a similar thing to happen i.e., To be able to select the element from the page on which you want to perform specific operations with a clean and modifiable code.
Javascript -
<script>
var select_target = false;
$(document).click(function(event) {
if (select_target) {
event.preventDefault(); //If you click a link or a button, this helps in just selecting it and it won't perform it's default operation.
var text = $(event.target).text();
console.log(text)
select_target = false;
}
})
$(document).ready(function() {
$("body *").mouseenter(function(el){
if(select_target){
$(el.target).addClass("red-hover-box"); //To highlight the elements on hover
}
})
$("body *").mouseout(function(el){
if(select_target){
$(el.target).removeClass("red-hover-box"); //To remove the highlight on the elements. This will keep the element highlighted if you click on it, since the select_target's value would be false after the click.
}
})
})
$('.select_target').click(function() {
e.stopPropagation(); //To prevent the click on the button to be handled by the event listener.
select_target = true
})
</script>
CSS -
.red-hover-box{
border:1px solid red;
}
HTML -
<!-- Lot of code from the other parts of the webpage -->
<button name="ignore" type="button" class="btn btn-primary btn-md m-1 select_target">
Select Target
</button>
<!-- Lot of code from the other parts of the webpage -->
I'm still now able to figure out on how to get a unique identifier for the HTML element that has been clicked, and would update this answer once it's been figured out.
Thanks!

How to register to the onClick event of a Close button element

I am using a UI Action in serviceNow to call a GlildeModalForm popup window.
That window has a X(close button) that I need to catch when the user press that button. I do not have any feedback on that button click and need to catch it
I have seen some exemple on ServiceNow communty where you can register to some callback function but it is used only after submitting the form.
var modalForm = new GlideModalForm('Create User Member' , tableName );
modalForm.setOnloadCallback(formOnLoadCallback);
modalForm.setCompletionCallback(formAfterSubmitCallback);
modalForm.render();
function formOnLoadCallback() {
//Access GlideModal g_form to set field for the new record
var d_form = window.frames["dialog_frame"].g_form;
d_form.setValue('field', g_form.getValue('field'));
d_form.setValue('field', g_form.getValue('field'));
}
function formAfterSubmitCallback(action_verb, sys_id, table, displayValue) {
//Get the newly created record sys_id and then set e.g a value to the starting record
g_form.setValue('field', sys_id);
//Save the record
g_form.save();
}
By using the element inspector of my browser i can see that the Close button is define as below :
<button data-dismiss="GlideModal" class="btn btn-icon close icon-cross"
id="x_58872_needit_cascadesequence_closemodal"> <span
class="sr-only">Close</span>
</button>
I would need to find that button from the script above and then register to its onClick, then in onClick even I would like to simply send an alert of potential loosing data message
Thanks for help on this
Since click events bubble up the DOM, you can simply register a click listener on the document. The event object is automatically passed to the handler function you pass to addEventListener(). Inside the handler, you can check if the click event was raised on an element that has data-dismiss="GlideModal":
document.addEventListener('click', function(e) {
if (e.target.matches('[data-dismiss="GlideModal"]') {
alert ('Close modal clicked');
}
})
This is called a delegate event listener because the listener is not registered on the element you expect the event to occur on, but higher up the DOM tree. This also has the advantage that it works for dynamically created elements (like supposedly your modal HTML).
Edit: I just double-checked the HTML you've shown. Possibly you might have to check whether the click originates from the span inside the button, rather than the button itself:
document.addEventListener('click', function(e) {
if (e.target.matches('[data-dismiss="GlideModal"] span') {
alert ('Close modal clicked');
}
})
The SerivceNow GlideModalForm extends GlideModal which supports event registration via the on method. There are 2 supported events that might work for what you want:
closeconfirm: called by the destroy method, can be used to abort destruction
beforeclose: called once the window has already been hidden
I think you can just use the closeconfirm event to know when the close happens, you don't necessarily need to care about aborting the action, and it'll fire as soon as the user clicks the button, but before the window is removed.
Notably, however, this will probably also fire when the user clicks the "Close" button (not the X) which optionally shows via the modal preference: myGlideModal.setPreference('sysparm_button_close', 'Close')
Here's a rough example:
var myGlideModal = new GlideModal(...);
dd.on("beforeclose", function (){ /* do stuff, maybe return false to cancel */ });
You can create an onclick function as follows:
html:
<button data-dismiss="GlideModal" class="btn btn-icon close icon-cross"
id="x_58872_needit_cascadesequence_closemodal" onclick="myFunction()">
<span class="sr-only">Close</span>
</button>
JavaScript:
function myFunction() {
alert("I am an alert box!");
}

Firing a HTML attribute using angularjs without using a button

I have a HTML & javascript custom made attribute that will show a popup containing message when a button is clicked.
Button to click :
<a data-deploy-menu="menu-sheet-tutorial-1" href="#">Tap Here to open</a>
The sheet/popup that opens :
<div id="menu-sheet-tutorial-1" class="menu-wrapper">
<div class="content">
<h4>Hello, I'm action sheet!</h4>
Close
</div>
</div>
The data-deploy-menu="menu-sheet-tutorial-1" is what firing the event to open the sheet.
And, this is what happens when the button is clicked in javascript.
$('a[data-deploy-menu]').on( "click", function(){
var menu_ident = $(this).data('deploy-menu');
$('#'+menu_ident).addClass('active-menu');
$('.fade-bg').addClass('active-fade'));
});
And, this is what happens when the close button is clicked
$('.close-menu').on('click', function(){
$('.menu-wrapper').removeClass('active-menu'));
$('.fade-bg').removeClass('active-fade'));
});
The problem i'm facing is that I'm not able to fire this event without a button click.
So, using angularJS, I want to fire this sheet automatically when the form is submitted or when a particular condition is true.
AngularJS has a directive calls ngSubmit who could be provided with an expression like a function. Here is te documentation:
https://docs.angularjs.org/api/ng/directive/ngSubmit

jQuery Tools Overlay - Two buttons with different close conditions

I have the following jQuery Tools overlay:
<div id='editDescriptiontOverlay' class='overlay'>
<input type='text' class='description'/>
<button class='save'>Save</button>
<button class='close'>Cancel</button>
</div>
Background info: The HTML for this overlay is static. I have a list of items each having their own Edit link. When a given Edit link is clicked, the overlay is generated by calling: $('a[rel=#editDescriptionOverlay]').overlay( { ... } ); and the input is populated with the respective text.
The Save button needs to validate the text in the input element and close the overlay if and only if the validation is successful. Otherwise, the overlay must remain open. The Cancel button simply closes the overlay without validation.
The validation logic has been independently verified to work.
I've tried setting the onBeforeClose event during overlay generation as a means of validation. Taking this approach, both the Save and Cancel buttons needed the same class .close. Unfortunately, the condition applies to all .close elements in the overlay so even the Cancel button was validating.
I've also tried binding a click event to the Save button immediately after generating the overlay, like so:
$('.save', $('#editDescriptionOverlay'))
.unbind('click')
.bind('click', function() {
if (validateText) {
console.log("Validation passed.");
$('a[rel=#editDescriptionOverlay]').overlay().close();
}
else {
console.log("Validation failed.");
}
});
The console.log's confirm that the validation is working, but the overlay doesn't close.
Any insight is appreciated, thanks.
For jquery widgets, public methods should be called as follows:
$('a[rel=#editDescriptionOverlay]').overlay("close");
wherein close is the method name that you wish to call.
If a method accepts parameters, then, these should be added as parameters right after the method name.
Updated:
I am sorry. I just had time to check what jQuery Overlay Tools is and I am mistaken. This is not similar to any jQuery widget, hence, my comment above will also not work for this case. I tried your code above and it worked. The overlay was closed. But, when I tried it with multiple <a rel="#editDescriptionOverlay">, which I think is what you did. It did not work. My suggestion would be to use just one <a rel="#editDescriptionOverlay"> and use a dummy anchor element for the Edit link, which when clicked would trigger a click to <a rel="#editDescriptionOverlay">. You can do something like this:
<script type="text/javascript">
$(document).bind("ready", function(e){
$("a[rel]").overlay();
$('.save', $('#editDescriptionOverlay')).unbind("click").bind("click", function(){
if (validationValue){
$("a[rel=#editDescriptionOverlay]").overlay().close();
}
});
});
function clickThis(){
$("a[rel=#editDescriptionOverlay]").trigger('click');
return false;
}
</script>
Edit1
Edit2
<a rel="#editDescriptionOverlay">Dummy</a>
<div id='editDescriptionOverlay' class='overlay'>
<input type='text' class='description'/>
<button class='save'>Save</button>
<button class='close'>Cancel</button>
</div>
I'd prefer binding an event to the save button (the second one you mentioned). Actually your code looks fine, except that you probably don't need to bind the event to $('#editDescriptionOverlay') and you have typo in your html markup above (<div id='editDescriptiontOverlay' should be <div id='editDescriptionOverlay').
See here for an example.

Categories

Resources