How to transfer an element in jQuery? - javascript

I've got this function that calls upon a modal
$('#btn1').click(function () {
// Get textfield
var textfield = $('#txt1');
// Get value
var input = textfield.val();
// Check if the value is already in the database
var json = textfield.data('json');
if (itemExists(input, json)) {
// Stuff
} else {
$('#modalAddText').append('X does not exist');
$('#myModal').modal();
}
});
Then this to check if the user clicked "OK"
$('#modalOk').click(function () {
insertItem(itemone, itemtwo);
$('#myModal').modal('hide');
});
So the problem is I don't have access to the textfield in the first function anymore, so how can I get/keep access to it?
And I can't just do $('#txt1'); because I have multiple txtfields
So can I somehow transfer the textfield variable?

Try to declare textfield in outer scope.
That is:
var textfield = $('#txt1');
$('#btn1').click(function () {
... // textfield is achievable
});
$('#modalOk').click(function () {
... // textfield is achievable
});

Related

jQuery to Javascript adding required attribute

So I have the following jQuery code that I've built out that checks whether a on change event has been triggered on #rtk5 and then either removes or adds the 'required' attribute.
Works perfectly in jQuery:
// Make checkbox textboxes not required unless checked
$(document).ready(function() {
$('#rtk5').change(function() {
if ($('.rtk5ReqField').attr('required')) {
$('.rtk5ReqField').removeAttr('required');
}
else {
$('.rtk5ReqField').attr('required','required');
}
});
});
I would like to convert it to JavaScript with a function call, but I can't seem to figure out how to properly do it.
Error:
TypeError: rtk5req.getAttribute is not a function
Here is my attempt:
var rtk5req = document.getElementsByClassName('rtk5ReqField');
function rtk5Required() {
rtk5req.addEventListener('change', (e) => {
if (rtk5req.getAttribute('required')) {
rtk5req.removeAttribute('required');
} else {
rtk5req.getAttribute('required', 'required');
}
});
}
rtk5req.addEventListener('change', rtk5Required());
document.addEventListener('DOMContentLoaded', rtk5Required);
rtk5Required();
Updated code: Removed the repetitive change call
var rtk5req = document.getElementsByClassName('rtk5ReqField');
function rtk5Required() {
if (rtk5req.getAttribute('required')) {
rtk5req.removeAttribute('required');
} else {
rtk5req.getAttribute('required', 'required');
}
}
rtk5req.addEventListener('change', rtk5Required());
document.addEventListener('DOMContentLoaded', rtk5Required);
rtk5Required();
Updated code #2:
Thanks all for all the hard work, there's one small issue that I'm still experiencing and had to make some tweaking - When I uncheck the checkbox, it doesn't remove the required tag placed on rtk5Declaration from which it did in the jQuery.
var rtk5_selection = document.getElementById('rtk5');
document.addEventListener('DOMContentLoaded', () => {
rtk5_selection.addEventListener('change', () => {
if (rtk5_selection.getAttribute('required')) {
document.getElementById('rtk5Declaration').removeAttribute('required');
} else {
document.getElementById('rtk5Declaration').setAttribute('required', 'required');
}
});
});
Thanks so much all!
Since you only have one element you should be using its ID instead of its class, and avoiding the complication caused by document.getElementsByClassName returning a pseudo-array of elements instead of a single element.
NB: use setAttribute to change an attribute's value, or better yet (as shown in the code below) use the direct boolean property that mirrors the element's attribute.
document.addEventListener('DOMContentLoaded', () => {
const rtk_sel = document.getElementById('rtk5');
const rtk_dec = document.getElementById('rtk5Declaration');
rtk_sel.addEventListener('change', () => {
rtk_dec.required = !rtk_sel.checked;
});
});
Thanks all for the contribution, below is the working version which I have tweaked:
var rtk5_selection = document.getElementById('rtk5');
var rtk5declaration = document.getElementById('rtk5Declaration');
function rtd3Declaration() {
if (!rtk5_selection.checked) {
rtd3declaration.removeAttribute('required');
} else {
rtd3declaration.setAttribute('required', 'required');
}
}
rtk5_selection.addEventListener('change', rtd3Declaration);
document.addEventListener('DOMContentLoaded', rtd3Declaration);
rtd3Declaration();

Change value of first iteration input with next iteration input value

Structure Concept:-
Basically, i am trying to create the modal window containing input and that modal window currently fires when the input on index page get focused for that I have used data attribute to make a link between them by assigning them same attribute value.
Javascript Concept:-
for the modal window, I have created the modal object. and model object contains a bindModal method which takes one argument and that argument is data attribute value. after taking that value bindModal method will search dom elements containing that particular value and after the search, I iterate over them using each loop.
Problem
So basically I want whenever user starts typing on the model input it should get written automatically in input on the index page.
I will appreciate you all if guys help me out to make my code more optimized and well structured and most important thing is that let me know what mistake I have done in overall work Thanks
JavaScript Code
var modal = function () {
this.toggleModal = function () {
$('#modal').toggleClass('content--inActive').promise().done(function () {
$('#modal__close').on('click',function(){
$('#modal').addClass('content--inActive');
});
});
}
this.bindModal = function (bindVal) {
var bindValue = $(document).find('[data-modal-bind = ' + bindVal + ']');
$.each(bindValue, function (index) {
var bind1 = $(this);
if(index === 1) {
var bind2 = $(this);
$(bind1).change(function (){
$(bind2).val(bind1.val());
});
}
});
}
}
var open = new modal();
$('#input_search').on('click',function(){
open.toggleModal();
open.bindModal('input');
});
Here is one way to do what you want:
var modal = function() {
this.bindModal = function(bindVal) {
var bindValue = $('[data-modal-bind = ' + bindVal + ']');
bindValue.each(function(index) {
$(this).keyup(function() {
var value = $(this).val();
bindValue.each(function(i, e) {
$(this).val(value);
});
});
});
}
}
$('#input_search').on('click', function() {
var open = new modal();
open.bindModal('input');
});
Changes done:
I cached the inputs with same binding values in bindValue variable, and then bound the the keyup event for each of them. On keyup, the value of the current input is get in value, which is then assigned to each input using the inner loop.
This makes the inputs to be in sync while typing. Hope that solves your issue.

Handle cell click event on Angular Gantt

I am trying to customize the behaviour of Angular Gantt.
On cell click : I have to get the current cell value & corresponding header value.
I gone thru the documentation present in this url : https://angular-gantt.readthedocs.io/en/latest/
but couldn't get the required event.
Is there any event present to achieve this functionality. Any help is much appreciated.
I tried following code
mainApp.controller("TestController", function ($scope, TestService) {
$scope.registerApi = function (api) {
api.tasks.on.change($scope, onTaskChange); //working
//TO handle the cell click & corresponding header value
api.core.getDateByPosition($scope, getHeader)
//api.core.on.ready($scope, getDateByPosition) //not working
//api.core.on.rendered($scope, getDateByPosition) //not working
}
var onTaskChange = function (selected) {
$scope.currCell = selected.model;
console.log("onTaskChange: " + selected.model.name);
};
var getHeader= function (getHeader) {
// I should get the current clicked cell header value. But getting error
};
}
Answering my own question as someone may find it useful.
I am able to achieve this from this link
https://angular-gantt.readthedocs.io/en/latest/configuration/customize/
Following is the code which I used:
$scope.registerApi = function (api) {
api.directives.on.new($scope, function (dName, dScope, dElement, dAttrs, dController) {
if (dName === 'ganttTask') {
dElement.bind('click', function (event) {
debugger;
$scope.RowName1 = dScope.task.row.model;
$scope.currentTask = dScope.task.model;
});
}
else if (dName === 'ganttRow')
{
dElement.bind('click', function (event) {
debugger;
$scope.RowName = dScope.row.model.name;
$scope.Header = api.core.getDateByPosition(event.offsetX, true)
});
}
});

How to save the checkbox state even after the page refresh?

I have multiple checkboxes on my UI which when checked doing some operation. But the moment I refresh the page all the check boxes are unchecked again. How can I use AJS.Cookie (Atlassian Javascript framework) to save the state. Source Code which I have written but it gives the cookie value as undefined.
'#generate-canvas-button' is the id of the button which passes all the checked checkboxes.
// Wait until the page is completely loaded.
AJS.$(document).ready(function() {
// Iterating over all checkboxes on page.
$('input:checkbox').each(function() {
// Getting checkbox name.
var name = $(this).attr('name');
// Checking saved cookie.
if (AJS.Cookie.read(name)) {
// Updating checkbox state.
$(this).prop('checked', true);
}
});
// Clicking the OK button should run submit(), pop up displays all checked boxes
$('#generate-canvas-button').click(submit);
});
function submit() {
var checked = [];
var targetGroupActors = [];
var bigPictureActors = [];
var bigPictureImpacts = [];
var productDetailsActors = [];
var productDetailsDeliverable = [];
// Iterating over all checkboxes on page.
$('input:checkbox').each(function() {
// Getting checkbox name.
var name = $(this).attr('name');
// Checking checkbox state.
if ($(this).is(":checked")) {
// Saving checkbox name to cookie.
AJS.Cookie.save(name, true);
} else {
// Remove checkbox state from cookie.
AJS.Cookie.erase(name);
}
if ($(this).is(":checked")) {
impactMapValues = $( this ).prop('id');
impactMapActor = $( this ).prop('name');
var value = document.getElementById(impactMapValues).value;
if (impactMapActor == "actor-checkbox") {
targetGroupActors.push(value);
}
if (impactMapActor == "impact-checkbox") {
var result = value.split(",");
actor_value = result[0];
impact_value = result[1];
bigPictureActors.push(actor_value);
bigPictureImpacts.push(impact_value);
}
if (impactMapActor == "deliverable-checkbox") {
var result = value.split(",");
actor_value = result[0];
deliverable_value = result[1];
productDetailsActors.push(actor_value);
productDetailsDeliverable.push(deliverable_value);
}
checked.push(value);
}
});
addTotargetGroup(targetGroupActors);
addToBigPicture(bigPictureActors,bigPictureImpacts);
addReleaseTarget(productDetailsActors,productDetailsDeliverable);
}
Try this approach:
// Wait until the page is completely loaded.
$(document).ready(function() {
// Iterating over all checkboxes on page.
$('input:checkbox').each(function() {
// Getting checkbox name.
var name = $(this).attr('name');
// Checking saved cookie.
if (AJS.Cookie.read(name)) {
// Updating checkbox state.
$(this).prop('checked', true);
}
// Attaching onchange handler.
$(this).change(function() {
// Checking checkbox state.
if ($(this).is(":checked")) {
// Saving checkbox name to cookie.
AJS.Cookie.save(name, true);
} else {
// Remove checkbox state from cookie.
AJS.Cookie.erase(name);
}
});
});
});
Use viewstate concept intead of using other cookies logic
Wrap all your logic in
AJS.toInit(function ($) {
// You can use $ instead of AJS.$ here
...
});
This is Atlassian's equivalent of $(document).ready(...) which allows all the Atlassian code to load before you call yours.

Making sure my form isn't being submitted multiple times with jquery show/hide

So when someone hits Reply, I am attempting to pop-up a form to type your response. Once the form is submitted, it disappears until the next time you hit Reply.
This is working except after the 1st time, I am submitting the information twice. If I do it a third time, the form submits three times. Essentially what is happening is the previous form doesn't seem to be resetting after I hide it again.
I checked this website/google and have tried using reset() but it didn't work. Below is the code:
$(document).on('click', '.secretfeed button', function () {
var message_id = $(this).attr('name');
$(".comment_box").show();
$("#m_id").val(message_id);
var value = document.getElementById("m_id").value;
$('#comment_form').submit(function (e) {
e.preventDefault();
var commentData = $(this).serialize();
$.post('../../process_comment.php', commentData, processData);
function processData(data) {
//$('comment_form').reset()
$(".comment_box").hide();
$('#comment_form')[0].reset();
RefreshFeed();
}
});
});
Rather than initializing the submit function on every click, move it outside the click function. jQuery may be creating an instance of it for each click.
$('#comment_form').submit(function (e) {
e.preventDefault();
var commentData = $(this).serialize();
$.post('../../process_comment.php', commentData, processData);
function processData(data) {
//$('comment_form').reset()
$(".comment_box").hide();
$('#comment_form')[0].reset();
RefreshFeed();
}
});
$(document).on('click', '.secretfeed button', function () {
var message_id = $(this).attr('name');
$(".comment_box").show();
$("#m_id").val(message_id);
var value = $("#m_id").val();
});
The alternative is to unbind the click function before reusing it.
We want a reusable way to handle the state. We will save the state of the button in a boolean which gets turned on and off depending on the status of the request. The pattern is the following:
var isSending = false;
function onSubmit() {
isSending = true;
// Send data
}
function onComplete() {
// done sending data
isSending = false;
}
if (!isSending) {
onSubmit();
}
// When data sending is finished:
onComplete();
The above can be encapsulated in a more functional way that uses promises to manage the state. (jQuery AJAX functions all return a promise-like object):
function oneAtATimeFunction(promisedFunction) {
var pendingPromise;
function reset() { pendingPromise = null; }
return function() {
if (pendingPromise) { return pendingPromise; }
pendingPromise = promisedFunction.apply(promisedFunction, arguments)
.always(reset);
return pendingPromise;
}
}
function submitForm() {
return $.ajax({
url: '/foo',
method: 'POST',
data: { data: 'from form' }
});
}
$('#submit-button').on('click', oneAtATimeFunction(submitForm));
Adding a little flare to the UI We can add a way to turn on and off the submit button. First we will define a helper function to handle the on and off state:
function buttonEnable(enabled) {
$('#submit-button').attr('disabled', !enabled);
}
buttonEnable(false); // disable the button
buttonEnable(true); // enable the button
Putting it all together:
function onClick() {
buttonEnable(false);
return onSubmit()
.always($.proxy(buttonEnable, null, true));
// The above is also the same as:
// .always(function() { buttonEnable(true); });
}
$('#submit-button').on('click', oneAtATimeFunction(onClick));
To see this in action here is a JSBin example.

Categories

Resources