Creating Javascript Buttons - javascript

I have created buttons using javascript, these buttons are created onload by the javascript page. The number of buttons created, as well as the button attributes (id, name), depend on the info that is fetched from a database table. Now I need to use the buttons independently, but I don't know the id in advance so I could mention it on any function, please help.
var CABLE_BOM_ALT_QUERY_PAGE = 'GetAltFromBom.json.aspx';
var WIRE_TYPE = 'AVSSXF2B';
var WIRE_LENGTH = 2000;
$(document).ready(function () {
FetchCableBom();
});
function FetchCableBom() {
$.ajax({
url: CABLE_BOM_ALT_QUERY_PAGE
, data: "WireType=" + WIRE_TYPE + "&WireLength=" + WIRE_LENGTH
, dataType: 'json'
, success: DisplayButtons
, error: ErrorHandler
, async: false
});
}
function createButtons(tbID, tbClass, tbType, tbValue, onClick) {
return '\n<input'
+ (tbID ? ' id=\'' + tbID + '\'' : '')
+ (tbClass ? ' class=\'' + tbClass + '\'' : '')
+ (tbType ? ' type=\'' + tbType + '\'' : '')
+ (tbValue ? ' value=\'' + tbValue + '\'' : '')
+ (onClick ? ' onclick=\''+ onClick + '\'':'')
+ '>';
}
function DisplayButtons(cableData) {
var newContent = '';
$.each(cableData, function (i, item) {
newContent += createButtons(item.CommonCable, null, "submit", item.CommonCable, toggle);
});
$('#Categories').html(newContent);
}
function toggle() {
console.log("P#ssw0rd");
return;
}
function ErrorHandler() {
alert('ERROR: ' + jqXHR.status + '\r\nURL: ' + this.url + '\r\nContact the I.T Department.');
}

Even after reading it a few times I am not quite sure I know what you are trying to do. But here is my guess: You have some result set containing button attributes which come from a database. And you want these buttons "independently", I assume without having queried the database, because you need some kind of Id.
Have you thought about statically pre-populating your result set whenever the database hasn't been queried yet? Something along the lines of this:
if (hasDatabaseResult) {
buttonData = getDatabaseResult();
} else {
buttonData = [ {id : 1, name : "First record"} ]
}

Related

getJSON does not work on button click but does with hitting enter key

My getJSON request and the rest of my function works fine if the user hits enter after filling out the field however my function does not get past the getJSON request if they click the search button.
I've found some similar post on SO but haven't been able to fix my issue yet. I've tried adding .live before my .click event and also tried adding e.preventDefault in a couple different spots but that hasn't resolved it either.
My HTML looks like this
<input id="zipCode" maxlength="5" type="text"> <button id="zipSearch" onclick="findByZip()">Search</button></p>
My JS looks like this
$(document).ready(function () {
$('#zipSearch').click(findByZip);
$('#zipCode').bind('keydown', function (e) {
if (e.keyCode === 13) { // 13 is enter key
e.preventDefault();
findByZip();
return false;
}
});
}
);
function findByZip() {
console.log('running findByZip');
var zip = $('#zipCode').val();
var stateName = $('#stateName');
stateName.text("Reps for " + zip);
$("#results").empty();
var url='//something.com/api/Reps?Zipcode=' + zip;
console.log(url);
$.getJSON(url, function (data) {
console.log(data);
if (data.length == 0) {
var header = "<h3>No matches found.</h3>"
$('#result').append(header);
}
else {
$.each(data, function (i, item) {
var header = "<h3>Manufacturer's Representative</h3>";
var businessName = $("<h4 id=businessName" + i + "></h4>").text(item.BusinessName);
var contactName = $("<h4 id=contactName" + i + "></h4>").text(item.Contact);
var address = $("<div id=address" + i + "></div>").text(item.Address);
var address2 = $("<div id=address2" + i + "></div>").text(item.City + ", " + item.State + " " + item.Zipcode);
var phone1 = $("<div id=phone1" + i + "></div>").text("PH: " + item.Phone1);
var phone2 = $("<div id=phone2" + i + "></div>").text("PH2: " + item.Phone2);
var fax = $("<div id=fax" + i + "></div>").text("FAX: " + item.Fax);
var email = '<div id=email' + i + '>' + item.Email + '</div>';
var website = '<div id=website' + i + '>' + item.Website + '</div>';
if (item.RegionalRepId == item.Id) {
header = "<h3>Regional Manager</h3>";
}
$("#results").append(header, businessName, contactName, address, address2, phone1, phone2, fax, email, website);
if (businessName[0].textContent == "null") {
$("#businessName" + i).remove();
}
if (contactName[0].textContent == "null") {
$("#contactName" + i).remove();
}
if (address[0].textContent == "null") {
$("#address" + i).remove();
$("#address" + i).remove();
}
if (phone1[0].textContent == "PH:null") {
$("#phone1" + i).remove();
}
if (phone2[0].textContent == "PH2:null") {
$("#phone2" + i).remove();
}
if (fax[0].textContent == "FAX:null") {
$("#fax" + i).remove();
}
if (email.includes("null")) {
$("#email" + i).remove();
}
if (website.includes("null")) {
$("#website" + i).remove();
}
});
}
});
}
expected result is to just pull and display data by different click events and searches to a map. Clicking on a state works, typing in a zipcode and hitting enter works, but typing in a zipcode and clicking search does not work.
If you guys have any suggestions it would be greatly appreciated. Young in my career, mostly have worked in .NET, C#, and Xamarin. Unfortunatly JS and JQuery are a little new to me. Thanks!
My form wasn't preventing a default on form via the submit button. It was only preventing the default on enter. Once I added type="button" inside my <button> tag everything worked fine.

Multiple of the similar "Select Option" ID , Dynamic Javascript Code

1) I need to find a way to have multiple of id="select-repo" because every single "add another item" is the same. "Add Another Item" is suppose to add another row of html with that id="select-repo" for now it's just a empty textbox.
Generate Functions on the go? Dynamic Functions? I can easily loop the Select box but not the "$('#select-repo').selectize({" function i believe.
2) After number 1 is solved, I need to find a way to know which row of data to update after an option has been selected.
3) Is this easier to get done with VUE.JS, since i'm using laravel , integration should be easier with Vue.JS
What is your advice, I was told to use stuff like ReactJS / styled components? is there anyway to not switch framework to just get this done?
Please Advice.
HTML Code
<td><select id="select-repo" class="repositories"></select></td>
JS Code
<script>
//<select id="select-repo"></select>
$('#select-repo').selectize({
valueField: 'url',
labelField: 'name',
searchField: 'name',
options: [],
create: false,
render: {
option: function(item, escape) {
return '<div>' +
'<span class="title">' +
'<span class="name"><i class="icon ' + (item.fork ? 'fork' : 'source') + '"></i>' + escape(item.name) + '</span>' +
'<span class="by">' + escape(item.username) + '</span>' +
'</span>' +
'<span class="description">' + escape(item.description) + '</span>' +
'<ul class="meta">' +
(item.language ? '<li class="language">' + escape(item.language) + '</li>' : '') +
'<li class="watchers"><span>' + escape(item.watchers) + '</span> watchers</li>' +
'<li class="forks"><span>' + escape(item.forks) + '</span> forks</li>' +
'</ul>' +
'</div>';
}
},
score: function(search) {
var score = this.getScoreFunction(search);
return function(item) {
return score(item) * (1 + Math.min(item.watchers / 100, 1));
};
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'https://api.github.com/legacy/repos/search/' + encodeURIComponent(query),
type: 'GET',
error: function() {
callback();
},
success: function(res) {
callback(res.repositories.slice(0, 10));
}
});
},
onChange: function(value) {
alert(value);
}
});
</script>
Since id can not be the same, you can define a global variable like index to memo the count as part of id;
Like to dynamically add select with id "select-repo"+index; e.g. select-repo1, select-repo999
Here's an example:
var index = 1;
function addSelect(){
$('#somewhere').append('<select id="select-repo'+index+'">');
$('select-rep'+index).selectize(){
....
};
index++;
}
And you can easily get the select index by parse Id string.

Ajax callback from two functions

Hello i have a problem with ajax and two callbacks code look like that
loadTasks(function(tasks) {
taskhtml = whatStatus(tasks);
loadSupportList(function(tasks) {
supporthtml = support(tasks);
$("#devtask-table").html(
titleDraw() + "<tbody>" + supporthtml + taskhtml
+ "</tbody>");
hideCurtain();
});
});
And it's work fine when loadSupportList or loadTasks have records. But when one of them don't i get Error, status = parsererror, error thrown: SyntaxError: Unexpected end of input. And it jump off function and leave me with nothing. My ajax function looks that way :
function loadSupportList(callback) {
$.ajax({
type : "POST",
url : url,
data : {
userId : userId,
sessionId : sessionId
},
success : function(data) {
callback(data['tasks']);
},
error : function(jqXHR, textStatus, errorThrown) {
console.log("Error, status = " + textStatus + ", " + "error thrown: "
+ errorThrown);
}
});
}
And i dont know what to change, to ignore(?) or made some json with ('success')? Is there a way? Thanks for your time.
I make something silly, but its work so it's not silly
loadTasks(function(tasks) {
taskhtml = whatStatus(tasks);
$("#devtask-table").html(
titleDraw() + "<tbody>" + supporthtml + taskhtml
+ "</tbody>");
loadSupportList(function(tasks) {
supporthtml = support(tasks);
$("#devtask-table").html(
titleDraw() + "<tbody>" + supporthtml + taskhtml
+ "</tbody>");
hideCurtain();
});
});
assuming tasks returns an array... update your loadSupportList function like this..
success : function(data) {
var ret = [];
if(
'object' == typeof data &&
'undefined' != typeof data.tasks
) ret = data.tasks;
callback(ret);
}

How do I get specific value key pair in ajax javascript for datatype json?

I want to get the value of "status" from data in the code below,
$.ajax({
dataType: "json",
url: "calendar/php/date.php",
type: "POST",
data: {
select: "%Y-%c-%e",
where: "%Y-%c",
d: y + "-" + m,
order: "timestamp, id"
},
beforeSend: function() { $('#loading').show(); },
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
$("<span class=\"label label-success\">" + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
complete: function() { $('#loading').fadeOut(200); }
});
Following is some part of the console.log result:
key: 2014-11-11
value: {"2014-11-11":[{"0":"3","1":"2014-11-11 11:11:00","2":"2014-11-28 10:12:00","3":"test","4":"test","5":"0","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-11","id":"3","timestamp":"2014-11-11 11:11:00","toTimestamp":"2014-11-28 10:12:00","title":"test","location":"test","status":"0","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-11"}],"2014-11-12":[{"0":"15","1":"2014-11-12 07:07:00","2":"2014-11-12 03:09:00","3":"test","4":"test","5":"1","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-12","id":"15","timestamp":"2014-11-12 07:07:00","toTimestamp":"2014-11-12 03:09:00","title":"test","location":"test","status":"1","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-12"}]}
I want get the value of "status" i.e 0, as seen in the above result, in order to include it in the for loop (for (var key in data) {...}) to change the class 'label-success' to 'label-failure' if the status is 0. Could you help me?
Hello maybe I am wrong but
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
returns the whole data object in string format when you say JSON.stringify(data);
You want the value which is returned when you give data a specific key to read values from:
console.log('key: ' + key + '\n' + 'value: ' + data[key]);
EDIT: Im not sure if data[key] will return a [object Object]... if it does try JSON.stringify(data[key])
I would also suggest Itterating through data with the
for(var i = 0; i < data.length; i++){}
this makes it readable and is measured the most performant way of extracting data.
EDIT nr 2:
This is your object:
{"2014-11-11":[{"0":"3","1":"2014-11-11 11:11:00","2":"2014-11-28 10:12:00","3":"test","4":"test","5":"0","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-11","id":"3","timestamp":"2014-11-11 11:11:00","toTimestamp":"2014-11-28 10:12:00","title":"test","location":"test","status":"0","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-11"}],"2014-11-12":[{"0":"15","1":"2014-11-12 07:07:00","2":"2014-11-12 03:09:00","3":"test","4":"test","5":"1","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-12","id":"15","timestamp":"2014-11-12 07:07:00","toTimestamp":"2014-11-12 03:09:00","title":"test","location":"test","status":"1","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-12"}]}
this is a bit nested, so try to get an overview of what you have:
data = {
"2014-11-11": [],
"2014-11-12": []... }
This object has a length method that returns the length of your object. this allows you to itterate over the Data Object will give you "2014-11-11" as key and with this key you can access your values like this: data[key] this will return your array...to read data from your array you will have to itterate again data[key][i]... now you can read the data inside each array element like this
data[key][i]["status"];
Hope this helped somehow... cant be bothered to write all this code :D
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
var status = data['status'];
var klass = status === 0 ? 'label-failure' : 'label-success';
$('<span class="label '+klass+'">' + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
Try this code instead.
$.ajax({
dataType: "json",
url: "calendar/php/date.php",
type: "POST",
data: {
select: "%Y-%c-%e",
where: "%Y-%c",
d: y + "-" + m,
order: "timestamp, id"
},
beforeSend: function() { $('#loading').show(); },
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
for (var i in data[key]) {
$("<span class=\"label " + ((data[key][i] === "0") ? "label-failure" : "label-success") + "\">" + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
}
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
complete: function() { $('#loading').fadeOut(200); }
});

Javascript function not called in jQuery $.submit

Hey there,
Again, I've been searching a solution to find out why a function, would not being called... and guess what, I did not find.
I have a form, that I submit using jQuery Ajax. When error, I get every local data, I got, I sorted them, and show them to the user.
Here is the sample code :
$.ajax({
type: "POST",
url: "http://xxx/register.php",
data: form,
success: function(msg){
//console.log("Data Saved: " + msg);
$.iGrowl(2,stringdata[4]);
var data = parseJSON(msg);
if(data.msg.score != undefined){
var cpt = 0;
$.each(data.msg.score, function(index,el){
if(cpt<8){
if(el.selected)
$('tbody').append('<tr class="win"><td>' + el.name + '</td><td>' + el.score + '</td></tr>');
else
$('tbody').append('<tr><td>' + el.name + '</td><td>' + el.score + '</td></tr>');
}
});
}
else{
$.iGrowl(3,"Erreur inconnue...");
}
$("#scorediv").css("visibility","visible");
$( "#formule" ).css('opacity',0);
$( "#scorediv" ).css('opacity',1);
},
error: function(data) {
cpt = 0;
var i = 0;
score.each(function(r){
arrayScore[i] = r;
i++;
});
arrayScore.sort(function(a, b){
console.log("sorting...");
if(a[3])
{
if(b[3])
{
return (b[3].value - a[3].value); //causes an array to be sorted numerically and descending
}
}
});
$.each(arrayScore, function(index,el){
//arrayScore.forEach(function(el) {
//score.each(function(el){
if(cpt<8)
{
if(el[2].value == form[2].value)
$('tbody').append('<tr class="win"><td>' + el[1].value + '</td><td>' + el[3].value + '</td></tr>');
else
$('tbody').append('<tr><td>' + el[1].value + '</td><td>' + el[3].value + '</td></tr>');
cpt++;
}
else
return false;
});
var user = form;
store.save(user, function(r) {
});
$.iGrowl(3,stringdata[5]);
$("#scorediv").css("visibility","visible");
$("#formule").css('opacity',0);
$( "#scorediv" ).css('opacity',1);
}
});
My array is never sorted. If I change this part :
var i = 0;
score.each(function(r){
arrayScore[i] = r;
i++;
});
by this :
score.each(function(r){
arrayScore.push(r);
});
arrayScore is never filled.
I try to execute each line in the console step by step, it works.... I'm getting kind of crazy... and I really do not know what could have happened ?
Any help would be graceful appreciate !
P.S : I'm using, jQuery1.5 + Lawnchair and CSS3 animation.
Code tested on safari and chrome.
Thanks !
Javascript array objects don't support a method called each. You should try
$.each(score, function(index, value){...});

Categories

Resources