Can't edit last two characters in HTML text input - javascript

I'll start by saying that I have no idea why this is happening, and that just yesterday it was working just fine. I have this input (it gets saved on the Onblur event), and I can edit everything in the input except the final two characters or numbers in any field. It is though that is fixed for some reason. I don't seem to recall this happening before this morning. So I'm expecting Rod Serling to come in at any moment and inform me that I am in fact in the twilight zone. I've switched back to any earlier commit, when I new it was working, and for some reason the problem persists. (Even after a hard refresh and flushing content just in case JS is stale). Everything else works, on blur the values are saved correctly, it's just the simple fact that I CAN'T CHANGE THE LAST TWO CHARACTERS IN THE INPUT FIELD!!! (sorry, it was a late night)
EDIT: Sorry, I should state that it starts out like this:
<td onclick="addInput(this);" id="website_revenue:2017-03-16">$479,432.00</td>
And the input is added just fine.
If the value in the input is this:
<input type="text" id="input:website_revenue:2017-03-06" value="$479,432.00" />
I can't edit the "00".
I first thought, maybe it's a decimal issue, but I can't edit the last two characters in a whole number:
<input type="text" id="input:website_revenue:2017-03-06" value="360">
In that case I can't edit the "60".
Maybe it's my entire lack of sleep, but I've never seen anything like this before in my 15 years of programming...and I have NO IDEA why it's happening. No clues in the console, no errors are being flagged. Any ideas? Am I in the twilight zone??
Here is the JS being used, which again, worked just fine yesterday:
function addInput(elm) {
if (elm.getElementsByTagName('input').length > 0) return;
var value = elm.innerHTML;
elm.innerHTML = '';
var id = elm.getAttribute('id');
if(value == "$0.00" || value == "0"){
value = "";
}
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('id', 'input:'+id);
input.setAttribute('value', value);
input.setAttribute('style', 'width:100px;');
input.setAttribute('onBlur', 'closeInput(this)');
elm.appendChild(input);
input.focus();
}
function closeInput(elm) {
var td = elm.parentNode;
var value = elm.value;
td.removeChild(elm);
if(value == ""){
td.innerHTML = "0";
}else{
$.ajax({
type: "GET",
url: "/pages/process.php",
data: "edit_data="+elm.id+"&value="+value,
dataType: 'json',
success: function(ret){
if(ret.success === true){
td.innerHTML = ret.value;
if(ret.math === true){
var targets = ret.targets;
for (i in targets){
for (key in targets[i]){
if(key == "key"){
var newid = targets[i][key];
}
if(key == "value"){
var newval = Math.round(targets[i][key]);
var elm = document.getElementById(newid);
elm.innerHTML = newval;
}
}
}
}
}else{
$("#error").html("ERROR: These fields can only accept numbers!!");
td.innerHTML = "ERROR";
}
}
});
}
}

Ok, so I think I figured it out in github from a diff. The only real change was in CSS. The input seems to be inheriting a recent change to the div that contains the table, that sets the scroll from right to left (direction:rtl;), this set the cursor all the way to the right, and for some reason, that creates this issue. If I set the input itself to direction:ltr; the problem is fixed.
So I wonder, why does direction:rtl ruin the input?

Related

SAP Java Script for % Increase Function

We have a Requirement, where Business always discuss to Increase or Decrease the Target sales value by some Integers, accordingly we have Input Enabled SAP WAD report which gives sale numbers. Moreover Now we have developed all of the Necessary Configuration to perform this %Increase Function but need this precise Javascript code optimization on my existing code.
Logic is, I Select the Required multiple row Cells and subsequently admit to press the %Increase Button, a Prompt will pop-up and enter the required integer Values and say OK.
So,for that Input provided integer value, back-end code should perform the %Increase calculation and insert back to respective cell.
x = (Input Value/100)X Cell Value;
Result = Cell value X x
Here I need your help fix the Javascript syntax correction.
The below Code performs 80% of my required function, but only need 20% of modification on that.
function sapbi_rig_plan_Per_Increase(content){
if ('undefined' == typeof(content) ) content = '';
if (content == null) content = '';
var info = sapbi_rig_plan_inf;
if (sapbi_rig_plan_isValidState(info) === false){
alert('Please select the range.');
return;
}
var content = prompt("Please enter value", " ");
if (isNumber(content ) == true){
var cell;
for(var cntSel = 0; cntSel<info.activeSel.length; cntSel++){
cell = document.getElementById(info.activeSel[cntSel][0]);
var fact = (content/100)*cell;
var content1 = fact+cell;
sapbi_rig_plan_setContent(cell, content1);
}
} else {
alert('Please Enter the Valid Qty only');
}
}
Please Note : I am Not java Developer, i am SAP BW-IP Developer

how to show text typed in a password input type otherwise hide the password

I want to allow users to see what they type in a password field. For instance, as soon as they type a letter in the field, they should see what was typed and the letter should change back to its default bullet.
This jQuery plugin does what you want: https://code.google.com/archive/p/dpassword/
The blog post contains the details.
Another option is to swap the type of the field using a checkbox ("Show password?"). Switching the type of the input element between text and password should achieve this. If that doesn't work, you need to create a new input element and copy the value.
Note on security: The password is hidden for a reason. Just to give you an idea of the possible attacks, here is the ones I know of:
If a smart phone is lying on the table next to your keyboard, then the vibrations caused by typing can be recorded and the keys you pressed can be calculated from that.
If the monitor is visible from outside the building, a good telescope can read you screen over quite a distance. If you wear glasses or there is a teapot, you can still read that at 30m.
So be aware that displaying a password does compromise security.
Related articles:
I Spy Your PC: Researchers Find New Ways to Steal Data
http://css-tricks.com/better-password-inputs-iphone-style/
Building uppon #SubhamBaranwal's answer that has the major drawback of losing the password field's value, you could do something like the following:
$(_e => {
const frm = $('#my-form');
const passField = frm.find('.pass');
const passCopy = $('<input type="hidden" />');
passCopy.prop('name', passField.prop('name'));
passField.prop('name', null);
passField.prop('type', 'text');
frm.append(passCopy);
let timer;
passField.on("keyup", function(e) {
if (timer) {
clearTimeout(timer);
timer = undefined;
}
timer = setTimeout(function() {
copyPass();
passField.val(createBullets(passField.val().length));
}, 200);
});
function createBullets(n) {
let bullets = "";
for (let i = 0; i < n; i++) {
bullets += "•";
}
return bullets;
}
function copyPass() {
const oPass = passCopy.val();
const nPass = passField.val();
if (nPass.length < oPass.length) {
passCopy.val(oPass.substr(0, nPass.length));
} else if (nPass.length > oPass.length) {
passCopy.val(oPass + nPass.substr(oPass.length));
}
}
/* for testing */
frm.append('<input type="submit" value="Check value" />');
frm.on('submit', e => {
e.preventDefault();
copyPass();
alert(passCopy.val() || "No Value !");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my-form">
<input class="pass" type="password" name="pass" />
</form>
However, this remains a simplistic implementation that will only support editing the password from the end (appending characters or backspaces). For a full implementation, you'd have to check and record where the current selection lies at each keyUp, and then modify the recorded value according to what you get after the input field was updated. Far more complicated
I think you want something like this JSFiddle
HTML Code -
<input class="pass" type="password" name="pass" />
JS Code -
function createBullets(n) {
var bullets = "";
for (var i = 0; i < n; i++) {
bullets += "•";
}
return bullets;
}
$(document).ready(function() {
var timer = "";
$(".pass").attr("type", "text").removeAttr("name");
$("body").on("keyup", ".pass", function(e) {
clearTimeout(timer);
timer = setTimeout(function() {
$(".pass").val(createBullets($(".pass").val().length));
}, 200);
});
});

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

Checking the text input before triggering event in JavaScript

I am trying to create a text-based adventure game. I managed to figure out how to make text output in html's textarea through simple onclick button, but now I am trying to do something new. I am having trouble with doing same thing but with input text where users can write anything in the box and then click on the button. Right now, I am trying to make this program to check the user input against some flag (in this case, I set my flag equal to 'pizza') before it does something. Unfortunately, my code doesn't work at all. I think I don't completely understand how the input is being passed around in JavaScript's functions.
The JavaScript part:
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
if (fileName == "pizza") {
var obj=document.getElementById(test);
obj.value="is this showing up in the textarea???";
}
else {obj.value="wrong password!"; }
}
The html part:
<input name="filename" id="filename" type="text">
<a id="record_button" onclick="record('textarea1');" href="javascript:void(0);" title="Record">Perform Action</a>
<textarea wrap="virtual" cols="73" rows="10" id="textarea1"></textarea>
The problem is this block with your else statement, obj isn't declared. Because you have obj defined in the if statement above it is exclusive to that scope. Just define obj right above the if block.
--
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
var obj=document.getElementById(test);
if (fileName == "pizza") {
obj.value="is this showing up in the textarea???";
}
else {
obj.value="wrong password!";
}
}
Add an event listener using JS:
document.getElementById('record_button').onclick=function(){
record('textarea1');
}
Also, there were a couple things wrong with your function. Here it is with corrections:
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
var obj = document.getElementById(test);
if (fileName == "pizza") {
obj.value = "is this showing up in the textarea???";
}
else {
obj.value = "wrong password!";
}
}
You were using document.getElementByID on the second line, which is incorrect capitalisation
You were only defining obj conditionally, so the else clause always threw an exception.
Here is a demonstration: http://jsfiddle.net/uQpp7/1/

How to prevent submitting the HTML form's input field value if it empty

I have HTML form with input fields. Some of inputs can be empty, i.e. the value is "".
<input name="commentary" value="">
Just now, when commentary field is not set, it appears in submit url like: &commentary=
How I can remove empty inputs from the submit url, so when the commentary input is empty it would not be passed at all.
Thank you very much.
Update
Thanks to minitech answer, I could resolve it. JavaScript code is below:
$('#my-form-id').submit(function() {
var commentary = $('#commentary').val();
if (commentary === undefined || commentary === "") {
$('#commentary').attr('name', 'empty_commentary');
} else {
$('#commentary').attr('name', 'commentary');
}
});
The only reason I have prefixed field name with "empty_" is that IE passes empty name in URL anyway.
This can only be done through JavaScript, as far as I know, so if you rely on this functionality you need to restructure. The idea, anyway, is to remove the name attribute from inputs you don’t want included:
jQuery:
$('#my-form-id').submit(function () {
$(this)
.find('input[name]')
.filter(function () {
return !this.value;
})
.prop('name', '');
});
No jQuery:
var myForm = document.getElementById('my-form-id');
myForm.addEventListener('submit', function () {
var allInputs = myForm.getElementsByTagName('input');
for (var i = 0; i < allInputs.length; i++) {
var input = allInputs[i];
if (input.name && !input.value) {
input.name = '';
}
}
});
You might also want to reset the form afterwards, if you use a listener and cancel.
I prefer not to alter the input elements (changing their names, or flagging them as disabled and so), because if you go back you could get a broken form.
Here is my solution instead, which relies on FormData:
window.addEventListener('load', function() {
let forms = document.getElementsByClassName('skipEmptyFields');
for (let form of forms) {
form.addEventListener('formdata', function(event) {
let formData = event.formData;
for (let [name, value] of Array.from(formData.entries())) {
if (value === '') formData.delete(name);
}
});
}
});
You probably don't want to match radio buttons. And if the form contains select's, you'll need to match them too.
With jQuery, you might use something like this:
$('#form-id').submit(function() {
$(this).find('input[type!="radio"][value=""],select:not(:has(option:selected[value!=""]))').attr('name', '');
});
Instead of using a submit-type input, use a button-type input for form submission. The JavaScript handler for the button-type input should call form's submit() method after checking that commentary is non-empty. You should also alert the user to their mistake (better with a red text on the page rather than the pop-up produced by alert()).
Remember that you should not rely solely on client-side input validation, though since it is always possible to send the form from a modified page or directly in HTTP.
Thankyou #Ryan
This is my full solution for this.
I use Jersey and #BeanParam and this fixes the problem of "" & null inputs
$('#submitForm').click(function() {
var url = "webapi/?";
var myForm = document.getElementById('myFormId');
var allInputs = myForm.getElementsByTagName('input');
for (var i = 0; i < allInputs.length; i++) {
var input = allInputs[i];
if (input.value != "" && input.name != "submitForm") {
url += input.name +'='+input.value+'&';
}
}
console.log(url);
$.ajax({
method : "GET",
url : url,
data : {
// data : "json",
// method: "GET"
},
success : function(data) {
console.log("Responce body from Server: \n" + JSON.stringify(data));
$("#responce").html("");
$("#responce").html(JSON.stringify(data));
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log('Error: ' + errorThrown);
}
});
});

Categories

Resources