Input unresolved quest - javascript

I have this code:
http://jsfiddle.net/4Qsa8/111/
This input is increasing size when you type a letter as you can see. But here is the issue, when I delete first letter from the end, the input does not decrease, it starts to decrease when I delete the second letter from the end. So the question is how to make input decrease in size on the deleting of the last letter, not on the second, before thanks.
-HTML
<div class="resizing-input">
* <input type="text" placeholder="placeholder"/>
<span style="display:none"></span>
</div>
-CSS
.resizing-input input, .resizing-input span {
font-size: 20px;
font-family: Sans-serif;
white-space: pre;
padding: 1px;
}
-JS
$(document).ready(function () {
var $inputs = $('.resizing-input');
// Resize based on text if text.length > 0
// Otherwise resize based on the placeholder
function resizeForText(text) {
var $this = $(this);
if (!text.trim()) {
text = $this.attr('placeholder').trim();
}
var $span = $this.parent().find('span');
$span.text(text);
var $inputSize = $span.width();
$this.css("width", $inputSize);
}
$inputs.find('input').keypress(function (e) {
if (e.which && e.charCode) {
var c = String.fromCharCode(e.keyCode | e.charCode);
var $this = $(this);
resizeForText.call($this, $this.val() + c);
}
});
// Backspace event only fires for keyup
$inputs.find('input').keydown(function (e) {
if (e.keyCode === 8 || e.keyCode === 46) {
resizeForText.call($(this), $(this).val());
}
});
$inputs.find('input').each(function () {
var $this = $(this);
resizeForText.call($this, $this.val())
});
});

Use keyup event instead of keydown event. because keydown event occurs before the input update its value. It will work.

Line 26 of the jsfiddle example, change the line:
$inputs.find('input').keydown(function (e) {
to:
$inputs.find('input').keyup(function (e) {

Related

When user enters text in textbox then append a prefix value

I have a textbox which needs to be filled with website URL. So when user places the cursor in the textbox then the textbox should prefill with "http://" (Not a placeholder).
If the user does not enter anything and moves to the next textbox then the textbox have empty value
If the user fills the textbox then the value is unchanged
I tried below Javascript code but did not work:
if (document.activeElement.id == 'input-textbox-id' && !document.activeElement.value) {
document.querySelector("#input-textbox-id").value="http://";
} else if (document.activeElement.id != 'input-textbox-id' && (!document.activeElement.value || document.activeElement.value == 'http://')) {
document.querySelector("#input-textbox-id").value="";
}
You can use the focus and blur events for this.
Assuming that the variable textBox contains the reference to your textBox element, you can use the following code:
let textBox = document.getElementById("a");
textBox.addEventListener("focus", function() {
if (!this.value) {
this.value += "http://";
}
});
textBox.addEventListener("blur", function() {
if (this.value == "http://") {
this.value = "";
}
});
<input type="text" id="a">
You will need to attach event listener by using addEventListener. Events you need: focus and focusout.
We add .http-prefill class for all inputs. We iterate over inputs array and attach event.
Please do not forget to remove eventListener when you are done eg. you unload the form.
To do so, just copy the code for adding listeners and replace addEventListener with removeEventListener.
inputs.forEach(function(input) {
input.removeEventListener('focus', onFocus);
input.removeEventListener('focusout', onFocusOut);
});
Example code:
var fillValue = 'http://';
var onFocus = function() {
this.value = fillValue;
}
var onFocusOut = function() {
if (this.value === fillValue) {
this.value = '';
}
}
var inputs = document.querySelectorAll('.http-prefill');
inputs.forEach(function(input) {
input.addEventListener('focus', onFocus);
input.addEventListener('focusout', onFocusOut);
});
.http-prefill {
width: 100%;
margin-bottom: 5px;
}
<input class="http-prefill" name="input-0" />
<input class="http-prefill" name="input-1" />
<input class="http-prefill" name="input-2" />
<input class="http-prefill" name="input-3" />
you can use some key events like onKeyDown and when keydown you can get hold of old value and append it with new value.
let keyPressed = true
function onKeyDown(event) {
if(keyPressed && event.keyCode !== 8)
{
keyPressed = false;
let oldvalue = document.getElementById('input-textbox-id').value;
document.getElementById('input-textbox-id').value = "http://"+oldvalue
}
if(!document.getElementById('input-textbox-id').value)
{
keyPressed = true;
}
}
here is working code. http://jsbin.com/zoxiwokepi/edit?html,output

A button should show/hide depending on whether or not there is value in input field

Right now the button shows when input is added to the input field, but if I remove the input the button doesn't hide.
My only idea for a solution is to divide the function into 2 seperate ones.
That is, one that adds the input to the input field on click, and then another functions that keeps track of input.val, and controls the hide/show effect of the button.
Would that be a better way of doing it?
$("#peopleInPopup").on('click', '.list-group-item', function() {
var peopleName = $(this).children("span").text();
var peopleID = $(this).children("span").attr("class");
var input = $("#friendsNames");
input.val(input.val() + peopleName + "");
if (input.val().length === 0) {
$("#checkButton").toggle(false);
console.log("button should NOT display");
} else {
console.log("button should display");
$("#checkButton").toggle(true);
}
$("#checkButton").click(function() {
var newParticipants = input.val();
socket.emit("addParticipantsToConversation", newParticipants);
$("#chatToInfo").append(", ", input.val());
$("#friendsNames").val("");
$(":mobile-pagecontainer").pagecontainer("change", $("#pagefour"), {
transition: "slidedown"
});
});
});
Just use show and hide from jQuery instead, perhaps? I assume you want this to happen as the input is changing, so I've thrown in keyup (could use onChange or alternatives).
Tweaking your code slightly...
$('input').on('keyup', function (event) {
let value = event.target.value;
if (value && value !== '' && value.length > 0) {
$('#myButton').show();
} else {
$('#myButton').hide();
}
})
With a markup...
<input id='input' />
<button id='myButton'>GO</button>
And some sort of base style...
#go {
display: none;
}
Do the trick?
I actually just found a solution to my problem. The code below makes it work:
$("#peopleInPopup").on('click', '.list-group-item', function(){
var peopleName = $(this).children("span").text();
var peopleID = $(this).children("span").attr("class");
var input = $("#friendsNames");
input.val(input.val() + peopleName + "");
$("#checkButton").toggle(true);
$("#friendsNames").on('input', function(event) {
if (this.value.length === 0) {
console.log("Works!");
$("#checkButton").toggle(false);
console.log("button should NOT display");
} else {
console.log("button should display");
$("#checkButton").toggle(true);
}
});
$("#checkButton").click(function(){
var newParticipants = input.val();
socket.emit("addParticipantsToConversation", newParticipants);
$("#chatToInfo").append(", ",input.val());
$("#friendsNames").val("");
$(":mobile-pagecontainer").pagecontainer("change", $("#pagefour"), { transition: "slidedown" });
});
});

tabindex issue with select2

I am having an issue with the taborder on my form whilst using select2.
I have an input form that I want the user to be able to tab through in order.
I have been able to order the text input fields but not select2 dropdownlists.
It appears the issue is with them having a default tabindex="-1", as below;
> <div id="s2id_ctl00_MainContent_ddlAreaKept" class="select2-container
> form-control">
> <a class="select2-choice" tabindex="-1" onclick="return false;" href="javascript:void(0)">
> <input id="s2id_autogen4" class="select2-focusser select2-offscreen" type="text" tabindex="0">
> <div class="select2-drop select2-display-none select2-with-searchbox">
> </div>
> <select id="ctl00_MainContent_ddlAreaKept" class="form-control select2-offscreen" name="ctl00$MainContent$ddlAreaKept" tabindex="-1">
I have also written the following javascript to add tabIndex values to the fields but it isn't working how I'd like.
var tabOrder = 0;
document.getElementById("ctl00_MainContent_ddlAreaKept").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_ddlNCDYears").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtVehicleValue").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtAge").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtForename").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtSurname").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtEmail").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtPhoneNumber").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_btnGetQuote").tabIndex = tabOrder++;
The dropdownlists don't get tabbed into, it skips them and goes through the textboxes as it should.
Any help much appreciated!
SOLVED : I tried:
var tabOrder = 1;
and this has solved the issue. I don't exactly know why or how :|
There is a solution in github, you can create a js file and then you include it under the call of select2, inside this new file you must paste this:
jQuery(document).ready(function($) {
var docBody = $(document.body);
var shiftPressed = false;
var clickedOutside = false;
//var keyPressed = 0;
docBody.on('keydown', function(e) {
var keyCaptured = (e.keyCode ? e.keyCode : e.which);
//shiftPressed = keyCaptured == 16 ? true : false;
if (keyCaptured == 16) { shiftPressed = true; }
});
docBody.on('keyup', function(e) {
var keyCaptured = (e.keyCode ? e.keyCode : e.which);
//shiftPressed = keyCaptured == 16 ? true : false;
if (keyCaptured == 16) { shiftPressed = false; }
});
docBody.on('mousedown', function(e){
// remove other focused references
clickedOutside = false;
// record focus
if ($(e.target).is('[class*="select2"]')!=true) {
clickedOutside = true;
}
});
docBody.on('select2:opening', function(e) {
// this element has focus, remove other flags
clickedOutside = false;
// flag this Select2 as open
$(e.target).attr('data-s2open', 1);
});
docBody.on('select2:closing', function(e) {
// remove flag as Select2 is now closed
$(e.target).removeAttr('data-s2open');
});
docBody.on('select2:close', function(e) {
var elSelect = $(e.target);
elSelect.removeAttr('data-s2open');
var currentForm = elSelect.closest('form');
var othersOpen = currentForm.has('[data-s2open]').length;
if (othersOpen == 0 && clickedOutside==false) {
/* Find all inputs on the current form that would normally not be focus`able:
* - includes hidden <select> elements whose parents are visible (Select2)
* - EXCLUDES hidden <input>, hidden <button>, and hidden <textarea> elements
* - EXCLUDES disabled inputs
* - EXCLUDES read-only inputs
*/
var inputs = currentForm.find(':input:enabled:not([readonly], input:hidden, button:hidden, textarea:hidden)')
.not(function () { // do not include inputs with hidden parents
return $(this).parent().is(':hidden');
});
var elFocus = null;
$.each(inputs, function (index) {
var elInput = $(this);
if (elInput.attr('id') == elSelect.attr('id')) {
if ( shiftPressed) { // Shift+Tab
elFocus = inputs.eq(index - 1);
} else {
elFocus = inputs.eq(index + 1);
}
return false;
}
});
if (elFocus !== null) {
// automatically move focus to the next field on the form
var isSelect2 = elFocus.siblings('.select2').length > 0;
if (isSelect2) {
elFocus.select2('open');
} else {
elFocus.focus();
}
}
}
});
docBody.on('focus', '.select2', function(e) {
var elSelect = $(this).siblings('select');
if (elSelect.is('[disabled]')==false && elSelect.is('[data-s2open]')==false
&& $(this).has('.select2-selection--single').length>0) {
elSelect.attr('data-s2open', 1);
elSelect.select2('open');
}
});
});
This work for me, if you want to know more: https://github.com/peledies/select2-tab-fix
© 2017 GitHub, Inc.
Terms
Privacy
Security
Status
Help
Contact GitHub
API
Training
Shop
Blog
About
focus it after select it!
$('.select2').on('select2:select', function (e) {
$(this).focus();
});
for your code replace .select2-offscreen with my .select2.
S F My English!
You could bind load event and trigger it on first time loaded
As you can see , the tabindex of the select control will become "3" instead of "-1"
$(document).ready(function() {
var $select2 = $("#tab2");
$select2.data('placeholder', 'Please Chhose').select2({
formatNoMatches: function (term) {
return 'No Match "' + term + '" Item';
},
allowClear: true
}).on("load", function(e) {
$(this).prop('tabindex',3);
}).trigger('load');
$("#tab1").prop('tabindex',4);
$("#tab3").prop('tabindex',2);
$("#tab4").prop('tabindex',1);
}
JSBIN
This code worked for me. I focus the first element in the modal:
$('#modalId').on('shown.bs.modal', function () {
$('#FirstElement').focus()
});
TabIndex Issue might happen after the form reset.
As per the documentation You may clear all current selections in a Select2 control by setting the value of the control to null:
$(selector).val(null).trigger("change");

jquery / Regex, stop event bubbling

I have a form validation using jquery /regex:
$(document).ready(function () {
$('.keyup-numeric').keyup(function () {
$('span.error-keyup-1').hide();
var inputVal = $(this).val();
var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
if (!numericReg.test(inputVal)) {
$(this).after('<span class="tiny warning_bubble">Numeric characters only.</span>');
}
});
});
How can I stop the warning_bubble span from piling up?
Fiddle: http://jsfiddle.net/M2Ns5/
THanks,
You could have the warning created with the rest of the html, and set its style to be initially hidden and then just show, or hide the warning when needed
HTML
<label>Phone Number:
<input type="tel" class="keyup-numeric" placeholder="(XXX) XXX-XXXX"/>
<span class="tiny warning_bubble">Numeric characters only.</span>
</label>
CSS
.warning_bubble {
color:#d2232a;
-webkit-border-radius: 12px;
border-radius: 12px;
background-color:#ffdd97;
padding:5px;
width:100%;
display:none;
}
JS
$(document).ready(function () {
$('.keyup-numeric').keyup(function () {
$('span.error-keyup-1').hide();
var inputVal = $(this).val();
var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
if (!numericReg.test(inputVal)) {
$(this).parent().find(".warning_bubble").show();
} else {
$(this).parent().find(".warning_bubble").hide();
}
});
});
JSFiddle Demo
Check if the next element has the warning_bubble class & then add it the span.
$(document).ready(function () {
$('.keyup-numeric').keyup(function () {
$('span.error-keyup-1').hide();
var inputVal = $(this).val();
var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
if (!numericReg.test(inputVal)) {
if (!$(this).next().hasClass('warning_bubble')) {
$(this).after('<span class="tiny warning_bubble">Numeric characters only.</span>');
}
} else {
$(this).parent().find(".warning_bubble").hide();
}
});
});
jsFiddleDemo here
The fewest changes to your code would be to add a container inside the label, after the input:
<span class="warning-container"></span>
And change your after line to a empty/append:
$(this).siblings('.warning-container').empty().append('<span class="tiny warning_bubble">Numeric characters only.</span>');
Note: empty().append() is a faster way of doing html(). Also be aware that while this is the fewest changes to your original code, there are many ways to make it more efficient and more robust.
http://jsfiddle.net/MrPolywhirl/PkPU9/
$(document).ready(function () {
(function(tel) {
// Validation expression
var numericReg = /^\d*\d(|.\d*\d|,\d*\d)?$/;
// Create bubble
var bubble = $('<span class="tiny warning_bubble" style="display:none">Numeric characters only.</span>');
$(tel).after(bubble); // Add and hide bubble to the input
// Add key listener to the text input
$(tel).keyup(function () {
var inputVal = $(this).val();
// Toggle the bubble using jquery show/hide
bubble[inputVal && !numericReg.test(inputVal) ? 'show' : 'hide']();
});
})('.keyup-numeric');
});

Disabling BACKSPACE in chrome

I have an input field for mobile numbers and i want that inside that input field "+91" should be visible to the user all the time.. means he can not erase it.
So i planned to disable BACKSPACE and DELETE button when the value of INPUT FIELD is equal to +91
The startegy is working fine for me in FIREFOX but its all screwed up in CHROME.
I googled a lot but couldnt find any successfull code for Disabling Backspace in CHROME. :(
Here is my code for FIREFOX
<script language="JavaScript" type="text/javascript">
document.onkeypress = function(e) // FireFox/Others
{
var t=e.target.id;
var kc=e.keyCode;
if ((kc == 8 || kc == 46) && t == "phonen" && document.getElementById(t).value=="+91")
{ e.preventDefault();
return false;}
else {
return true
}
}
function sett(e)
{e.value="+91";}
</script>
Can anyone suggest me how can i do the same in CHROME???
As I wrote in a comment... Don't even bother with this kind of approach. Just fake it. Here's a simple way (though you might want to adjust fonts, spacing, etc.):
html:
<div class="prefix-wrapper">
<span class="prefix">+91</span>
<input type="text" value="">
</div>
css:
.prefix-wrapper {
position: relative;
}
.prefix-wrapper .prefix {
position: absolute;
z-index: 2;
top: 3px;
left: 5px;
color: #999;
}
input {
padding-left: 30px;
}
demo: http://jsbin.com/elatot/1/
User still can click with a mouse or move the cursor and edit +91 strings.
I would suggest that you bind .keyup and .change handlers to your input and check then if it contains your prefix(note that jQuery would be it much easier). Like this:
$('#your_input_id').on('keyup change', function() {
if ( $(this).val().indexof('+91') != 0) $(this).val('+91');
});
A solution not using jQuery would be to hook up to the change/keyup events directly:
var checkPhone = function (e) {
if (e.target.value.indexOf('+91') != 0) {
e.target.value = '+91';
}
}
var phoneElement = document.getElementById('phonen');
phoneElement.onchange = checkPhone;
phoneElement.onkeyup = checkPhone;
Try this with jQuery:
// HTML Code
<input type="text" name="phone" id="phone" class='phone' placeholder='+918888888888' value='' maxlength='13' />
// jQuery code
$(document).keydown(function (e) {
var l = $('.phone').val().length;
var elid = $(document.activeElement).hasClass('phone');
if (e.keyCode === 8 && elid && l == 3) {
return false;
} else {
return true;
}
});
Fiddle DEMO

Categories

Resources