JS Variable Not Being Passed Correctly - javascript

I've been working on this code for a while. I have a HTML, JS and a Code.js page.
On changing of the value in a Dropdown list on my HTML form, the item in the Dropdown is passed to the Code.js to have the result returned, however, I keep having NULL as my result. -arr is the result.
Another issue, is that I can see in the script logs that getRowData() is being executed twice, not sure why, but this may be overwriting our array.
HTML
JS
//$('#searchDropdown').one('change', function(){
//$("#searchDropdown").change(function(){
//$('#searchDropdown').on('keyup propertychange change', function(){
//$('#searchDropdown').on('input', function(){
//$('#searchDropdown').one('submit', function(){
$('#searchDropdown').one('change', function(){
var selatr = $('#input1').val();
google.script.run.withSuccessHandler(poperr).getRowData(selatr);
});
function poperr(arr){
alert(arr +" ! ");
}
Code.GS
function getRowData(selatr){
//Vlookup a GoogleSheet and return the resulting row
sheet_data.getRange(2,16).setValue(selatr); //set for vlookup
var x = sheet_data.getRange(3,16).getValues();
var arr= [];
arr.push({
id : selatr
name : sheet_data.getRange(x,2).getValues()
})
return arr;
}

It might be because you have multiple event handlers in your code and your getRowData function is being called twice.
Try e.stopImmediatePropagation(); This stops the rest of the event handlers from being executed.
$('#searchDropdown').one('change', function(e){
e.stopImmediatePropagation();
var selatr = $('#input1').val();
google.script.run.withSuccessHandler(poperr).getRowData(selatr);
});

Related

I get 'Bad assignment' when trying to use $(this) inside function after .load() method

I couldn't find any solutions for my problem yet. Maybe I used wrong keywords.
I'm trying to update the value of an input field onchange after a .load() action has been performed.
Here is my script:
$(document).on("change",".myInput",function() {
var value = $(this).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(this).val('OK');
});
});
So, after someAction.php has been loaded into #actionDiv successfully, I'd like to change the value of that input field, that has been changed.
I have several input fileds, which take this kind of action...
It seems "$(this)" is unknown in the function after load() has been completed.
Can anyone please help?
Thanks
You need to store a reference to the element, or use an arrow method which doesn't change the value of this
$(document).on("change",".myInput",function() {
var that = this;
var value = $(that).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(that).val('OK');
});
});
OR
$(document).on("change",".myInput",function(e) {
var value = $(e.target).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(e.target).val('OK');
});
});
OR
$(document).on("change",".myInput",function() {
var value = $(this).val();
$('#actionDiv').load("someAction.php?value="+value, () =>{
$(this).val('OK');
});
});

Can't output variable in change function jquery

i will get the value on select with change function in jquery. I used a global variable to get the value, but the console.log don't works outside my function:
jQuery(function($) {
var formule;
$('#group_14').on('change', function() {
formule = this.value;
});
console.log(formule);
});
The console log just works with this code:
jQuery(function($){
var formule;
$('#group_14').on('change', function() {
formule = this.value;
console.log(formule);
});
});
I want to recover my formule variable to use it after in other functions, how can return my variable in all my script?
Think about whats going on with the event as the page loads:
In the below snippet, console.log is outside of the change event so will output to console on page load i.e. before the event has fired, formule is not initialised as anything at that point
jQuery(function($){
var formule;
$('#group_14').on('change', function() {
formule = this.value;
});
//outside of the change event, formule is null or undefined
//until the event is fired and formule is intialised
console.log(formule);
});
The following snippet will output the value for formule after formule has been initialised by the change event
jQuery(function($){
var formule;
$('#group_14').on('change', function() {
formule = this.value;
//formule has been initialised within the scope of the change event
//so is no longer null or undefined and can be used elsewhere
console.log(formule);
});
});
Ok, so how i can solve the problem? i will create a function after with this variable inside to addition it with other variables

Jquery .change() event fires only once

So I'm fairly novice with jquery and js, so I apologise if this is a stupid error but after researching I can't figure it out.
So I have a list of data loaded initially in a template, one part of which is a dropdown box that lets you filter the data. My issue is that the filtering only works once? As in, the .change function inside $(document).ready() only fires the once.
There are two ways to reload the data, either click the logo and reload it all, or use the search bar. Doing either of these at any time also means the .change function never fires again. Not until you refresh the page.
var list_template, article_template, modal_template;
var current_article = list.heroes[0];
function showTemplate(template, data)
{
var html = template(data);
$("#content").html(html);
}
$(document).ready(function()
{
var source = $("#list-template").html();
list_template = Handlebars.compile(source);
source = $("#article-template").html();
article_template = Handlebars.compile(source);
source = $("#modal-template").html();
modal_template = Handlebars.compile(source);
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
$("#classFilter").change(function()
{
console.log("WOW!");
var classToFilter = this.value;
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.heroClass.search(classToFilter) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
$("#searchbox").keypress(function (e)
{
if(e.which == 13)
{
var rawSearchText = $('#searchbox').val();
var search_text = rawSearchText.toLowerCase();
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.name.search(search_text) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
}
});
$("#logo").click(function()
{
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
//$("#logo").click();
});
function displayModal(event)
{
var imageNumber = $(this).data("id");
console.log(imageNumber);
var html = modal_template(current_article.article[0].vicPose[imageNumber]);
$('#modal-container').html(html);
$("#imageModal").modal('show');
}
I should note two things: first, that the search bar works perfectly, and the anonymous function inside both of them is nearly identical, and like I said, the filtering works perfectly if you try it after the initial load. The second is that the same problem occurs replacing .change(anonymous function) with .on("change",anonymous function)
Any help or advice would be greatly appreciated. Thanks.
I agree with Fernando Urban's answer, but it doesn't actually explain what's going on.
You've created a handler attached to an HTML element (id="classFilter") which causes part of the HTML to be rewritten. I suspect that the handler overwrites the HTML which contains the element with the handler on it. So after this the user is clicking on a new HTML element, which looks like the old one but doesn't have a handler.
There are two ways round this. You could add code inside the handler which adds the handler to the new element which has just been created. In this case, that would mean making the handler a named function which refers to itself. Or (the easier way) you could do what Fernando did. If you do this, the event handler is attached to the body, but it only responds to clicks on the #classFilter element inside the body. In other words, when the user clicks anywhere on the body, jQuery checks whether the click happened on a body #classFilter element. This way, it doesn't matter whether the #classFilter existed when the handler was set. See "Direct and delegated events" in jQuery docs for .on method.
Try to use some reference like 'body' in the event listeners inside your DOM like:
$('body').on('click','.articleButton', function() {
//Do your stuff...
})
$('body').on('click','#classFilter', function() {
//Do your stuff...
})
$('body').on('keypress','#searchbox', function() {
//Do your stuff...
})
$('body').on('click','#logo', function() {
//Do your stuff...
})
This will work that you can fire it more than once.

Separating JS to multiple files

There are multiple pages on my web-project working with exactly same JS functions. I was copying and pasting same functions to all pages' js files. But recently seperated common functions to another js file named common_fns.js, for every page created just selector cached variables and placed at the top of every page in order some_page.js, common_fns.js . Something like that
some_page.js
$(function() {
var closer=$("#nlfcClose"),
NewFormContainer=$("#NewLessonFormContainer"),
opener=$("#nlfcOpen"),
NewForm=$("#NewLessonForm"),
OpsForm=$("#LessonOps"),
SelectBox=$( "#courses" ),
SelectBoxOptions=$("#courses option"),
jquiBtn=$(".jquiBtn"),
AddOp="AddLesson",
DelOp="DelLesson";
});
common_fns.js
$(function() {
SelectBoxOptions.text(function(i, text) {
return $.trim(text);
});
SelectBox.combobox();
jquiBtn.button();
closer.button({
icons: {
primary: "ui-icon-closethick"
},
text: false
}).click(function(){
NewFormContainer.slideUp("slow");
});
opener.click(function(){
NewFormContainer.slideDown("slow");
});
NewForm.submit(function(){
var querystring = $(this).serialize();
ajaxSend(querystring, AddOp);
return false;
});
OpsForm.submit(function(){
var querystring = $(this).serialize();
ajaxSend(querystring, DelOp);
return false;
});
});
It was working when I copied and pasted common functions to every pages' file. But now it doesn't: Firebug shows error message undefined SelectBoxOptions even for first function. What am I missing? Only way to copy-paste same functions into every pages' js file?
You are declaring local variables inside the event handler, that's why you can't use them in the next event handler.
Declare the variables outside the function:
var closer, NewFormContainer, opener, NewForm, OpsForm, SelectBox, SelectBoxOptions, jquiBtn, AddOp, DelOp;
$(function() {
closer = $("#nlfcClose");
NewFormContainer = $("#NewLessonFormContainer");
opener = $("#nlfcOpen");
NewForm = $("#NewLessonForm");
OpsForm = $("#LessonOps");
SelectBox = $( "#courses" );
SelectBoxOptions = $("#courses option");
jquiBtn = $(".jquiBtn");
AddOp = "AddLesson";
DelOp = "DelLesson";
});

How can I pass args to event handler?

How can I pass args to the event handler function? This runs the function on page load which is not the desired effect. I need this routine validateText to run against several different textbox, dropdown combinations. Can I reuse validateText instead of creating one per text/dropdown combination??
//add blur event handler to the textbox with jQuery when the page is finished loading
$(document).ready(function() {
$("#myTextbox").blur(validateText($("#myTextbox"), $("#Select1")));
})
function validateText(textbox, dropdown) {
var message = $("#message");
var isValid = false;
//get the value the user type in
var textboxValue = $(textbox).val();
//get the options from the lookup
var options = $("option", dropdown);
//loop through the options and compare it to "value"
options.each(function() {
var optValue = $(this).val();
if (optValue === textboxValue) {
isValid = true;
}
});
if (!isValid)
message.text(textboxValue + " is not a valid value from the list.");
else
message.text(textboxValue + " is perfectly valid.");
}
Use binding to pass extra parameters to an event listener:
http://docs.jquery.com/Events/bind
$(document).ready(function() {
$("#myTextbox").bind("blur", [ $("#myTextBox"), $("#Select1")], validateText);
})
Then access the data from event.data:
function validateText(event) {
textBox = event.data[0];
dropdown = event.data[1];
}
The reason it calls at load is because handing over a function name with arguments actively calls it. You can effectively mimic what you're looking for by wrapping the call to validateText in an anonymous function like so.
$(document).ready(function() {
$("#myTextbox").blur(function(){
// Since in your original example you used $("#myTextbox") as an arg, this mimics it
validateText($(this), $("#Select1"));
});
});
The anonymous function, since it's using the 'this' keyword, should scale a little better with your initial selector if you change it from #myTextbox to textarea or whatever. =)

Categories

Resources