jQuery on variable change, update textbox - javascript

In jQuery, is is possible to check if var x = [] changes, and then add the contents of the array to a textbox.
So if x contains ["1","2","3"]. My textbox textbox1 value will be "1","2","3"

You could do something like this to avoid using a watcher:
var Data = (function () {
var _x = [],
$textbox = $("#myTextbox");
return {
getX: function () {
return x;
},
setX: function (x) {
_x = x;
// Setting 'x' triggers an update
$textbox.val(x.join(","));
}
}
}();
And then set the value of x using Data.setX(x) and get it using Data.getX().

var myString = myArray.join(',');
$('#textbox1').val(myString);

Don't know about watching a variable for a change, unless you create an object that has an "onChange" event, but to show the values in the textbox use this...
$("#textboxID").val(x.join(","));
The easiest thing would be to have an update function with the above code and just call that everywhere you change the value of x.

if ($.inArray(x, [1, 2, 3]) != -1) {
$('#textbox1').val(x);
}

Related

How to fix this 'undefined' when i try to display the sum in the element "pro1'

Im trying to get the value from the element 'amt1' which increases everytime i onclick a button and display it on the element 'pro1'. however, i am receiving the value 'undefined' im really new to javascript. hope someone could help me. thank you in advance!
var add1 = function(sum) {
return function () {
document.getElementById("amt1").innerHTML = ++sum;
var price1 = document.getElementById("amt1").value;
return price1;
};
}(0);
var total1 = price1*parseFloat(119.90);
function displayPrice(){
document.getElementById('pro1').innerHTML = total1;
}
price1 is a local variable in the lexical scope of the function returned by sum function. It's value is not available in the outer scope when you try to multiply it by 119.90.
You can get the price from the element amt1 dynamically inside displayPrice function instead.
Also if amt1element is not an input then you should use .textContent property of the element instead of .value:
var add1 = function(sum) {
return function () {
document.getElementById("amt1").innerHTML = ++sum;
};
}(0);
document.querySelector('button').addEventListener('click', add1)
function displayPrice(){
var price = parseFloat(document.getElementById("amt1").textContent);
var total = price * 119.90;
document.getElementById('pro1').innerHTML = total;
}
document.querySelectorAll('button')[1].addEventListener('click', displayPrice)
<p id="amt1">0</p>
<button>Add</button>
<br><br>
<button>Total</button>
<p id="pro1"><p>

Why is my function outputting 0 (zero)?

This code is supposed to calculate two user inputs by multiplying them. However, the output is consistently 0 instead of would normally be expected ie 5*5=0. I am not sure why this is happening. Am I not passing the variables into the function correctly? I feel like I might not be properly understanding value vs. reference (I am currently learning javascript)
var x = document.getElementById("a").value;
var y = document.getElementById("b").value;
var button = document.getElementById("button");
button.addEventListener('click', function() {
calculator(x,y);
}, false);
function calculator(a,b) {
var output = a * b;
document.getElementById("answer").innerHTML = output;
console.log(output);
}
Omit the value capture, just grab the elements:
var x = document.getElementById("a");
var y = document.getElementById("b");
Then use the values as the function parameters.
button.addEventListener('click', function() {
calculator(x.value, y.value);
}, false);
You were grabbing the values when they were empty and passing those to the function.
DEMO
It could be that the script is treating the values as strings, try using parseInt(a) * parseInt(b)

JavaScript variable variables

Say I have object:
function obj()
{
this.prop1;
this.prop2;
this.prop3;
}
and an array of obj's
objects = [new obj(),new obj(),new obj()];
I want to easily iterate through each using jquery where the class name is equivalent to the property of the object.
var itemsIWantToBind = ["prop1","prop2","prop3"];
for(j=0;j<itemsIWantToBind.length;j++)
{
$("."+itemsIWantToBind[j]).unbind().blur(function(){
var id = $(this).siblings(".objID").html();
if(id >= 0)
{
objects[id].itemsIWantToBind[j] = $(this).text());
}
});
}
My issue is I want to be able use a variable variable to iterate through the items for this
objects[id].itemsIWantToBind[j] = $(this).text());
^^^^^^^^^^^^^^^^^
the indicated part does not correctly bind the value of the array item as it is trying to bind the property name of it instead.
In php it would be the same as:
foreach($itemsIwantToBind as $item)
{
$objects[$id]->$item = "Something";
}
Is there a simple way to do this in JavaScript?
Use brackets notation:
var o = new obj();
o.prop1 = "I'm the value";
var s = "prop1";
console.log(o[s]); // "I'm the value"
I think this is how this relates to your code:
["prop1","prop2","prop3"].forEach(function(prop) { // **A**
$("."+prop).unbind().blur(function(){
var id = $(this).siblings(".objID").html();
if(id >= 0)
{
objects[id][prop] = $(this).text()); // **B**
}
});
});
(B) is the place where we actually use the name, but note the (A) change to so that we get a value that won't change. You can't just use
// Wrong unless we also change the loop
objects[id][itemsIWantToBind[j]] = $(this).text());
because j will be be beyond the end of the array when the event occurs.
forEach is an ES5 feature that can readily be shimmed for old browsers. Or you can use jQuery's $.each instead:
$.each(["prop1","prop2","prop3"], function(i, prop) { // **A**
$("."+prop).unbind().blur(function(){
var id = $(this).siblings(".objID").html();
if(id >= 0)
{
objects[id][prop] = $(this).text()); // **B**
}
});
});

Is this For loop in javascript the way you translate into jquery $.each()?

I am just interested to know if this is how you translate it from javascript to jquery. If not, could you please modify it so I can understand?
The javascript code is:
function blaAll() {
hideSomething();
var formEl = document.getElementById("idForm");
var inputs = formEl.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
dosomething(inputs[i]);
}
}
The jquery code:
function blaAll() {
hideSomething();
var formEl = $("#idForm");
var inputs = formEl.$("input");
$.each(inputs,function(i, 0)) {
dosomething(inputs[i])
}
}
Thank you for your answer
Not really you have to define two arguments you pass to anonymous function.
First is index eg your i, second is object itself.
Since you have object already you do not need to use it like inputs[i] although you could.
function validateAll() {
hideSomething();
var formEl = $("#idForm");
var inputs = formEl.$("input");
$.each(inputs,function(i, item) {
dosomething(item);
});
}
For the $.each function, the callback is provided a key and value, so it's actually wrong. What it should be is:
$.each(inputs,function(key, val)) {
dosomething(val)
}

Javascript for...in loop for objetcs not running on last property

this is my first post in stackoverflow.. I am trying to iterate over an object(my implementation is an associative array) which in turn has some properties. Now I wish to construct another array out of it in order to use it as a localsource in jquery autocomplete widget for seach operations. Now the problem is that i am using for in loop to that according to the documenations available... However the output is always one less than the original object. The itearation involving the last element is not performed at all. Below is the sample object that I am using as input.
SubTeachPair = object{"5CS1":{SubAbbrev:"CA-L",SubCode:"5CS1",SubName:"Computer Architecture",TeacherId:"1",TeacherName:"Ayush Pandey",label:"Computer Architecture",value:"5CS1"},"5CS2":{SubAbbrev:"CA-P",SubCode:"5CS2",SubName:"Computer Engg",TeacherId:"10",TeacherName:"MAyush Pandey",label:"Computer Engg",value:"5CS2"}}
It has this kind of elements and is dynamically generated so the property names are variable. The loop construct that I have written is
var SubSource = [];
console.log(SubTeachPair);
var count = 0;
for(sub in SubTeachPair){
console.log(count);
SubSource[count] = {};
SubSource[count]['label']=SubTeachPair[sub]['label'];
SubSource[count]['value']=SubTeachPair[sub]['value'];
count++;
}
However, the result for the given input is only:
object{{ label: "Computer Architecture", value: "5CS1"}}
Am I missing something here?
edit-- The function that produces the input object is as follows(It is triggered onclick by the next button).
$('#' + $(this).attr("id")).autocomplete({
source : 'search',
minLength : 1,
change : function(event, ui) {
if( typeof ui.item != 'undefined') {
SubTeachPair[$(this).attr("id")] = {};
// console.log(ui.item);
SubTeachPair[$(this).attr("id")]['value'] = $(this).attr("id");
SubTeachPair[$(this).attr("id")]['label'] = $('label[for="' + this.id + '"]').html();
SubTeachPair[$(this).attr("id")]['SubCode'] = $(this).attr("id");
SubTeachPair[$(this).attr("id")]['SubName'] =$('label[for="' + this.id + '"]').html();
SubTeachPair[$(this).attr("id")]['SubAbbrev'] =$('label[for="' + this.id + '"]').attr('id');
SubTeachPair[$(this).attr("id")]['TeacherId'] = ui.item.id;
SubTeachPair[$(this).attr("id")]['TeacherName'] = ui.item.value;
// console.log(SubTeachPair);
//window.SubTeachPair = SubTeachPair;
}
}
});
I think I have found the cause of the error -- the object that is the input is actually the out put of another form that uses jquery autocomplete . Now when I enter something in the input and then click on the suggestion, the suggestion is filled in the text input, however if i do not click outside the input text and directly click the button which triggers my script, I get that error. Otherwise its fine. Is there any way to avoid that?
In your code, the array SubSource and count are not defined, You have to declare:
var SubSource = [];
var count = 0`
before for(sub in SubTeachPair) {...}
See http://jsfiddle.net/abu5C/
Try this:
SubSource[count] = {};
for(sub in SubTeachPair) {
console.log(count);
SubSource[count]['label']=SubTeachPair[sub]['label'];
SubSource[count]['value']=SubTeachPair[sub]['value'];
count++;
}

Categories