Change value of first iteration input with next iteration input value - javascript

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.

Related

How to assign event handlers to multiple elements (colorPicker)

I'm trying to find a way to assign event handlers to each box that I create dynamically. At the moment the user can click "Add above" or "Add below" and 2 rows of boxes will appear wherever they clicked.
I'm trying to make it so that when the user clicks on a specific square, a colorPicker will pop up and that specific square's color can be changed.
However, my program is a bit buggy, it only works for the first square that the user clicks on and the colorPicker never pops up again.
Does anyone know how I can go about fixing this or if there is a better alternative?
My code:
http://codepen.io/anon/pen/bwBRmw
var theParent = document.querySelector(".container");
theParent.addEventListener("click", doSomething, false)
//var picker = new Picker()
function doSomething(e) {
console.log("gets inside doSomething")
console.log(e.target)
console.log(e.currentTarget)
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
console.log("Hello " + clickedItem);
var k = document.getElementById(clickedItem)
var picker = new Picker(k)
picker.show();
}
picker.on_done = function(colour) {
$(k).css('background-color',colour.rgba().toString());
picker.hide()
}
//e.stopPropagation();
}
I noticed in your CodePen that you didn't post the full code for doSomething. You have a problem because the picker variable is local to the function. If the code execution doesn't land inside the IF-statement, the picker variable is never created. Simply uncomment the code declaring the picker variable outside the function, and remove the var directive from in front of the line of code where you instantiate a new picker. Furthermore, you need to reset the "parent" element of the picker, since there is only one picker on the page: picker.settings.parent = k;
var picker = null; // Initialize global variable
function doSomething(e) {
console.log("gets inside doSomething")
console.log(e.target)
console.log(e.currentTarget)
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
console.log("Hello " + clickedItem);
var k = document.getElementById(clickedItem)
// Reference the global "picker" variable
if (!picker) {
picker = new Picker(k)
} else {
// Set the "parent" element of the picker to the newly clicked element
picker.settings.parent = k;
}
picker.show();
}
picker.on_done = function(colour) {
$(k).css('background-color',colour.rgba().toString());
picker.hide()
}
//e.stopPropagation();
}

Click event object tracking woes

So I am working on this but of jQuery that gets the element id through a click event. This then triggers a function that acts like the deprecated .toggle()- it slides an element down on the fist click and slides that element up on the second click. However, there is a bug that causes the element to slide up and down the amount of times that it has been clicked on. For instance, if this is the second time I use the .clickToggle function, the element (table) slides up and down twice before settling, and so on. I suspect it has something to do with the event object, e, tracking the number of clicks-- i.e. I probably shouldn't set id = e.target.id-- but I'm not sure how to fix while still getting the relevant element id that I need.
Here is the relevant clickToggle plug in (courtesy of an answer here on stackoverflow).
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
Here is the buggy code that fits the above description.
$(document).click(function(e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/);
//clickToggle the individual table
$('#showTable' + strId).clickToggle(function () {
$('#table' + strId).slideDown();
$('#table' + strId).load('files.php');
},
function () {
$('#table' + strId).slideUp();
});
});//close mousemove function
Any help would be much appreciated. Thanks.
The problem is that you're registering a new click handler for the element each time you invoke clickToggle:
this.click(function() {...
On each subsequent click, you add another handler, as well as invoking all previous handlers. Bleagh.
Better to be straightforward: (DEMO)
var showTable = function($table) {
$table.slideDown();
$table.load('files.php');
$table.removeClass('hidden');
};
var hideTable = function($table) {
$table.slideUp();
$table.addClass('hidden');
};
$(document).click(function (e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/)[0];
var $table = $('#table' + strId);
if ($table.hasClass('hidden')) {
showTable($table);
} else {
hideTable($table);
}
});

If the value of an input is greater than 0 dynamically populate other inputs on a page

Right now I'm using javascript to get the job done but i'm using onkeyup. This won't work for me because i'm using a button to populate the "var first". When a user pushes the button it populates the var first so there is no actual keyup/keydown.
<script>
window.onload = function () {
var first = document.getElementById('USERDEFINE1'),
//second = document.getElementById('ADDRESS2');
third = document.getElementById('PHONENIGHT');
fourth = document.getElementById('INTERNET');
fifth = document.getElementById('last_purchase');
sixth = document.getElementById('last_purchase_date');
first.onkeyup = function () { // or first.onchange
//second.value = '4444';
third.value = '111-111-1111';
fourth.value = 'NONE';
fifth.value = 'N/A';
sixth.value = 'N/A';
};
};
</script>
could i use something like:
if (document.getElementById(first.value) > 0
and if so how do i implement into my current javascript or should i rewrite it all together? Thanks in advance.
You will simply have to run the same population logic after pressing the button and after pressing a key in that input. You can also rely on other events like change, depending on how dynamic you want your interface to be.
Basically,
function populateInputs() {
//if we are in here, it means the value of first is > than 0
//at this point you can populate your other inputs
}
document.getElementById('your-button-id').addEventListener('click', function () {
first.value = 10; //init the value greater than 0
populateInputs(); //we know value is greater so populate
});
first.addEventListener('keyup', function () {
if (first.value > 0) {
populateInputs();
} else {
//first.value is not greater than 0
//reset input values to N/A or blank?
}
});

field value gets undefined jquery

Can I Clear a event que in javascript?
when I have done one click event and then does another click event the input field gets the value undefined even when it has a value like "newfile.jpg"
I retrieves the values by doing somevariable = $('#cke_104_textInput').val();
but somevariable gets the value undefined.
here is the javascript code:
$(function () {
// Handler for .ready() called.
function changeLink() {
link = $('#cke_104_textInput').val();
if (link == "") {}
else {
link = link.replace("_", "/");
parts = link.split('.');
explodeExtension = parts[parts.length - 1];
link = link.replace("/download/", "/download/" + explodeExtension + "/");
link = link.replace("." + explodeExtension, "");
$('#cke_104_textInput').val('');
$('#cke_104_textInput').val(link);
clearInterval(changelink);
}
}
function changePic() {
link = $('#cke_103_textInput').val();
if (link == "") {}
else {
link = link.replace("_", "/");
parts = link.split('.');
explodeExtension = parts[parts.length - 1];
link = link.replace("/download/", "/show/" + explodeExtension + "/");
link = link.replace("." + explodeExtension, "");
$('#cke_103_textInput').val('');
$('#cke_103_textInput').val(link);
clearInterval(changepic);
}
}
$('#cke_60').live('click', function (event) {
changelink = setInterval(function () {
changeLink()
}, 1000);
});
$('#cke_64').live('click', function (event) {
changepic = setInterval(function () {
changePic()
}, 1000);
});
});
In the code i try to rewrite the content of two input fields.
this has to be done because the files are not in the sites root they are outside of it, and to be able to show or download them on the site the urls need to be in a specific format.
To answer your first line question, yes you can. Take a look at unbind()
You are creating link as a global variable, which means it is clashing with itself.
Change link = $('#cke_104_textInput').val(); to var link = $('#cke_104_textInput').val();.
Also as a side note, you have this code twice:
$('#cke_104_textInput').val('');
$('#cke_104_textInput').val(link);
which is redundant and inefficient. You should remove the first line in both cases, because selecting an element (even via ID) is not a free operation.

Google Apps Script Find function caller id

I have a Google Apps Script that dynamically generates buttons and assigns for each a ClickHandler which in turn calls a function.
My problem is that because every button calls the same function I can't find a way to indentify which of them actually made the call. Here is a code sample:
var handler = app.createServerHandler("buttonAction");
for (i=1,...) {
app.createButton(...).setId(i).addClickHandler(handler);
}
function buttonAction() {
//How do I know what button made the call?
}
Another option is to use the e.parameter.source value to determine the ID of the element that triggered the serverHandler to be called.
Here's an example:
function doGet(e) {
var app = UiApp.createApplication();
var handler = app.createServerHandler("buttonAction");
for (var i = 0; i < 4; i++) {
app.add(app.createButton('button'+i).setId(i).addClickHandler(handler));
}
return app;
}
function buttonAction(e) {
var app = UiApp.getActiveApplication();
Logger.log(e.parameter.source);
}
e.parameter.source will contain the ID of the element, which you could then use to call app.getElementById(e.parameter.source) ...
You could create multiple handlers, each for one button:
for (i=1,...) {
var handler = app.createServerHandler("buttonAction" + i);
app.createButton(...).setId(i).addClickHandler(handler);
}
function buttonAction1() {
// code to handle button 1
}
function buttonAction2() {
// code to handle button 2
}
function buttonAction...
I wouldn't recommend of having these sort of "anonymous" action handlers though, as you might be having troubles later in remembering which actionX does what.
(e.g. have a different approach, w/o a loop, or prepare a dictionary-like/array object of meaningful handler names before that loop.)
OTOH, you could use event object argument provided to your callback function:
function buttonAction(event) {
// use event object here to identify where this event came from
}
The thing is the above event object properties depends on where your callback is being called from. For instance, if it were a submit button where you had a Form, then you could access parameters submitted by that from like so: event.parameter.myParamName. See code sample here.
So, if you have a variable number of buttons, you could use a hidden element + the button:
for (i=1,...) {
var hiddenAction = app.createHidden("action", "action"+i);
var handler = app.createServerHandler("buttonAction");
handler.addCallbackElement(hiddenAction);
var btn = app.createButton("Button text", handler);
// you'll need to add both btn and hidden field
// to the UI
app.add(hiddenAction);
app.add(btn);
}
Then, your buttonAction might look like this:
function buttonAction(e) {
var action = e.parameter.action;
// do something based on action value here
// which will be one of "action1", "action2", ...
}
The above is a copy & paste from Hidden class sample.
The above might not work out of the box, but you get the idea: create a hidden element that holds the info you need in your callback, and attach that hidden to your server handler. You could even create multiple hidden elements or a Form panel.
I have the same issue. It works using Tag.
EG
SETUP
var button = addButton(app
,panel
,"buttonActiveTrelloProjects_" + i.toString()
,appVars.buttonWidth() + "px"
,appVars.level2ButtonHeight().toString() + "px"
,false
,false
,"Trello"
,"buttonActiveTrelloProjectsHandler"
,(appVars.buttonLhsGap() * buttonCntr) + (appVars.buttonWidth() * (buttonCntr - 1 ) + 9)
,(appVars.level2ButtonTopGap() * 34)
,3
,"button");
button.setTag(projectName );
USE
function buttonActiveProjectsChartHandler_1(button){
...
buttonTag = getButtonTag(button);
chartType = buttonTag.split(";")[1];
activeProject = buttonTag.split(";")[0];
...
}
function getButtonTag(button){
var jsonButton = JSON.stringify(button);
var source = button.parameter.source;
var tagPtr = source + "_tag";
return button.parameter[tagPtr];
}

Categories

Resources