Assign a variable variable in Javascript loop [closed] - javascript

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'];

Related

Comparing keyword value field in array - Javascript [closed]

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'));

Watch variable changes in Jquery/Javascript [closed]

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

Facing error while getting value of dynamically created textbox [closed]

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 8 years ago.
Improve this question
i have created a dynamic textbox but unable to fetch its value on runtime. it shows something else.
code
var UL = document.createElement('ul');
var Li = document.createElement('li');
var A4 = document.createElement('input');
A4.type = 'text';
A4.setAttribute('id', 'current_page');
A4.value = list.length;
A4.setAttribute('style', 'width:30px;height:26px;text-align:center;position:relative;left:35px');
Li.appendChild(A4);
UL.appendChild(Li);
script
var va = $('#current_page').val;
alert(va);
Seeing as you're using JavaScript for everything else, save the jQuery for another day:
var va = document.getElementById('current_page').value;
In jQuery you need to use .val(); instead of .val;
var va = $('#current_page').val();
alert(va);
It doesn't look like you're ever appending anything to the document.
You need to use $('#current_page').val(); to get the value
For future reference can check if your selectors are finding anything using:
console.log($('#current_page'));
Use .val() in jQuery and it is a function
var val = $('#current_page').val();
alert(val);
Using Native JavaScript, You can use document.getElementById
alert(document.getElementById('current_page').value)

How return this data in json for each? [closed]

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 5 years ago.
Improve this question
i have json values like this, i try to use for each to get the result one bye one, but it was not returning to me
"[{"id":6,"userid":13,"title":"business3","bussinessTypeid":1,"photurl":"","cntry":[{"id":"9","name":"Bahrain"}]},
{"id":7,"userid":13,"title":"business6 arabic","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},
{"id":10,"userid":13,"title":"E-commerce","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},
{"id":11,"userid":8,"title":"Auto phone parts","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},
{"id":19,"userid":8,"title":"التجارة الإلكترونية","bussinessTypeid":1,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},
{"id":20,"userid":8,"title":"E-commerce -online shopping","bussinessTypeid":8,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},
{"id":21,"userid":13,"title":"My new Business","bussinessTypeid":6,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]}]"
can anyone guide me to achive this
I think it's being treated as a string try to remove the ( " ) on the start and end of it something like:
var json = [{"id":6,"userid":13,"title":"business3","bussinessTypeid":1,"photurl":"","cntry":[{"id":"9","name":"Bahrain"}]},{"id":7,"userid":13,"title":"business6 arabic","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},{"id":10,"userid":13,"title":"E-commerce","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},{"id":11,"userid":8,"title":"Auto phone parts","bussinessTypeid":1,"photurl":"","cntry":[{"id":"1","name":"Afghanistan"}]},{"id":19,"userid":8,"title":"التجارة الإلكترونية","bussinessTypeid":1,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},{"id":20,"userid":8,"title":"E-commerce -online shopping","bussinessTypeid":8,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]},{"id":21,"userid":13,"title":"My new Business","bussinessTypeid":6,"photurl":".jpg","cntry":[{"id":"9","name":"Bahrain"}]}];
Then do the iteration:
for(id in json){
alert(json[id]['id']);
}
and don't include any next line spaces are ok as long as they are separated by a comma (,)
Use parseJson()
Description: Takes a well-formed JSON string and returns the resulting
JavaScript object.
$.each(data, function(key, value){
console.log(value.id, value.title);
$.each(value.cntry, function(key2, value2){
console.log(value2.id, value2.name);
})
});
Try this with jquery
var data = jQuery.parseJSON(yourJsonInString); //or this parser below
var data = JSON.parse(yourJsonInString);

Regex like parameter function in Javascript [closed]

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))

Categories