I'm trying to set an input field to the value of a jQuery variable but it's refusing to cooperate. Can someone please tell me what I'm doing wrong? Essentially, I'm trying to get equipment failure counts to display in an input textbox so I can write the value back to a table. Each failure counts as 1 and is added to a total (truckFailsTot variable) when users click a Y/N radio button next to each type of failure. The example below just includes one failure for brevity.
HTML
div class="form-row">
<div class="form-group col-lg-12"><label class="col-form-label" for="TruckFailCount">TruckFailCount</label>
<input class="form-control" ${disabled( 'TruckFailCount')} id="TruckFailCount" maxlength="13" name="TruckFailCount" title="truckFailCount" type="text" value="${row.truckFailCount?html}" />
</div>
</div>
jQuery - I've commented out my failed attemps below. It seems like such a simple thing, yet nothing is working.
jQuery('body').on("change",'#TruckAirCompressor',function(){
if (this.value == "Fail") {
fail_TruckAirCompressor = 1;
}
else if (this.value == "Pass") {
fail_TruckAirCompressor = 0;
}
else {
}
truckFailsTot = fail_TruckAirCompressor + fail_TruckAirLines + fail_TruckBattery
+ fail_TruckBeltsHoses + fail_TruckBody + fail_TruckBrakesAccessories + fail_TruckBrakesParking
+ fail_TruckBrakesService + fail_TruckClutch + fail_TruckCouplingDevicesHitch
+ fail_TruckDefrosterHeater + fail_TruckDriveLine + fail_TruckExhaustMuffler
+ fail_TruckFluidLevels + fail_TruckFuelTanks + fail_TruckHorn + fail_TruckLights
+ fail_TruckMirrors + fail_TruckSafetyEquipment + fail_TruckSteeringMechanism
+ fail_TruckTiresRimsWheels + fail_TruckWindows + fail_TruckWindshieldWipers;
// var t = truckFailsTot;
// $('#TruckFailCount').value(t);
// document.getElementById("#TruckFailCount").innerHTML=t;
// var val1 = truckFailsTot;
// $('#TruckFailCount').val(val1);
// var fooBar = 1;
// $('#TruckFailCount').val(fooBar);
});
Thanks in advance!
I stumbled upon the correct syntax needed to assign a jQuery variable to an input text field and wanted to update my question in case someone else runs across a similar issue. All the jQuery documentation I'd come across recommended setting the value of the input field using .val(). Doing so didn't work for me, but the below code did.
var truckFailsTot;
truckFailsTot = fail_TruckAirCompressor + fail_TruckAirLines + fail_TruckBattery;
document.getElementById("TruckFailCount").value = truckFailsTot;
Related
Am using AJAX code whereby I handle errors form the backend code.. All is working well except that I want to alert the errors individually to the user in a numbered list
Expected Output
1. Please insert a valid phone number
2. Please insert your email
3. Please insert a valid passport number
AJAX code handling errors
error: function(data) {
//Unblock the spinner
$.unblockUI();
var errors = '';
for(datos in data.responseJSON){
errors += data.responseJSON[datos] + '<br>';
}
//Alert each error individually
alert(errors);
}
I would recommended that you should be using a for loop instead of for in. See why here
error: function(data) {
//Unblock the spinner
$.unblockUI();
var errors = '';
for(var i = 0; i < data.responseJSON.length; i++){
// Remove the "(i+1) + '. ' + " if your json response already contains that part.
errors += (i+1) + '. ' + data.responseJSON[i] + '\n'; // <-- Notice how the br tag is changed to a new line
}
alert(errors)
}
I also changed the <br> tag to a \n as alerts don't support html tags.
It is not clear to me from the question, whether you want a
multiline alert message or
multiple alert dialogs as the
output,
but in case 1) is true, you should use newline ("\n") instead of br tag - see New line in JavaScript alert box and the code could look like:
var i = 1,
errors = '';
for(datos in data.responseJSON){
errors += i + '. ' + data.responseJSON[datos] + '\n';
i++;
}
//Alert each error individually
alert(errors);
If 2) is what you need, you should call alert() for each error message
I am trying to automate my businesses blog. I want to create a dynamic html string to use as a wordpress blog description. I am pulling text data from email body's in my gmail account to use as information. I parse the email body using the first function below.
I have everything working properly except for the for loop (in the second code block) creating the description of the post. I have searched for hours and tried dozens of different techniques but I cant figure it out for the life of me.
Here is how I am reading the text values into an array:
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
This is how I am trying to dynamically output the text arrays to create a basic HTML blogpost description (which I pass to xmlrpc to post):
var1 = getMatches(string, regex expression, 1);
var2 = getMatches(string, regex expression, 1);
var3 = getMatches(string, regex expression, 1);
var3 = getMatches(string, regex expression, 1);
var fulldesc = "<center>";
var text = "";
for (var k=0; k<var1.length; k++) {
text = "<u><b>Var 1:</u></b> " + var1[k] + ", <u><b>Var 2:</u></b> " + var2[k] + ", <u><b>Var 3:</u></b> " + var3[k] + ", <u><b>Var 4:</u></b> " + var4[k] + ", <br><br>";
fulldesc += text;
}
fulldesc += "</center>";
Lastly here is the blog post description code (using GAS XMLRPC library):
var fullBlog = "<b><u>Headline:</u> " + sub + "</b><br><br>" + fulldesc + "<br><br>General Description: " + desc;
var blogPost = {
post_type: 'post',
post_status: 'publish', // Set to draft or publish
title: 'Ticker: ' + sub, //sub is from gmail subject and works fine
categories: cat, //cat is defined elsewhere and works fine
date_created_gmt: pubdate2, //defined elsewhere (not working but thats another topic)
mt_allow_comments: 'closed',
description: fullBlog
};
request.addParam(blogPost);
If there's only one value in the var1,2,3,4 arrays all works as it should. But any more than 1 value and I get no output at all from the "fulldesc" var. All other text variables work as they should and the blog still gets posted (just minus some very important information). I'm pretty sure the problem lies in my for loop which adds the HTML description to text var.
Any suggestions would be greatly appreciated, I'm burned out trying to get the answer! I am a self taught programmer (just from reading this forum) so please go easy on me if I missed something stupid :)
Figured it out: It wasnt the html/text loop at all. My blogpost title had to be a variable or text, but not both.
Not working:
title: 'Ticker: ' + sub, //sub is from gmail subject and works fine
Working:
var test = 'Ticker: ' + sub;
//
title:test,
I am trying to output the contents of an array within an array to a small area on an HTML page. I can only get one dimensional arrays to output.
Simplified, the intended array has a number of properties, but am struggling to find the correct code to output an array nested inside an array.
Properties are;
ID(integer)
Location(string)
Postcode(String)
other properties may be added down the line.
To output the information I am using the following code (which I can only get to work on a single array - even if I change to using [i][x] )
document.write("<tr><td>ID " + i + " is:</td>");
document.write("<td>" + LocationArray[i] + "</td></tr>");
How do I correctly create an array capable of storing the information and then output a specific part of it? eg display the contents of LocationArray[2][3]
Is document.write an efficient method, or is there something better?
I put something together, that could help you. To answer your question at the end about creating an array 'the right way'; There are two possibilities:
Create an array with 'property'-based properties : var locationsArray = [{ID:123,Location:'blabla',Postalcode:'1234'}];
Create an array with string-keys : var locationsArray = [{'ID':123,'Location':'blabla','Postalcode':'1234'}];
In my example I used the first attempt.
To your second question: document.write just writes at the end of the document. If you want to write to a specific area of the website, create a container (for example) and give it an id. Then change the property innerHTML of the created container, as I did in my example.
HTML:
<div id="locations"></div>
<button onclick="printLocations()">Print Locations</button>
Javascript:
function printLocations() {
var locationsArray = [{
ID : 123,
Location : 'Candyland',
Postalcode : '1234'
}, {
ID : 456,
Location : 'Middle-Earth',
Postalcode : '4567'
}
];
var locationsHtml = '';
for (var index in locationsArray) {
locationsHtml += 'ID: ' + locationsArray[index].ID + ', ' +
'Location: ' + locationsArray[index].Location + ', ' +
'Postalcode: ' + locationsArray[index].Postalcode + '<br />';
}
console.log(locationsHtml);
document.getElementById('locations').innerHTML = locationsHtml;
}
If you just want to write a specific part of the array (in your example just one specific location) just use the index you want and access it the same way as in the for loop in my example:
var locationsHtml = locationsArray[1].ID + locationsArray[1].Location + etc...;
/*with string-keys: var locationsHtml = locationsArray[1]['ID'] + etc...;*/
document.getElementById('locations').innerHTML = locationsHtml;
I created a very simple index.html file and inside I included some jquery script. You can see below:
<script>
$(document).ready(function(){
var $tweets = $('.tweets');
var current_position = -1;
function getTweets(){
var index = streams.home.length - 1;
var cp = index;
while(index >= current_position + 1){
var tweet = streams.home[index];
$tweets.append('<div class="twe"><span class="name" style="color:blue">' + '#' + tweet.user + ': ' + ' </span><span class="message">' + tweet.message + tweet.created_at + '</span></div>');
index--;
}
current_position = cp;
}
getTweets();
$('button').click(function(){
getTweets();
});
$('.name').click(function(){
$tweets.prepend('<div>' + 'objname' + streams.home.length + '</div>');
});
});
</script>
there is one button used for updates all the tweets and dynamically put them in the section with class="tweets" part. And this button works fine no matter how many times I press it.
Then I add click event to all those with class name 'name' and once I click it , it will add 'objname' + streams.home.length to the front of my
section class="tweets" part. The problem is first time , I CLICK the $('.name') it works fine , but later after I added more items through $('button') click event. it seems the new created $('.name') items is not clickable which means they don't generate 'objname' + streams.home.length to the front of my
section with class="tweets" part. I am really confused here and don't know why.
try following
$("body").on("click",".name",function(){
$tweets.prepend('<div>' + 'objname' + streams.home.length + '</div>');
});
As your element gets added runtime on the page, it needed to be taken care separately with help of "on" which bind events automatically when event gets created.
check reference
I have a small Google Apps Script that processes a date column in a spreadsheet and generates entries in a Calendar (birthdays).
Work is fine, but when adding reminders to the (recently-created) CalendarEvent, an error is thrown :
Service error: CalendarApp: Mismatch: etags = ["GUQKRgBAfip7JGA6WhJb"], version = [63489901413]
I've tried to perform 1 second sleep after creating event (wait for changes to be done in calendar), but no luck on this...
BTW, events are created succesfully, only reminders cannot be added.
PD: the calendar is one I own, but not my primary calendar.
Here is part of the code:
try
{
birthday = new Date(Data[i][BirthColumn]);
birthday.setFullYear(today.getFullYear());
birthday.setUTCHours(12);
birthlist += Data[i][NameColumn] + " --> " + birthday + "\n";
calendarevent = cal.createAllDayEventSeries("¡Cumpleaños " + Data[i][NameColumn] + "!", birthday, CalendarApp.newRecurrence().addYearlyRule().times(YearsInAdvance));
if (calendarevent == null)
success = false;
else
{
//This sentence fails every single time.
calendarevent.addEmailReminder(0);
calendarevent.addPopupReminder(0);
calendarevent.addSmsReminder(0);
}
}
catch (ee)
{
var row = i + 1;
success = false;
errlist += "Error on row " + row + ": check name and birth date. Exception Error: " + ee.message + "\n";
}
This is the portion of the code I finally change to make it work, as Serge insas suggest me before:
if (calendarevent == null)
success = false;
else
{
cal.getEventSeriesById(calendarevent.getId()).addEmailReminder(0);
cal.getEventSeriesById(calendarevent.getId()).addPopupReminder(0);
cal.getEventSeriesById(calendarevent.getId()).addSmsReminder(0);
}
This is a known issue
See comment nr 67 for a working workaround : the trick is to re-call the event for every item you want to add (reminder, popup...) using cal.getEventSeriesById(eventID) after you get the Id simply with .getId()
I use it in some scripts and it solved the issue for me.