JavaScript function writing - javascript

This is what im doing:
1.
function getVal() {
var asd = document.getElementById("nomyape").value
}
getVal()
asd (to check if the var has something)
asd is undefined
pd: "nomyape" has a value , if i do document.getElementById("nomyape").value I get the value, thats why i know im pretty close
What i would like to make its a function that gets 6 diferents values from differents id, so when i call it i can gather all the form data
Thank you in advance

var values=[];
var ids=['nomyape_!','nomyape_2',...];
function getVals(){
for(i in ids){
values.push(
document.getElementById(ids[i]).value
);
}
}
use a for loop to store all values in the values array.

you can do like this. You need to remove var inside function which is making it a local variable.
var asd;
function getVal (){
asd=document.getElementById("nomyape").value
}

You should return the value from your function and assign it to a variable.
function getVal (elementId) {
return document.getElementById(elementId).value;
}
var a = getVal("id_of_element1");
var b = getVal("id_of_element2");
In your version of the code you create a local variable in the function that is only visible in the function.
Assuming all of your element's have id attributes, you could pass the element id into the function to get the value of each input.

Related

How to make a js var in a function global to use it outside?

I want to make the "var id" in the function global. That i can use the value of it in the alert outside the function. Thats my code:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
}
alert(id);
</script>
You didn't specified what is your final goal or why are you trying to move id to a global scope, but you can do it by simple moving the var id (declaration) outside the function, then it will be global and accessible by all functions.
Obviously, the alert will show "undefined" since id only gets some value when the myFunctionGetCode() is called.
The code below shows this.
var id;
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
id = con+code;
console.log(id)
}
alert(id);
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
BUT if you want to throw the alert with the id value only when it gets some value then you should move the alert() inside the function. (You can still declare the id variable outside the function to let it global, or inside the function, as you currently have)
Open snippet to see:
//var id; -> You can still declare it here (as global)
function myFunctionGetCode() {
var code = getInputVal('code');
var con = "/";
var id = con+code; //or you can declare it here, but not global
alert(id);
}
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
From your sample code I guess that you do not want to make your value global, but that you want to return a value - after all you are doing an operation inside your function that calculates a value from certain inputs.
So you would use the return keyword, and call the function to get the value:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
return id;
}
alert(myFunctionGetCode());
</script>
As a rule you do not want to make function variables global, since this means the value can be changed anywhere in your script or website, and that might lead to side effects and unexpected values in your function. If you need to pass something in use function parameters (or read from a text input like in your case), if you want to give back a result use return.
Can you move the alert inside the function or return the "id" value from the function instead?
You can make the variable global by doing something like:
window.your_namespace.id = value;
and then access the variable in the same way:
value = window.your_namespace.id
but its best not to pass data around using the global namespace.
You have to make var id to property of window object then you can access the id out side the function.
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
window.id = 10;// Change to this
}
myFunctionGetCode();
alert(id);

Storing Jquery reference

Is it possible to store the reference to an element in an array or object without having a unique ID on the element?
I am having trouble with storing a subtable in another table so I can reference it later. I get the table by class with this code:
$(this).parent('tr').parent().find('.tableSomeTable');
Is the only solution to have unique id's on each element and use the .selector method?
More of my code. Abit simplified.
var rows = [];
var historyLoad;
$(document).on("click", '.details-control', function (e) {
var t = $(this);
var tr = t.closest('tr');
var row = t.parent().parent().parent().DataTable().row(tr);
var id = t.closest('tr').attr('id');
var object = {
id: id,
btnHistory: t.parent('tr').next().find('#btnHistory'),
tblHistory: t.parent('tr').parent().find('.tableHistory'),
historyLoad: historyLoad
};
if ($.inArray(id, rows) > -1) {
loadData = false;
}
else {
loadData = true;
loadHistory(object);
rows.push(object);
}
};
Here is where I am having trouble retrieving the correct elements. And I also want to save the ajaxHistory element to my object (which is working fine).
This code is not working, but if I change it to $(result.btnHistory.btnHistory.selector) I get the object. But this doesn't seem to work very good with multiple rows.
function loadHistory(result) {
result.ajaxHistory = $.ajax({
...
beforeSend: function () {
$(result.btnHistory).html(<loading txt>);
$(result.tblHistory).find('tbody').html(<loading txt>);
},
....
success: function (data) {
if (data.TotalRecordCount > 0) {
$(result.tblHistory).find('tbody').html('');
$.each(data.Records, function (e, o) {
$(result.tblHistory).find('tbody').append(<data>)
});
}
else {
$(result.tblHistory).find('tbody').html(<txt no records>);
}
$(result.btnHistory).html(<txt loading done>));
},
First off, if you are trying to find the parent table, try
var $myObj = $(this).closest('table.tableSomeTable');
instead of navigating parents.
As far as storing the jQuery reference, define a variable and then store it. The above will store the object in $myObj but that is locally scoped. If you need a global variable then define it globally and just assign it here. If you want to define it as a property within an object then define it that way. It really comes down to a scope question at this point.
EDIT: Just saw your added content.
First off, don't name it 'object'. This may run into key word issues. Use var myObj or similar instead. Next, object.btnHistory is a reference to a jQuery object. So, when you pass it to loadHistory, you do not need to apply the $(...) again. Just use the reference directly: result.btnHistory.html(...). A good habit to get into is prepending you jQuery variables with $ so you remember it is already a jQuery variable.
The .find() method returns a jQuery object. So the answer is, yes, you can store this return object in a variable:
var $yourObject = $(this).parent('tr').parent().find('.tableSomeTable');

Create variable to JavaScript array from another function?

I have a function that create and store an array for all the p elements:
function dummyArray(){
var $dummy= $('p');
var dummy= [];
i = 0;
$dummy.each(function()
{
dummy[i++] =$(this).html();
});
return dummy;
}
Now, in order to reuse the array in another function, I can use dummyArray() and dummyArray()[0] to access the individual data.
function initAll(){
//dummyArray();
//dummyArray()[0];
}
However I want to store it inside a variable like below but it gives me error.
function initAll(){
var allArray = dummyArray();//error
}
Is there a way to store it inside a variable or is there a better way of doing this?
After cleaning up my code I noticed that using var allArray = dummyArray(); does work, the error was generated from something else. cheers~
Edited:
The error I found out was the function name cannot be the same as the new variable name declared even though the () aren't there.
var dummyArray = dummyArray();//error
var allArray = dummyArray();//works

.innerHTML function Javascript

This is my code:
function text(var text)
{
var Value = document.getElementById("display").innerHTML;
var New = Value + text;
document.getElementById("display").innerHTML=New;
}
What it's supposed to do is get a string from when it's called, and then add that string to the end of a div element with the ID "display". I called it like this: text("hello");
The HTML of the webpage is a blank div element, and it stays blank even after the code is run. It worked when I did document.getElementById("display").innerHTML="hello!";, but isn't now. Thanks!
Don't use "var" for a function parameter - just listing it between the function parenthesis is enough. So change that function to:
function text(text)
{
var Value = document.getElementById("display").innerHTML;
var New = Value + text;
document.getElementById("display").innerHTML=New;
}
and it should work.
Take the var out of the function parameter: function text(text)...
BTW: don't name your parameter the same thing as your function - it's confusing.
And you can do it like this:
function text(inputText)
{
document.getElementById("display").innerHTML = document.getElementById("display").innerHTML +" "+ inputText;
}
:)

JQuery - accessing a VAR in a function which I will need in another function?

Ok so in my html/js i have a form that updates based on the users previous selection. On the last stage i have a select menu where the user will choose their city. I have stored the value of the selected item in my Options list with the id #myCity to the following.
('#myCity').change(function(){
var CityValue = $("#myCity").val();
});
Once that value is set, my form then displays the submit button
<input type="submit" id="go" value="Submit" onclick="getweather()" />
This is where i start to have a bit of bother. In my getweather() function i want to be able to take the var CityValue from above and append it to another var so i can load a specific page.
function getweather(){
var CityValue;
var to_load = 'getweather.php?p='+ CityValue +'.html';
$('#weather').empty().append(to_load);
}
but in my testing i do not think that my getweather() function is able to read my desired var. Can anyone suggest a solution?
Well, the first function you specified (the event handler for onchange) doesn't do anything right now. You can just remove it and edit the second function like this:
function getweather(){
var CityValue = $("#myCity").val();
var to_load = 'getweather.php?p='+ CityValue +'.html';
$('#weather').empty().append(to_load);
}
You declared the CityValue only in the function scope that you cannot access from outside. Either declare your variable globally:
var CityValue;
$('#myCity').change(function(){
CityValue = $("#myCity").val();
});
function getweather() {
var to_load = 'getweather.php?p='+ encodeURIComponent(CityValue) +'.html';
$('#weather').empty().append(to_load);
}
Or just call $("#myCity").val() in your getweather function:
function getweather() {
var to_load = 'getweather.php?p='+ encodeURIComponent($("#myCity").val()) +'.html';
$('#weather').empty().append(to_load);
}
Well, the first function you specified (the event handler for onchange) doesn't do anything right now. You can just remove it and edit the second function like this:
You can then add this function call to the change event.
function getweather(){
var CityValue = $("#myCity").val();
var to_load = 'getweather.php?p='+ CityValue +'.html';
$('#weather').empty().append(to_load);
}
$('#myCity').change(getweather);
The more elegant answer to the question is in using jQuery data API. This allows you to store arbitrary data within an object rather than declaring variables, keeping everything in a nice OOP manner. So, to do what you want would mean storing the value like so:
$('#myCity').change(function(){
$("#myCity").data("CityValue", $("#myCity").val());
});
This way you would be able to retrieve it like so:
function getweather(){
var to_load = 'getweather.php?p='+ $("#myCity").data("CityValue") +'.html';
$('#weather').empty().append(to_load);
}

Categories

Resources