I want to assign an sql sting to a variable in Javascript. But I want to loop through an array to build par of the sql statement.
static sql:
var tag = [fun, beach, sun];
var sql = "SELECT * FROM myTable "
+"WHERE id > 5" //...
// loop through tag array and add to the sql
function tagQuery(tag) {
for (var i = 0; i < tag.length; i++) {
var tagQuery = "AND WHERE tags like %'"+tag[i]+"'%";
return tagQuery;
};
}
It is not clear to me how to get each result of the tagQuery function to be added to the sql sting?
EDIT: maybe a more clear way to ask the question is: How can I get each iteration of the tagQuery function to be joined with the sql variable?
var tag = [fun, beach, sun];
var sql = "SELECT * FROM myTable WHERE id > 5";
function tagQuery(tag) {
var str = '';
for (var i = 0; i < tag.length; i++) {
str += " AND tags like '%" + tag[i] + "%' "
}
return str;
}
sql += tagQuery(tag);
Fiddle: http://jsfiddle.net/7P4us/2/
EDIT:
I took out the tagQuery function altogether, after you commented:
sql += tagQuery(tag); ...will only return the last iteration of the tagQuery loop
var tag = ['fun', 'beach', 'sun'];
var sql = "SELECT * FROM myTable WHERE id > 5";
if (tag[0] != null) {
sql += " AND (tags like '%" + tag[0] + "%' ";
}
if (tag[1] != null) {
for (var i = 1; i < tag.length; i++) {
sql += " OR tags like '%" + tag[i] + "%' ";
}
}
if (tag[0] != null) {
sql += ")";
}
But note: the jsFiddle link that Rusty put in a comment, since, shows that the tagQuery function can return all iterations... so seeing only the last iteration was probably in your implementation.
Related
I am trying to show all my localstorage items value on my index page but for some reason it is not showing. can anyone see what I am doing wrong in my code below. In my index page script I am looping thorough the length of local storage and trying to display them on screen, only thing that display is one item. Please help. thanks for your help.
here is my code (index page script):
document.addEventListener("DOMContentLoaded", function (event) {
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
})
The other script where I load it to localStorage:
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candsId');
var getCandId = document.getElementById("candsId");
var displayCandId = candidateId.options[candidateId.selectedIndex].value;
var id = 1;
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText))
id += 1
localStorage.getItem(`key${id}`);
window.location = "/";
}
"key${id}" is a template string, you need to use backticks `` instead of quotation marks "".
You could also loop through localStorage as you normally would for most JavaScript objects:
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key)) { // ignore the prototype methods
// Do whatever you want with key and value found here
console.log(key + ": " + localStorage[key]);
}
}
Typo: Use i instead id
var dataFromLocalStorage = localStorage.getItem(`key${id}`);
correct:
var dataFromLocalStorage = `localStorage.getItem("key${i}");
Another thing, You are updating same innerHTML
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
// do something with localStorage.getItem(localStorage.key(i));
// missing template string 'key${id}'
var id = 1;
function addTheEvent() {
var showText = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText));
id += 1;
window.location = "/";
}
I'm having trouble making this change on my program, I have some clue of what to do, but not a definitive solution. I want my program to be able to retrieve the data of a specific date using jquery datepicker, but I don't know how to pass the datepicker value to a prepared statement, any idea on how to do it.
try{
String query = "SELECT * FROM [" + GeneralData.DATABASE + "].[dbo].[VentasDetalle] "
+ "WHERE [Sucursal] = '" + GeneralData.suc + "' "
+ "AND [Date] = " + /*my doubt*/
System.out.println(query);
ps = connection.prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = ps.executeQuery();
int rowcount = 0;
if (rs.last()) {
rowcount = rs.getRow();
rs.beforeFirst();
}
ids = new String[rowcount];
prices = new double[rowcount];
for (int i = 0; rs.next(); i++) {
if (rs.getString("Type").replaceAll("\\s+", "").equals("PROD")) {
ids[i] = rs.getString("ProductCode").replaceAll("\\s+", "");
price[i] = rs.getDouble("price");
}
}
I am requesting data from a json to fill a table. I want to limit to 5 the request.
jQuery.getJSON("data/data.json", function(data) {
var table = $("table");
$.each(data, function(id, elem) {
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
});
})
Or another option is to add boolean key "active" to the data and that it brings me the data items with the value = true. How do i do this?
You can use .slice() to filter the returned array down to just the first 5 elements.
data = data.slice(0, 5);
Just use a simple for loop.
var json_arr, limit;
limit = 5; // set limit to whatever you like
json_arr = JSON.parse(json_data);
for(var i = 0; i < limit; i++;) {
var this_item = json_arr[i];
table.append(this_item); // do your thing
}
The best limit you can implement is on your own controller (where you get your data from)
But if you don't have access/don't want to change, you can simple achive this by JavaScript:
var limit = 5; //your Limit
for(var i in data){
if(i > limit) break;
var elem = data[i];
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
}
In PHP it's easy to create variables.
for($i=1; $i<=$ges; $i++) {
${"q" . $i} = $_POST["q".i];
${"a" . $i} = $_POST["a".i];
}
The result is $a1 = $_POST["q1];
How is the right way for that in jQuery?
I need to create it dynamicly for an ajax dataset.
for (var i = 1; i < ges; ++i) {
var finalVar = "input[name='a" + i + "']:checked";
var qtext = $("#q"+ i).text();
if ($(finalVar).val() == null) {
qvar = 0
} else {
qvar = $(finalVar).val();
}
//write question text and value in q1, a1, q2, a2,...
//generate ajax data
params = params + "q" + i + ":" + "q" + i + ", " + "a" + i + ":" + "a" + i + ","
}
I want to set the question text in q1 and the answer in a1.
Well if am not wrong you want to accumulate answers related to questions from the HTML and want to send the data through ajax..
So u can do something like this:
var QnA = {};
$('.eventTrigger').click(function(e) {
e.preventDefault();
$('#parent').find('.QnA').each(function() {
QnA[$(this).find('.Que').text()] = $(this).find('.Ans').val();
})
console.log(QnA);
})
https://jsfiddle.net/jt4ow335/1/
The only thing you can do about it, is:
var obj = {}
for(var i = 0; i < 10; i++)
obj['cell'+i] = i
console.log(obj)
and pass obj as data
I have an array in php which i am getting in Javascript.
Here is my php code
$query = "SELECT SeatNum FROM `$busNum` WHERE AB = 1";
$runQuery = mysqli_query($con, $query);
$i = 0;
foreach($runQuery as $row)
{
$availableSeats[$i++] = $row['SeatNum'];
}
And here i am getting this string in javascript
var getBookedSeats = <?php echo json_encode($availableSeats); ?>;
var bookedSeats =[];
for(var i =0 ; i <getBookedSeats.length ; i++){
bookedSeats[i] = getBookedSeats[i];
}
The array also saved in bookedSeats successfully. Now the problem is that when i used that array as a parameter to call function. Nothing goes in the parameter. Even there is no problem of scope. This is my function looks like:
var init = function (reservedSeat) {
//code
}
init(bookedSeats);
Implementation of init function is :
var settings = {
rows: 5,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
};
Seems the problem is that you are trying to compare the array values as numbers and you currently have them as strings. To convert them to numbers, you can simply use:
bookedSeats = bookedSeats.map(Number) // iterate over each bookedSeats element and return its numeric value
Which is the same as:
bookedSeats = bookedSeats.map(function(value){
return Number(value);
})
From the comments it looks like your variable bookedSeats is being assigned with values. However, if your init() function is expecting integers, you'll want to build the bookedSeats array with integers like so:
for(var i =0 ; i <getBookedSeats.length ; i++){
bookedSeats[i] = parseInt( getBookedSeats[i], 10 );
}
I do not use php but I belive php's json_encode returns a JSON formatted string. Which results in your JavaScript code storing individual characters from the string into the bookSeats variable.
You need to parse the string returned from php. For example...
var getBookedSeats = JSON.parse(<?php echo json_encode($availableSeats); ?>);