Why autofocus property works only on first trial? - javascript

I need to code a number of trials for a JsPsych experiment displaying a simple math question. The user must answer in a textbox as fast as possible and then press the Enter key to move to the next question. And so on.
On each question, a single textarea is shown for the user to type his/her answer, and such textarea must have focus immediately.
I've modified the survey-text plugin to continue through trials by pressing Enter, as well as adding the autofocus property on creation of each textbox. Problem is that autofocus works only for the first trial, and stops working for the rest.
Code is provided below (in order to work, JsPsych folder must be on the same dir):
<!doctype html>
<html>
<head>
<title>Habilidad Aritmetica</title>
<!-- Inicio llamada a libreria JsPsych + Plugin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="jspsych-5.0.3/jspsych.js"></script>
<!-- Plugin para recibir texto estilo survey -->
<script src="jspsych-5.0.3/plugins/jspsych-survey-text.js"></script>
<!-- Plugin para desplegar elementos tipo instrucciones -->
<script src="jspsych-5.0.3/plugins/jspsych-instructions.js"></script>
<!-- *** CSS *** -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="centered">
<script>
var aritm01={
type: 'survey-text',
timeline:[
{
questions:['<p>preg 1</p>']
}
]
};
var aritm02={
type: 'survey-text',
questions:['<p>preg 2</p>']
};
var aritm03={
type: 'survey-text',
questions:['<p>preg 3</p>']
};
function advance(event){
$("textarea").keydown(function(event){
console.log(event.keyCode);
//event.preventDefault();
if (event.keyCode == 13) {
console.log("User pressed enter. Clicking continue button");
var btn = document.getElementById("jspsych-survey-text-next");
btn.click();
//event.preventDefault();
}
});
}
function recoverfocus(event){
$("textarea").focus();
}
var second_battery = [];
second_battery.push(aritm01);
second_battery.push(aritm02);
second_battery.push(aritm03);
jsPsych.init({
timeline: second_battery,
on_finish: function(){
jsPsych.data.localSave('second_battery_results.csv', 'csv');
},
default_iti: 0
});
</script>
</div>
</body>
</html>
From JsPsych's survey-text plugin side, the important change is:
focused_box = $("#jspsych-survey-text-" + i).append('<textarea autofocus onfocus="advance(event)" onblur="recoverfocus(event)" required name="#jspsych-survey-text-response-' + i + '" cols="' + trial.columns[i] + '" rows="' + trial.rows[i] + '"></textarea>');
(yes, I know that in-line javascript is a bad idea, but so far is the only way I managed to make it work)
Stuff I've tried:
A lot of similar questions suggest the use of getElementById()
method, or getElementsByTagName() in order to handle the DOM
element, but for some reason none of them works.
I've also tried
using a timer to focus text areas, as suggested here (
the other solutions suggested on that topic didn't work neither).
As you can see from my
code, I'm trying to "recover" the focus using a function, which
triggers on Blur. I've also tried such approach onLoad(), with no
results in both cases.
I've tried displaying the questions on a
nested timeline inside a single trial, instead of using many trials.
No luck neither.
Am I missing something?
Some extra notes:
As you can guess from this question's tags, JQuery and HTML5 specific functions are totally allowed as solutions, in case that making autofocus work on its own isn't possible. No need to restrict yourselves, have fun.
This behavior has been tested on latest version of Firefox for Ubuntu 16, as well as the latest version of Chrome for Windows (Windows 10 specifically).
UPDATE: You can try this code here

You can apply the focus after you append the element to the page. In your modified survey-text plugin, try this on line 63:
$("#jspsych-survey-text-" + i +" textarea").focus();
This might make other things that you have in the code obsolete, but I didn't try any other modifications.

Related

Adding HTML Button to Dynamics CRM 2016 Form

What I'm attempting to do is add an HTML button that will trigger as really simple javascript function.
Essentially onclick, I want to see if a field contains a value of 0.00 - if so remove that value. Or, if the field does not contain data, add in the value of 0.00 so it should alternate between those two values.
<html>
<head>
</head>
<body>
<button onclick="ReCalc">Re-Calculate Balance</button>
<script>
function ReCalc() {
var BalanceWriteOff = Xrm.Page.getAttribute("jucy_balancewriteoff").getValue();
if ((BalanceWriteOff) ==null)
Xrm.Page.getAttribute("balancewriteoff").setValue("0");
Xrm.Page.data.entity.save();
if ((BalanceWriteOff) =="0")
Xrm.Page.getAttribute("jucy_balancewriteoff").setValue(null);
Xrm.Page.data.entity.save();
return;
}
</script>
</body>
</html>
When I try to run this on the form where the HTML element has been placed. Nothing is happening. I've thrown in some break points at the var and both if statements and I'm not getting a break when I'm triggering the onclick event.
I'm kind of stumped here. If anyone has any insights for me that would be awesome
Oops! In your onclick attribute you forgot to invoke the method.
To fix this, simply change onclick="ReCalc" to onclick="ReCalc()".
Here's a code pen to show you it works now - https://codepen.io/trentrand/pen/Jyomgr
To access CRM form fields from an HTML web resource, add this script to the HTML:
<script src="ClientGlobalContext.js.aspx" type="text/javascript"></script>
and prepend "parent" to the Xrm.Page object:
parent.Xrm.Page.getAttribute("jucy_balancewriteoff").getValue();

click a button on a web site automatically with javascript

I modify a code like that, for click a checkbox.
Such as,
Is there a any problem about button name or id. I could see just name and class. Is this a problem for work?
<html>
<head>
</head>
<body>
<button>Giris</button>
</body>
<script type="text/javascript">
var chkA5 = "button" class=formCheckBox type=checkbox value=ON name=chkA5
window.onload = function() {
document.getElementById("chkA5").checked = true
});
}
</script>
</html>
I copied all chechbox button properties on web site (F12 + Slect Element + click to check box) and pasted in my script. But I really confused, when I write a code in script, describing works for new things which I add or create. On this web site which I want to click a chechbox on has already buttons and text/check box. How can I create a connect with each other my scrips and web site.
In brief; I couldn't connect my scripts to web site's button and because of that I couldn't do any operation. Am I right?
How can I solve this problem? On picture which I shared, there are some code marked in a red square. This code works for desciribe some element in my scribs?
When we use document.get.ElementById().checked =true, on web site's element properties's has not a id? It has name and class.
Problem 1: getElementById should be getElementByName
Based on your screenshot, the input item you are trying to reference is:
<input name="chkA5" class="formCheckBox" type="checkbox" value="ON"></input>
and you are trying to getElementById()
document.getElementById("chkA5").checked = true
However, there is no id declared, so you will have to get the item by the name, using getElementByName():
document.getElementsByName("chkA5")[0].checked = true;
Problem 2: Your javascript has errors
This line will cause your script block fail:
var chkA5 = "button" class=formCheckBox type=checkbox value=ON name=chkA5
If you require a complete code sample, here is an example:
<html>
<head>
</head>
<body>
<input name="chkA5" class="formCheckBox" type="checkbox" value="ON"></input>
</body>
<script>
(function() {
document.getElementsByName("chkA5")[0].checked = true;
})();
</script>
</html>
Note: Make sure that the script block is at the end of your html, like in your example code provided.

Bootstrap-datepicker not displaying

I have looked up this question and I know it has been answered, but none of the other answers seem to work for me.
I think it might have something to do with all of the javascript on the page.
Here is my HTML code:
<div class="form-group">
<label for="birthday">Birthday</label>
<input type="text" class="form-control" name="birthday" id="birthday" >
</div>
If I remove the birthday id from the input and add it to the div the calendar is visible at all times under the input, but when I click into the input nothing happens
I am going to include all of my JS code just in case you see a conflict
Here is my JS code:
<!-- Loading Image Picker -->
<script src="../imgPicker/assets/js/jquery-1.11.0.min.js"></script>
<script src="../imgPicker/assets/js/jquery.Jcrop.min.js"></script>
<script src="../imgPicker/assets/js/jquery.imgpicker.js"></script>
<!-- Menu Toggle Script -->
<script>
$(document).ready(function() {
$('[data-toggle=offcanvas]').click(function() {
$('.row-offcanvas').toggleClass('active');
});
});
</script>
<!-- Bootstrap Select Script -->
<script src="../assets/js/bootstrap-select.js"></script>
<script>
$(document).ready(function() {
$("select").selectpicker({style: 'btn btn-default', menuStyle: 'dropdown-inverse'});
});
</script>
<!-- Bootstrap Datepicker Script -->
<script src="../vendor/datepicker/js/bootstrap-datepicker.js"></script>
<script>
$(document).ready(function() {
$('#birthday').datepicker({
autoclose: true
});
});
</script>
<!-- Upload Avatar Script -->
<script>
$(function() {
var time = function(){return'?'+new Date().getTime()};
// Avatar setup
$('#avatarInline').imgPicker({
url: '../imgPicker/server/upload_avatar.php',
aspectRatio: 1,
// We use the loadComplete to set the image
loadComplete: function(image) {
// Set #avatar image src
$('#avatar').attr('src', image.name / image.versions.avatar.url);
},
deleteComplete: function() {
$('#avatar').attr('src', 'avatar/avatar.png');
this.modal('hide');
},
cropSuccess: function(image) {
$('#avatar').attr('src', image.versions.avatar.url);
this.modal('hide');
location.reload();
}
});
});
</script>
<!-- Update Avatar Script -->
<script>
function updateAvatar(object){
$.ajax({
url: 'update-avatar.php',
data: 'avatartype=' + object.value,
cache: false,
error: function(e){
alert(e);
},
success: function(response){
// Reload the page to refresh data from database
location.reload();
}
});
}
</script>
<script src="../assets/js/jquery-ui-1.10.3.custom.min.js"></script>
<script src="../assets/js/jquery.ui.touch-punch.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
If add just the exact code I need in JSFiddle everything seemed to work fine, but for some reason I cannot get it to work in my code.
Can someone please help?
EDIT: I think I narrowed it down to a CSS issue. I am using Flat UI and when I remove this from my code everything seems to work, but I would like to continue using Flat UI. Has anyone worked with Flat UI and Bootstrap datepicker together? or does anyone know how I can resolve this issue?
Here is a JSFiddle of the issue.
Have you checked the Date Picker docs here:
Bootstrap Date Picker Docs
Looks like you're missing some key features such as:
<input class="datepicker" data-date-format="mm/dd/yyyy">
<input data-provide="datepicker">
It looks like there are "data-attributes" you can use rather than all the scripting you have done. I also wonder if input type should equal "date".
<input type="date" class="form-control" name="birthday" id="birthday" >
Which will trigger the HTML5 date-picker. Don't know if that's necessary or not but I would suggest revisiting the docs. Without a fiddle set up, it's hard to look for scripting conflicts but even if you have them the date-picker docs provide you with a "no conflict mode".
Give it a try!
I tried out your js and html. It seems to work with "birthday" id tied to the input element. It is missing the css/ styles though.
Here are some things I would try:
Try clearing the browser cache
Get rid of unnecessary js files. See if you can start from scratch and keep adding js as needed.
May be the source from where you got the js files is corrupted or not correct. (I downloaded all the js files you mentioned, I can provide you the copies if you want to try those.)
I will also look at differences between jQuery and bootstrap datepickers. You seem to have datepicker tied to input element similar to jQuery date picker. For reference : http://jqueryui.com/datepicker/
There was a conflict with my other CSS styles so I added this code to the datepicker3.css file:
.datepicker.dropdown-menu {
visibility: visible;
opacity: 1;
width: auto;
}
This seemed to have fixed the problem.

Is using custom HTML tags and replacing custom tags with outerHTML okay?

Is it alright to define and use custom tags? (that will not conflict with future html tags) - while replacing/rendering those by changing outerHTML??
I created a demo below and it seems to work fine
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<div id="customtags">
<c-TextField name="Username" ></c-TextField> <br/>
<c-NameField name="name" id="c-NameField"></c-NameField> <br/>
<c-TextArea name="description" ></c-TextArea> <br/>
<blahblah c-t="d"></blahblah>
</div>
</body>
<script>
/* Code below to replace the cspa's with the actual html -- woaah it works well */
function ReplaceCustomTags() {
// cspa is a random term-- doesn;t mean anything really
var grs = $("*");
$.each(grs, function(index, value) {
var tg = value.tagName.toLowerCase();
if(tg.indexOf("c-")==0) {
console.log(index);
console.log(value);
var obj = $(value);
var newhtml;
if(tg=="c-textfield") {
newhtml= '<input type="text" value="'+obj.attr('name')+'"></input>';
} else if(tg=="c-namefield") {
newhtml= '<input type="text" value="FirstName"></input><input type="text" value="LastName"></input>';
} else if(tg=="c-textarea") {
newhtml= '<textarea cols="20" rows="3">Some description from model</textarea>';
}
obj.context.outerHTML = newhtml;
}
z = obj;
});
}
if(typeof(console)=='undefined' || console==null) { console={}; console.log=function(){}}
$(document).ready(ReplaceCustomTags);
</script>
</html>
Update to the question:
Let me explain a bit further on this. Please assume that JavaScript is enabled on the browser - i.e application is not supposed to run without javascript.
I have seen libraries that use custom attributes to define custom behavior in specified tags. For example Angular.js heavily uses custom attributes. (It also has examples on custom-tags). Although my question is not from a technical strategy perspective - I fail to understand why it would strategically cause problems in scalability/maintainability of the code.
Per me code like <ns:contact .....> is more readable than something like <div custom_type="contact" ....> . The only difference is that custom tags are ignored and not rendered, while the div type gets rendered by the browser
Angular.js does show a custom-tag example (pane/tab). In my example above I am using outerHTML to replace these custom tags - whilst I donot see such code in the libraries - Am I doing something shortsighted and wrong by using outerHTML to replace custom-tags?
I can't think of a reason why you'd want to do this.
What would you think if you had to work on a project written by someone else who ignored all common practices and conventions? What would happen if they were no longer at the company to find out why they did something a certain way?
The fact that you have to just go through with JavaScript to make it work at all should be a giant red flag. Unless you have a VERY good reason to, do yourself a favor and use the preexisting tags. Six months from now, are you going to remember why you did things that way?
It may well work, but it's probably not a good idea. Screen readers and search engines may have a hard/impossible time reading your page, since they may not interpret the JavaScript. While I can see the point, it's probably better to use this template to develop with, then "bake" it to HTML before putting it on the server.

How do you write Valid XHTML 1.0 Strict code when you are using javascript to fill an element that requires a child?

I'm running my site through the W3C's validator trying to get it to validate as XHTML 1.0 Strict and I've gotten down to a particularly sticky (at least in my experience) validation error. I'm including certain badges from various services in the site that provide their own API and code for inclusion on an external site. These badges use javascript (for the most part) to fill an element that you insert in the markup which requires a child. This means that in the end, perfectly valid markup is generated, but to the validator, all it sees is an incomplete parent-child tag which it then throws an error on.
As a caveat, I understand that I could complain to the services that their badges don't validate. Sans this, I assume that someone has validated their code while including badges like this, and that's what I'm interested in. Answers such as, 'Complain to Flickr about their badge' aren't going to help me much.
An additional caveat: I would prefer that as much as possible the markup remains semantic. I.E. Adding an empty li tag or tr-td pair to make it validate would be an undesirable solution, even though it may be necessary. If that's the only way it can be made to validate, oh well, but please lean answers towards semantic markup.
As an example:
<div id="twitter_div">
<h2>#Twitter</h2>
<ul id="twitter_update_list">
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&count=1"></script>
</ul>
</div>
Notice the ul tags wrapping the javascript. This eventually gets filled in with lis via the script, but to the validator it only sees the unpopulated ul.
Thanks in advance!
The following fragment is valid XHTML and does the job:
<div id="twitter_div">
<h2 class="twitter-title">Twitter Updates</h2>
<div id="myDiv" />
</div>
<script type="text/javascript">
var placeHolderNode = document.getElementById("myDiv");
var parentNode = placeHolderNode.parentNode;
var insertedNode = document.createElement("ul");
insertedNode .setAttribute("id", "twitter_update_list");
parentNode.insertBefore( insertedNode, placeHolderNode);
parentNode.remove(placeHolderNode);
</script>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&count=5"></script>
Perhaps you could use javascript to write the initial badge HTML? You'd probably only want the badge code to be inserted in your document if javascript were available to populate it, right?
You'd just need to make sure your document writing happens before the javascript for your various badges.
Could you give a specific example of the HTML / link to a page with the invalid code?
The solutions might be different for each badge. In Twitter's case, you can just write your own callback function. Here's an example based on their badge code:
<div id="twitter_div">
<h2>#Twitter</h2>
<div id="twitter_update_list"></div>
</div>
<script type="text/javascript">
function updateTwitterCallback(obj)
{
var twitters = obj;
var statusHTML = "";
var username = "";
for (var i = 0; i < twitters.length; i++)
{
username = twitters[i].user.screen_name;
statusHTML += ('<li><span>' + twitters[i].text + '</span> <a style="font-size:85%" href="http://twitter.com/' + username + '/statuses/' + twitters[i].id + '">' + relative_time(twitters[i].created_at) + '</a></li>');
}
document.getElementById('twitter_update_list').innerHTML = '<ul>' + statusHTML + '</ul>';
}
</script>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=updateTwitterCallback&count=1"></script>
I put a <li> with "display:none" in the <ul> Tag:
<ul id="twitter_update_list"><li style="display:none;">A</li></ul>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/01241.json?callback=twitterCallback2&count=1"></script>
This does not disturb the script and in this case it works,
and I think its not a "undesirable solution" :)
At some point the page becomes valid, right? That's the only time it can really be validated.
I'm not sure a non-trivial page will remain valid at every point during its construction if it's constructed with a lot of DOM scripting.
This might not be the most popular opinion on this topic, but...
Don't worry about 100% validation. It's just not that big of a deal.
The point of validation is to make your markup as standard as possible. Why? Because browsers that are given markup that doesn't conform to the spec (eg, markup that does not validate) do their own error checking to correct it and display the page the way you intended it to look to the user. The quality of the browsers error checking varies, yadda-yadda-yadda, it's better to have valid markup... But it's not even your code that's causing the validation to fail! The people who wrote those badges probably tested them in multiple browsers (and you should do the same, of course), if they work as expected then just leave it at that.
In short, there's no prize for validating :)

Categories