Somehow when I set the preventDefault() within the function, it wouldn't work. I believe this is somehow a scope problem? if It is, how can I solve it though?
Can someone give me a hand?
Thanks in advance.
var abc = {
save: function () {
var $optionsRegex = this.$optionsRegex;
$('.save-options').on('click', function (e) {
e.stopPropagation();
var regex = '';
$.each($('.input-options'), function (index) {
var val = $(this).children('input').val();
if (val !== "") {
regex += (index + "," + val + ":");
}
});
return $optionsRegex.val(regex.slice(0, -1));
});
},
};
works fine if I didn't put it into an object though
this would work fine
$('.save-options').on('click', function (e) {
e.preventDefault();
var optionsRegex = '';
$.each($('.input-options'), function (index, value) {
var value = $(this).children('input').val();
if (!value == "") {
optionsRegex += (index + "," + value + ":");
}
});
return $('#id_options_regex').val(optionsRegex.slice(0, -1));
});
Related
I'm trying to make a kind of newswire for a school project but I'm having a few problems with jQuery's .each() function. I'm trying to find a way to skip every 2nd array element in a loop.
Basically I have data from a NY Times API and got both title and abstract and push these into an array that I then loop and animate every once and awhile.
My problem is, I can't seem to find a way to get Title + Abstract (Index[0]+[1]) without the loop just moving to index[1] again. Now I knows in Javascript you can simply use a for (i=0; i < array.length; i+2) and thus skip every 2nd array element, but I haven't had any luck incorporating that. Any suggestions? :)
$(document).ready(function() {
var newsWire = [];
function loadNewswire() {
return $.getJSON('http://api.nytimes.com/svc/news/v3/content/all/all.json',
{'api-key': 'XXXXXXXXXXXXXXXXXXX'},
function(data) {
console.log(data)
var newsWireTemp = [];
for (var i = 0; i < data.results.length; i++) {
var breakingNews = data.results[i];
var breakingTitle = breakingNews.title.toUpperCase();
var breakingAbstract = breakingNews.abstract;
newsWireTemp.push(breakingTitle);
newsWireTemp.push(breakingAbstract);
}
newsWire = newsWireTemp;
});
}
loadNewswire().done(function () {
var items = newsWire;
$text = $('#newswiretxt span'),
delay = 10; //seconds
function loop (delay) {
$.each(items, function (i, elm){
$text.delay(delay*1E3).fadeOut();
$text.queue(function(){
$text.html(items[i]+ ": " +items[i+1]);
$text.dequeue();
});
$text.fadeIn();
$text.queue(function(){
if (i == items.length -1) {
loop(delay);
}
$text.dequeue();
});
});
}
console.log(items.length);
loop(delay);
});
});
Basically, just push the desired text concatenated into the array for the load function. Then as you iterate you can simply write the contents as is without messing with the iteration.
$(document).ready(function() {
var newsWire = [];
function loadNewswire() {
return $.getJSON('http://api.nytimes.com/svc/news/v3/content/all/all.json',
{'api-key': 'XXXXXXXXXXXXXXXXXXX'},
function(data) {
console.log(data)
var newsWireTemp = [];
for (var i = 0; i < data.results.length; i++) {
var breakingNews = data.results[i];
var breakingTitle = breakingNews.title.toUpperCase();
var breakingAbstract = breakingNews.abstract;
newsWireTemp.push(breakingTitle + ': ' + breakingAbstract);
}
newsWire = newsWireTemp;
});
}
loadNewswire().done(function () {
var items = newsWire;
$text = $('#newswiretxt span'),
delay = 10; //seconds
function loop (delay) {
$.each(items, function (i, elm){
$text.delay(delay*1E3).fadeOut();
$text.queue(function(){
$text.html(items[i]);
$text.dequeue();
});
$text.fadeIn();
$text.queue(function(){
if (i == items.length -1) {
loop(delay);
}
$text.dequeue();
});
});
}
console.log(items.length);
loop(delay);
});
});
See if this SO thread helps you.
From what I understand, you'd like to skip every other iteration, so checking i's parity to skip when appropriate should work.
For the lazy:
$.each(array, function(index, item) {
if(index % 2 === 0) return true; // This would skip
// Other logic
});
Let me know if it helps or not.
Instead of using two array indexes, use one object, var bn={};, add the two entries, bn.breakingTitle=breakingNews.title.toUpperCase(); and bn.breakingAbstract=breakingNews.abstract; then one push newsWireTemp.push(bn); so each entry in newsWire is more like newsWire[i].breakingTitle and newsWire[i].breakingAbstract.
One way to do it:
Fiddle: http://jsfiddle.net/q18dv4wr/
HTML:
<div id="test1">odds:</div>
<div id="test2">evens:</div>
JS:
var someData = [0,1,2,3,4,5,6,7,8,9,10];
var div1 = $('#test1');
var div2 = $('#test2');
$.each(someData,
function (index, value) {
if (index % 2 == 0) {
return;
}
else {
div1.append(' ' + value);
}
}
);
$.each(someData,
function (index, value) {
if (index % 2 != 0) {
return;
}
else {
div2.append(' ' + value);
}
}
);
EDIT: Seems I posted a moment too late. Someone else gave same idea already. =] Oh well.
You could do this:
$text.html(items[i]+ ": " +items[(i+=1)]);
But personally, I would push the breakingNews object into the array instead of having a different index for each property:
$(document).ready(function() {
var newsWire = [];
function loadNewswire() {
return $.getJSON('http://api.nytimes.com/svc/news/v3/content/all/all.json',
{'api-key': 'XXXXXXXXXXXXXXXXXXX'},
function(data) {
console.log(data)
var newsWireTemp = [];
for (var i = 0; i < data.results.length; i++) {
newsWireTemp.push(data.results[i]);
}
newsWire = newsWireTemp;
});
}
loadNewswire().done(function () {
var items = newsWire;
$text = $('#newswiretxt span'),
delay = 10; //seconds
function loop (delay) {
$.each(items, function (i, elm){
$text.delay(delay*1E3).fadeOut();
$text.queue(function(){
$text.html(items[i].title.toUpperCase()+ ": " +items[i].abstract);
$text.dequeue();
});
$text.fadeIn();
$text.queue(function(){
if (i == items.length -1) {
loop(delay);
}
$text.dequeue();
});
});
}
console.log(items.length);
loop(delay);
});
});
Try using .append() , checking if items[i + 1] is defined before appending items[i + 1] , else return empty string
$text.append(items[i] + (!!items[i+1] ? ":" + items[i+1] + " ": ""))
var items = "abcdefg".split("")
$.each(items, function(i, item) {
$("body").append(items[i] + (!!items[i+1] ? ":" + items[i+1] + " ": ""))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I've the following code. The return value of the function get_last_catergory_value is always undeifned. I've searched stackoverflow but couldn't debug the issue.
When I show the value being returned just before the return statement it shows the correct value. But when it is returned from function it is undefined. Can you please help me to resolve this?
function fetch_product(brand) {
var brand = brand;
//get last category id
var last_category = 'subcategory10';
var last_category_value = get_last_catergory_value(last_category);
alert(last_category_value); //undefined
}
function get_last_catergory_value(last_category) {
if($('.' + last_category).find(':selected').val() == 'none') {
last_category_number = last_category.substring(11);
last_category_number = parseInt(last_category_number);
last_category_number--;
last_category = last_category.substring(0, 11);
last_category = last_category + last_category_number;
get_last_catergory_value(last_category); //recall the function with values 'subcategory9', 'subcategory8' and so on...
} else {
var value = $('.' + last_category).find(':selected').val();
alert(value); //Gives the correct value here
return value;
}
}
Forgive me if its a trivial issue.
Thanks in Advance.
return statement is missing in the if block of get_last_catergory_value(last_category)
function get_last_catergory_value(last_category) {
if($('.' + last_category).find(':selected').val() == 'none') {
last_category_number = last_category.substring(11);
last_category_number = parseInt(last_category_number);
last_category_number--;
last_category = last_category.substring(0, 11);
last_category = last_category + last_category_number;
return get_last_catergory_value(last_category);
} else {
var value = $('.' + last_category).find(':selected').val();
alert(value); //Gives the correct value here
return value;
}
}
I'm trying to repurpose a "legacy function" to pass a function with parameters into another function and get called. I've seen bits and pieces of what I'm looking for, but my arguments keep getting passed as a single string. This is the calling code - the 4th parameter (starts with '_delRideNew') is what I need to call.
MODAL.show("Confirm", "Are you sure you want to delete this ride?","Yes","_delRideNew('" + id + "','" + day + "','" + attuid + "')","No","MODAL.hide();")
Here is the MODAL.show code (using easyui):
MODAL.show = function(title, msg, okbtn, okcallback, canbtn, cancallback) {
if(arguments.length > 2) {
$.messager.defaults.ok = okbtn;
$.messager.defaults.cancel = canbtn;
}
else {
$.messager.defaults.ok = "OK";
$.messager.defaults.cancel = "Cancel";
}
if(arguments.length === 6) {
var me = $.messager.confirm(title, msg, function(r) {
if(r) {
//parse out function and args
var pos = okcallback.indexOf("(");
var func = okcallback.substring(0,pos);
var argss = okcallback.substring(pos,okcallback.length);
argss = argss.replace("(", "");
argss = argss.replace(")", "");
var argArray = argss.split(",");
window[func](argArray);
}
else {
cancallback;
}
});
me.window('move',{
left:400,
top:document.body.scrollTop+document.documentElement.scrollTop+200
});
}
else {
confirm(msg, function(r) {
if(r) {
return true;
}
else {
return false;
}
});
}
}
The problem is when the window[func] gets called it passes the array as a single string here:
function _delRideNew(id,day,attuid){
alert(id); //shows all 3 params as a string
var txtURL = 'delRide.cfm?tech_attuid=' + attuid + '&ride_date=#getParam("month")#/' + day + "/#getParam("year")#";
SYS.loadScript(txtURL);
status = txtURL;
}
It's very much possible that I'm doing this completely wrong, but any help would be, well..helpful.
I use codemirror and jquery to "simulate" an xml-editor in the browser. Some xml-Tags include an "on"-attribute with two possible values (true or false). Would it be possible to toggle these values at an onclick event? Is a codemirror/jquery plugin available?
EDIT :
self-coded solution.
function attrtoggle(){
var pos = editor.getCursor();
var line = editor.getLine(pos.line);
var index = line.indexOf("on=");
if(index > 0){
//define range
if ( pos.ch -3 < index || pos.ch - 9 > index)
return false;
var len = 10;
var replace_pos = index + 4;
if(line.charAt(replace_pos) == "t"){
//insert false
line = line.replace('true', 'false');
} else{
//insert true
line = line.replace('false', 'true');
}
edited = pos.line;
editor.setLine(pos.line, line);
}
}
Just add an event-handler for the onclick event
$(".CodeMirror").attr("onclick","javascript:attrtoggle()");
By far not perfect (bad design and so on) , but it works as expected:
Just trigger the function at an onclick event.
function attributeToggle(){
var transitions = {
"on": {
"false":"true",
"true":"false"
}
}
var pos = editor.getCursor(); // object {line, ch}
var token = editor.getTokenAt(pos);
var line = editor.getLine(pos.line);
try{
var prev_pos = token.start - 1;
var prev_token = editor.getTokenAt({'line':pos.line, 'ch':prev_pos});
if(prev_token.className == "attribute")
var attr = prev_token.string;
else
return false;
if(typeof transitions[attr] === "undefined") //nothing to replace
return false;
var current_val = token.string.toLowerCase().replace(/(['"])/g, "");
if(typeof transitions[attr][current_val] === "undefined")
return false;
var line_new = line.substring(0, token.start) + \
"\"" + transitions[attr][current_val] + "\"" + line.substring(token.end);
editor.setLine(pos.line, line_new);
} catch (e){
console.log(e);
}
}
I am trying to pass a variable to a a function that I believe calls another function (I think) but am having problems. The variable I need to use in the second function is productid but several ways thAt I have tried have not worked. either a fix in javascript or Jquery will be great!!!
This is the line that I need the variable for
var error_url = '/ProductDetails.asp?ProductCode' + productid;
this is where the variable originates from...
var productid = form.elements['ProductCode'].value;
and here is the whole js code
function addToCart2(form, button) {
var softAdd = true;
var productid = form.elements['ProductCode'].value;
var qstr;
var bttnName = button.name;
button.disabled = true;
if (form.elements['ReturnTo']) {
form.elements['ReturnTo'].value = "";
}
qstr = serialize(form, bttnName + '.x', '5', bttnName + '.y', '5');
sendAjax('POST','/ProductDetails.asp?ProductCode=' + productid + '&AjaxError=Y', qstr , retrieveProductError2 ,displayServerError,false);
button.disabled = false;
return false;
}
function retrieveProductError2(result, statusCode) {
var ele = document.getElementById('listOfErrorsSpan');
var errorIndex = result.indexOf('<carterror>');
var productIndex = result.indexOf('<ProductIndex>')
if (errorIndex > -1 && productIndex == -1) {
var error_url = '/ProductDetails.asp?ProductCode' + productid;
window.location = error_url;
}
if (errorIndex != -1) {
//ele.innerHTML = result.slice(errorIndex + 11, result.indexOf('</carterror>'));
}
else {
ele.innerHTML = "";
if (productIndex == -1) {
sendAjax('GET','/AjaxCart.asp?GetIndex=True', '', showCart, null, false);
}
else {
productIndex = result.slice(productIndex + 14, result.indexOf('</ProductIndex>'));
sendAjax('GET','/AjaxCart.asp?Index=' + productIndex, '', showCart, null, false);
}
}
}
The easiest way is to just move your variable declaration outside of your method. So change the declaration of product id outside your addToCart2 method. So outside of that method you do this:
var product_id;
Then inside your method remove var from product_id and it will just be an assignment and not declaration.
Where you pass in retrieveProductError2 as your error callback for the sendAjax call, you could instead pass in:
function(result, statusCode) { retreiveProductError2(result, statusCode, productId);}
Then change the definition of your retreiveProductError2 function to accept the additional parameter.