Pure Javascript on screen keyboard issue - javascript-events

I have an on-screen keyboard and 5 input boxes. My problem is when I focus on an input box and input something, nothing will happen. I want to add input every time I focus on an input box.
Here's my simple code. This code only works for 1 input field. I want to make this work for 5 or 4 input fields.
function writeKey(key){
if(key){
if(key == "Enter"){
key = "10";
} else if(key == "tab"){
document.getElementById("feld1").value += "\t ";
} else if(key=="backspace"){
document.getElementById("feld1").value=document.getElementById("feld1").value.slice(0,-1);
} else if(key==" "){
document.getElementById("feld1").value += " ";
} else {
document.getElementById("feld1").value += String.fromCharCode(key);
}
}
}

Take a look at document.activeElement which points to currently focused element.
You can rewrite your code like this using it:
function writeKey(key){
var el = document.activeElement;
if(key){
if(key == "Enter"){
key = "10";
} else if(key == "tab"){
el.value += "\t ";
} else if(key=="backspace"){
el.value = el.value.slice(0,-1);
} else if(key==" "){
el.value += " ";
} else {
el.value += String.fromCharCode(key);
}
}
}
Demo here
Please note that you should run writeKey not onclick but onmousedown. Otherwise focus will be already moved from an input. Demo reflects that.
Here is its html code:
<div onmousedown="writeKey('a');return false">Click key</div>
<input type="text" />
<input type="text" />
<input type="text" />
Also, take a look at return false; after writeKey is called. It will prevent default browser action and clicking on a key you will not loose a focus from your input. Without it you will need to set focus on an element after each key press.

I don't know how you actually call the writeKey method. You could rewrite your code like this:
function writeKey(key, fieldId){
if(key){
if(key == "Enter"){
key = "10";
} else if(key == "tab"){
document.getElementById(fieldId).value += "\t ";
} else if(key=="backspace"){
document.getElementById(fieldId).value =
document.getElementById(fieldId).value.slice(0,-1);
} else if(key==" "){
document.getElementById(fieldId).value += " ";
} else {
document.getElementById(fieldId).value += String.fromCharCode(key);
}
}
}
Or you could pass the filed itself:
function writeKey(key, field) {
...
field.value += "\t";
...
}

Related

I'm trying to make upgrade system I cannot find way to save this data after when I Start game

private void Update()
{
Score.text = puanlama.ToString();
if (puanlama < firstbarvalue)//used for first bar value to open button activeness
{
activeness.interactable = false;
}
if (puanlama >= firstbarvalue && counterbars == 1)//counterbar for button activeness
{
textforvalues.text = firstbarvalue.ToString();// button value on it
activeness.interactable = true;
}
if (counterbars == 2)
{
activeness.interactable = false;
}
if (puanlama >= secondbarvalue && counterbars == 2)
{
textforvalues.text = secondbarvalue.ToString();
activeness.interactable = true;
}
if (counterbars == 3)
{
activeness.interactable = false;
}
}
public void Buttonactiveness()// Button activeness that I assign to my button[Here button and bars that I used][1]
{
if (puanlama >= firstbarvalue && counterbars == 1)
{
Fuelbars[0].SetActive(true);
for (int i = 1; i < Fuelbars.Length; i++)
{
Fuelbars[i].SetActive(false);
}
puanlama = puanlama - firstbarvalue;
counterbars++;
}
else if (puanlama >= secondbarvalue && counterbars == 2)//Bars which is second one
{
Fuelbars[0].SetActive(true);
Fuelbars[1].SetActive(true);
for (int i = 2; i < Fuelbars.Length; i++)
{
Fuelbars[i].SetActive(false);
}
puanlama = puanlama - secondbarvalue;
counterbars++;
}
I'm trying to put some code to turn this code to player pref and save this data.
playerpref counter bar is not working any suggest
Button activeness that I assign to my buttonHere button and bars that I used
Fuelbars which I'm trying to add is important part of work
counterbar for button activeness
In update section I tried to control button activeness and I changed button text

Dojo.Connect with click event for div element inside loop

I'm trying to show alert message including click event on div element that are sought through a loop. The problem is that in any div I click, it is only displayed the alert of the last element. How can I solve? I do not understand the logic being performed.
for (var i = 0; i < this.legend.layerInfos.length; i++)
{
var sNomeDiv = "";
var sMensagem = "";
if (this.legend.layerInfos[i].layer.visible)
{
sNomeDiv = this.legend.id + "_" + this.legend.layerInfos[i].layer.id;
if (this.legend.layerInfos[i].layer.description == "" || this.legend.layerInfos[i].layer.description == "undefined" || this.legend.layerInfos[i].layer.description == "null")
{
sMensagem = "Nenhuma informação cadastrada para a camada " + this.legend.layerInfos[i].title;
}
else
{
sMensagem = this.legend.layerInfos[i].layer.description;
}
//Always display an alert with the text of the last element of the loop
dojo.connect
(
dojo.byId(sNomeDiv),
"onclick",
function()
{
alert(sMensagem + " --> " + sNomeDiv);
}
);
}
}

cascades bb10 dropdown error

hei guys...i have problem creating dropdown menu on bb10..
let's say i have dropdown A and dropdown B..the option
onSelectedIndexChange action on dropdown A will change the option of dropdown B..
here's the code :
RegisterPhone.cpp :
void RegisterPhone::initData(){
JsonDataAccess jda;
QVariantList country = jda.load("app/native/assets/countries.json").toList();
QVariant var;
foreach(var, country){
QVariantMap a = var.toMap();
countries.append(a);
if(a.value("cca3").toString()=="IDN"){
dropDownCountry->add(Option::create().text(a.value("name").toString()).selected(TRUE));
QVariantList b = a.value("callingCode").toList();
codeLabel->setText("+" + b.at(0).toString());
}else{
dropDownCountry->add(Option::create().text(a.value("name").toString()));
}
}
}
void RegisterPhone::initControl() {
connect(buttonReg, SIGNAL(clicked()), this, SLOT(doRegister()));
connect(dropDownCountry, SIGNAL(selectedIndexChanged(int)), this,
SLOT(onSelectedIndex(int)));
connect(codeDropDown, SIGNAL(selectedOptionChanged(bb::cascades::Option*)), this,
SLOT(onSelectedValue(bb::cascades::Option*)));
}
void RegisterPhone::onSelectedIndex(int i){
qDebug() << countries.at(i).toMap();
QVariantMap country = countries.at(i).toMap();
QVariantList codes = country.value("callingCode").toList();
int count = codes.count();
qDebug() << codeDropDown;
if(count>1){
codeDropDown->removeAll();
isDropDown = true;
qDebug() << "count lebih dari 1";
codeLabel->setVisible(false);
codeDropDown->setVisible(true);
foreach(QVariant var, codes){
codeDropDown->add(Option::create().text("+" + var.toString()));
}
codeDropDown->setSelectedIndex(0);
}
else{
isDropDown = false;
qDebug() << "count == 1";
codeLabel->setVisible(true);
codeDropDown->setVisible(false);
if(codes.at(0).toString()==""){
codeLabel->setText("");
}
else{
codeLabel->setText("+" + codes.at(0).toString());
}
}
}
void RegisterPhone::onSelectedValue(bb::cascades::Option* value){
stringCode = value->text();
}
i have no problem creating the UI..it works fine when built and run..but when i choose several times, it would stopped working..
i have found out the problem is when i do
codeDropDown->removeAll()
also when i debug, it stopped here too
void RegisterPhone::onSelectedValue(bb::cascades::Option* value){
stringCode = value->text();
}
i need this function to retrieve the value of the callingCode
i don't know how to fix it..can please somebody help me?
pardon for the bad english...
thanks

Validate an input field in order to be unique and non duplicate in jQuery mobile

In my jQuery mobile app I have an alarm service the user enter number of alarms Per day , once the user enters the number of alarms lets say 3 , app will create 3 input fields for time , when the user clicks save button to save data i need to validate all the created input time fields so the entered time not equal the current time, and be unique there is no alarms at this time , I have solved it by the following code but the problem is that when the user enter a unique time " a non repeated time" I change the exist value from true to false but it didn't enter and execute this condition
else if (exist == false && $(this).attr('value') != currentTime ) directly "once " the exist value is updated ,I need to click the save button again in order to make the code know that the exist value is changed , and continue saving the alarm data in the DB .
How can i solve this problem ? please help me ...
<body>
<div data-role="page" id="Alarm">
<div data-role="header" ></div>
<div data-role="content" >
<form>
<input type="number" id="AlarmTimes"/>
<label for="AlarmTimes" > Number of alarms Per day </lable>
<div id="timeFields" style="display:none;" >
</div>
<div>
<input type="button" id="SaveBtn" value="Save Alarm "/></div>
</form>
</div>
</div>
</body>
javascript
var alarm_TimesNum;
var exist = true;
var ExistAlarmTimesArr = [];
$('#AlarmTimes').on('keyup' , function(){
alarm_TimesNum = $('#AlarmTimes').attr('value');
var timeFields = $('#timeFields');
if(timeFields.children().length != 0 )
{
timeFields.empty();
timeFields.hide();
}
for( var i=1 ; i<= alarm_TimesNum ;i++)
{
timeFields.append($( '<div class="ui-grid-a" ><div class="ui-block-a"> <input type="time" name="alarmTime" class="AlarmTime" /></div>'
+'<div class="ui-block-b" ><label for=" alarmTime" ><font size="5px" style="font- weight: normal;" class="Time_label"> Time:: </font></label></div></div>'));
timeFields.trigger('create');
}
timeFields.show();
});
db.transaction(getExistAlarmsTime,transError,transSuccess);
$('#SaveBtn').on('click',function(){
$('.AlarmTime').each(function(i){
if( $(this).attr('value') == currentTime || $.trim( $(this).attr('value')).length ==0 )
{
$('.Time_label').each(function(j){ if(j==i){ $(this).addClass('missing');} });
if(i==0){ alert('Enter time for alarm 1 '); }
else if(i==1){alert('Enter time for alarm 2 '); }
else if(i==2){alert('Enter time for alarm 3 '); }
}
else if( $(this).attr('value') != currentTime && exist == true )
{
for( var k=0;k<ExistAlarmTimesArr.length;k++)
{
if( $(this).attr('value') == ExistAlarmTimesArr[k])
{
$('.Time_label').each(function(j){ if(j==i){ $(this).addClass('missing');} });
if(i==0){alert( 'Enter Another Time for alarm 1 you have another alarm at this time '); }
else if(i==1){ alert( 'Enter Another Time for alarm 2 you have another alarm at this time '); }
else if(i==2){ alert( 'Enter Another Time for alarm 3 you have another alarm at this time '); }
exist = true;
break;
}
else { exist = false; }
}
}
else if (exist == false && $(this).attr('value') != currentTime )
{
$('.Time_label').each(function(j){ if(j==i){ $(this).removeClass('missed');} });
NotifTime = $(this).attr('value');
TimeArr[j] = NotifTime;
j= j+1 ;
count ++;
}
});
// save data in the DB
});
function getExistAlarmsTime(tx)
{
tx.executeSql("SELECT Time FROM AlarmTBL ",[],AlarmTimeExist,transError);
}
function AlarmTimeExist(tx,result)
{
for(var j=0;j< result.rows.length; j++)
{
var row = result.rows.item(j);
ExistAlarmTimesArr[j] = row['Time'];
}
}
I think the issue could just be the use of .attr('value'), try subbing it for .val() instead. I think that will fix your issues.

Multiline texbox validation

I want to validate maxlegnth of 5 characters in each row of the multiline textbox
Help me
Here's an example: A TextArea and span to show the validation results.
<textarea cols="30" rows="10" onblur="validateRows(this)"></textarea><br/>
<span id="validationResults" style="color:red"></span>
Here's the JavaScript code to validate each row:
function validateRows(e){
var content = e.value.split("\n");
for(var line in content){
var charLength = content[line].length - 1;
var lineNumber = parseInt(line) + 1;
if(charLength > 5){
document.getElementById("validationResults").innerHTML += "* line "
+ lineNumber + " has " + charLength
+ " characters" + "<br/>";
}
}
}
This is a C# version. Can be used either in Web applications for server side validation or Windows applications. (In Web applications for client side validation, Jose Basilio's code is appropriate)
public static bool HasMax5CharsPerLine(TextBox target)
{
foreach (string Line in target.Text.Split(new char[] {'\n'}))
if (Line.Length > 5)
return false;
return true;
}
using split function(both in C# and Javascript) and then check length it.
var temp = [TextFromTextBox].split('\n');
foreach(var s in temp)
{
if(!ValidateFunction(s))
{
// code for show exception
}
}

Resources