Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Is there a way to watch variable changes in Jquery/Javascript like it is the case in AngularJS ?
Angular uses a digest cycle to detect changes after you update a variable. For instance, when you click on an element, it will change variables in scopes, and will immediately trigger a look through to see what has changed. You can accomplish something similar using a simple interval function:
var _watch = null;
var test = null;
setInterval(function() {
if ( _watch !== test ) {
_watch = test;
console.log('Variable changed.', test);
}
}, 100);
To test this out, simply type test = "test" in the console, and you should see "Variable changed."
You can use obj.watch but it's only supported in Gecko (Basically firefox) for now.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch
Edit: For Chrome , Object.observe can be used.
Use a getter/setter method:
var log = ['test'];
var obj = {
get latest () {
if (log.length == 0) return undefined;
console.log('getting latest!'); // or trigger an event
return log[log.length - 1]
}
}
console.log (obj.latest); // Will return "test".
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/get
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have keyword (for example -2330) that needs to be compared with the 'values' in this string below.
"[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]";
Expected output needs to be true or false depending if the string has the keyword or not.
How do I check it?
I will do something like this to loop
var a = "[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]";
var new_a = JSON.parse(a);
var value_compare = '1574';
new_a[0]['value'].forEach(element => {
if (element[0].value == value_compare) {
//DO SOMETHING
alert('found: '+ JSON.stringify(element));
}
});
You first need to parse the JSON into an suitable JS structure. Because of the nested nature of the data you need to 1) map over the first object in your array, 2) return the value of the value property of the first object of each and finally 3) check to see if the keyword is included in the the returned array, and return true or false.
const json = '[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]';
const data = JSON.parse(json);
function doesItExist(data, keyword) {
const values = data[0].value.map(arr => arr[0].value);
return values.includes(keyword);
}
console.log(doesItExist(data, '2331'));
console.log(doesItExist(data, 'Bob'));
console.log(doesItExist(data, '1574'));
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
In my Js script, I am using switch case but I dnt want to use it but I am not getting better alternative of this.
Here I am using Js CONSTANT as well for defining First URL & Second URL
var FIRST_URL = "/first_url.html"
var SECOND_URL = "/second_url.html"
& also passing FIRST_URL and SECOND_URL as parameter from function. That's why I used FIRST_URL with double quotes and without quotes.
Snippet :-
if(url == "DIV_ID"){
switch (url_type) {
case FIRST_URL:
case "FIRST_URL":
result = "/first_url.html";
break;
case SECOND_URL:
case "SECOND_URL":
result = "/second_url.html";
break;
default:
result = "other_url.html";
break;
}
}
Suggest something to resolve this.
You can use something like this, but add proper error checking.
Roughtly:
var arr = {};
arr['FIRST'] = 'your first url';
arr['SECOND'] = 'your second url';
result = arr[urlType];
here's an example using object literal:
var arr = {
FIRST : 'your first url',
SECOND: 'your second url'
};
console.log(arr.FIRST)
console.log(arr['SECOND'])
//for adding properties
arr.thr='third prop';
basically the resulting obj is the same to bigmike's answer, but it maybe easier to understand .
This is what is called a key-value pair and the structure is an object (JS definitions).
BTW there is nothing wrong with switch .
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this function which produces the correct value when run, but I am having a hell of a time displaying the results.
Here is the JS which is calculated onChange in a form I am trying to display the resulting value elsewhere on the form. The alert displays the correct value but my id remains blank.
Thanks in advance for taking a look
function calculate_mtow1() {
togw_n = 0;
togw = $('#togw').val();
if (togw != '' && togw != 0 && togw != 'Nan') {
var togw = togw.replace(",", "");
togw_n = togw;
}
burn_n = 0;
burn = $('#burn').val();
if (burn != '' && burn !=0 && burn != 'Nan') {
var burn = burn.replace(",", "");
burn_n = burn;
}
var mtow1 = parseInt(togw_n) + parseInt(burn_n);
$('#mtow1').val(mtow1);
document.getElementById('mtow1');
alert(mtow1);
}
<td>TOW + Fuel Burn =<span id="mtow1"></span></td>
Your code is getting the element with getElementById but then not doing anything with it. You need to assign the result of getElementById to something, or call methods on it on the same line. If your goal is to put the value of mtow1 into your <span>, try doing this:
// Solution 1
var spanElement = document.getElementById("mtow1");
spanElement.innerHtml = mtow1;
Alternatively, perhaps you were trying to display the value of mtow1 by using this jQuery:
$('#mtow1').val(mtow1);
That doesn't do what you think it does. It changes the "value" attribute of the span to the value of mtow1, but that change isn't visible to the user. It's the same as writing this as your HTML:
<td>TOW + Fuel Burn =<span id="mtow1" value="valueofmtow1"></span></td>
If you want to use jQuery instead of the getElementById method I posted above, you could do this:
// Solution 2
$('#mtow1').html(mtow1);
You don't need to do both. Either solution will work on its own.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a loop with the jquery .each function that is filtering through IDs with the suffix _prop_val I then get the prefix and use it for other operations as you can see in the code below. At the moment I am having to use an if statement to set the rlPrice. Is there a way to get it in the loop i.e. prefixPrice and then have it set as rlPrice afterwards
$('[id$="_prop_val"]').each(function(){
var prefix = this.id.slice(0,2);
if( $('#'+prefix+'_prop_val').val() != ""){
$('#'+prefix+'_prop_val').prop('disabled', false).trigger('chosen:updated');
$('#'+prefix+'_ct_row').show();
$('#'+prefix+'_deactivate_btn').show();
if(prefix == "rl"){
rlPrice = $('#rl option:selected').data("unit-price");
}
checkExtra(prefix);
}else{
$('#'+prefix+'_container').addClass('inactive');
$('#'+prefix+'_activate_btn').show();
}
});
You might find an object more useful here. Define it before the loop:
var price = {};
Then in your loop just assign the price to a property with the prefix as a key - no need to check for a condition:
price[prefix] = $('#rl option:selected').data("unit-price");
Then you can just access the price using the prefix:
var rlPrice = price['rl'];
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I will do a function with parameters that get a regex and check the field of a form with it.
I have this code:
//The first function handler (no one runs):
field.onblur = function(){
checkField(0, /^([a-z ñáéíóúü]{2,60})$/i, "name", "nameError", "Error in name");
}
//The function:
function checkField(numForm, regex, idField, idError, error){
var form = document.getElementsByTagName("form")[numForm];
var field = form.getElementById(idField);
var spanError = form.getElementById(idError);
//Since here runs, so I think the problem is with the regex
if(!regex.test(idField.value))
spanError.innerHTML = error;
else
spanError.innerHTML = "";
}
What is the proper way to make a function and give it a regex like a parameter?
The regexp is passed fine, these two lines are erranous instead:
var field = form.getElementById(idField);
var spanError = form.getElementById(idError);
getElementById() is a method of document only. You can fix the issue by using id string like below:
var field = form[idField];
var spanError = form[idError];
... or using getElementById(): var field = document.getElementById(idField);
Also this line (unless a typo in the post)
if(!regex.test(idField.value))
should be:
if(!regex.test(field.value))