Separate 4 digits with : sign using regex - javascript

I am working on custom timepicker. What I want to do is: If user enters 1234 it will be change to 12:34. Problem is nothing happens at all (I am not getting exception). Here is what I have so far:
// check time entry
(function ($) {
String.prototype.Timeset = function(){
return this.replace(/^\d{2}\:\d$/,"$1,");
}
$.fn.Time = function(){
return this.each(function(){
$(this).val($(this).val().Timeset());
})
}
})(jQuery);
HTML Markup:
<input id="txtTime" type="text" maxlength="4" onpaste="return false;" onchange="this.value = this.value.Timeset();" />
How can I achieve this? My regular expression may also be the root of this. Note that I don't want to use any external mask plugins as I have to apply hot-keys on this one.

Let's try this:
function formatTime(s) {
return s.replace(/\D/g, "").replace(/^(\d\d)(\d\d).*$/, "$1:$2");
}
(function ($) {
$.fn.timeInput = function() {
return $(this).change(function() {
$(this).val(formatTime($(this).val()))
});
}
})(jQuery);
http://jsfiddle.net/LAbFQ/

Related

e.preventDefault() behvaing differently

I have a very simple jQuery UI spinner as follows:
<input value="2" class="form-control ui-spinner-input" id="spinner" aria-valuemin="2" aria-valuemax="24" aria-valuenow="2" autocomplete="off" role="spinbutton" type="text">
Using jQuery I set the above text box readonly true/false. The readonly and value is set based on the checkbox a user selects and that function looks like
function checkBoxes() {
var $targetCheckBoxes = $("#BoxFailure,#InstallationFailure");
$targetCheckBoxes.change(function () {
var isChecked = this.checked;
var currentElement = this;
var $radioButton = $('.usage-failure-type-radio');
$targetCheckBoxes.filter(function () {
return this.id !== currentElement.id;
}).prop('disabled', isChecked);
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked);
$radioButton.first().prop('checked', isChecked);
$radioButton.not(':checked').toggle(!isChecked).parent('label').toggle(!isChecked);
$('.usage-before-failure > div > span.ui-spinner > a').toggle(!isChecked);
});
}
Now what I'm trying to achieve is when the #spinner input is readonly and if the user presses the back space I want to prevent the default behaviour e.g. do navigate away from the page. For this I thought I'd do the following:
$('.prevent-default').keydown(function (e) {
e.preventDefault();
});
Which works fine if the input has the class prevent-default on page load. However, if I add it in my checkBoxes function in the following line
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).toggleClass('prevent-default')
Then I press the backspace it ignores e.prevenDefault();
But if I do
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).keydown(function (e) { e.preventDefault(); });
Then it works absolutely fine.
Can someone tell me why this is happening please.
The reason I want to use a separate function with a class name is because I have various inputs which get set to read only based on different check/radio values.
Can someone tell me why this is happening please
This is because of the DOM parser and the timing when JavaScript is executed.
If you already have an element with a class prevent-default in your DOM before JS is executed, then the JavaScript will recognise and handle it correctly. If you instead add the class afterwards with JS, then you have to re-initialise the keydown-event again to make it work.
To re-initialise you will need something like this:
function checkBoxes() {
var $targetCheckBoxes = $("#BoxFailure,#InstallationFailure");
$targetCheckBoxes.change(function () {
...
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).toggleClass('prevent-default');
// assign new keydown events
handleKeyDown();
...
});
}
function handleKeyDown() {
// release all keydown events
$('#spinner').off( "keydown", "**" );
$('.prevent-default').keydown(function (e) {
e.preventDefault();
// do more stuff...
});
}

Highlight input text not working

Hello I would like the text inside an input element to highlight upon initial click. However my function does not seem to be working. I have researched the issue and seen that there are some issues with jquery 1.7 and below. I have adjusted it to account for this any it still does not work.
Any help would be great. Thanks!
HTML
<input type="text" value="hello"/>
JS
$scope.highlightText = function() {
$("input[type='text']").on("click", function() {
$(this).select();
});
https://plnkr.co/edit/b7TYAFQNkhjE6lpRSWTR?p=preview
You need to actually call your method at the end of controller, otherwise the event is not bound.
https://plnkr.co/edit/a0BlekB8qTGOmWS8asIx?p=preview
... other code ...
$scope.highlightText = function () {
$("input[type='text']").on("click", function () {
$(this).select();
var test = $(this).parent();
console.log(test);
});
$("textarea").on("click", function () {
$(this).select();
});
};
$scope.highlightText();
};
To select the text inside an input you would simply call this.select() from onclick like shown below
<input type="text" onclick="this.select()" value="hello"/>

Using the same jQuery functions but causing conflicts in HTML

Title - Sorry about the title, it was difficult for me to actually explain this.
So I recently finished working on a dynamic fields system using jQuery. This is all working great however I'm wanting to re-use the html for the system over and over again on the same page, this causes problems.
Problem
- When you have duplicates of the form on the same page, and you press 'Add Field' it will run the function and apply the functions to the other classes on the page. (See fiddle for example.)
When you just have one form on the DOM it works fine, but I'm wanting to alter the html slightly so I can use it for different scenarios on a page. I don't want to have separate jQuery files to do this because I don't think it's necessary. I was thinking maybe I could target it's parent containers instead of the class directly? Then I could recycle the same code maybe?
Any suggestions on this guys?
HTML:
<form action="javascript:void(0);" method="POST" autocomplete="off">
<button class="add">Add Field</button>
<div class='input_line'>
<input type="text" name="input_0" placeholder="Input1">
<input type="button" class="duplicate" value="duplicate">
<input type="button" class="remove" value="remove">
</div>
</form>
JQUERY:
$(document).ready(function () {
'use strict';
var input = 1,
blank_line = $('.input_line'),
removing = false;
$('.remove').hide();
$('.add').click(function () {
var newElement = blank_line.clone(true).hide();
$('form').append(newElement);
$(newElement).slideDown();
$('.remove').show();
});
$('form').on('click', '.duplicate', function () {
$(this).parent().clone().hide().insertAfter($(this).parent().after()).slideDown();
$('.input_line').last().before($('.add'));
$('.remove').show();
input = input + 1;
});
$('form').on('click', '.remove', function () {
if (removing) {
return;
} else {
if ($('.input_line').length <= 2) {
$('.remove').hide();
}
$(this).parent().slideUp(function () {
$(this).remove();
removing = false;
});
$('.input_line').last().before($('.add'));
input = input - 1;
}
removing = true;
});
});
Working fiddle - JSFiddle
Problem fiddle - JSFiddle
As you can see in the problem fiddle above, when you duplicate the form it start conflicting. I would like each form to work independently.
Any help would be greatly appreciated!
You need to use closest('form') to find the associated form. Also when looking up the other fields, you need to search within the context of the related form, http://jsfiddle.net/95vaaxsL/7/
function addLine($inputLine) {
var $form = $inputLine.closest('form');
var $newElement = $inputLine.clone(true).hide();
$newElement.insertAfter($inputLine);
$newElement.slideDown();
$form.find('.remove').show();
}
$(document).ready(function () {
'use strict';
$('.remove').hide();
$('.add').click(function () {
addLine($(this).closest('form').find('.input_line:last'));
});
$('form').on('click', '.duplicate', function () {
addLine($(this).closest('.input_line'));
});
$('form').on('click', '.remove', function () {
var $inputLine = $(this).closest('.input_line');
var $form = $inputLine.closest('form');
if ($form.find('.input_line').length < 3) {
$form.find('.remove').hide();
}
$inputLine.slideUp(function(){
$inputLine.remove();
});
});
});
Pulled out the function.

Two plugins in a textarea

I need to use two plug-ins in one element on my page. I've never needed to do this and tried as it is in the code below. Most did not work!
<script type="text/javascript">
$(document).ready(function()
{
var wbbOpt = {buttons: "bold,italic,underline,|,img,link,|,code,quote"}
// plugin one wysibb
$("#editor").wysibb(wbbOpt);
// plugin two hashtags
$("#editor").hashtags();
//the two plugin worked in textarea #editor
});
</script>
Can anyone help me? Thank you.
So you can't use them because each of them take control and wrap the textarea. Since the editor is the most complex of the two the best thing to do is to take the code of the hashtag and adapt it at your need.
So here's a working example, but if you want you can trigger the function I use to the change event (adding it) or some way else
<div id="higlighter" style="width;1217px;"></div>
<textarea id="editor"></textarea>
<br />
<input id="btn" type="button" value="HASH">
<br />
$(document).ready(function() {
var wbbOpt = {
buttons: "bold,italic,underline,|,img,link,|,code,quote"
};
$("#editor").wysibb(wbbOpt);
$('#btn').click(function () { report() });
});
function report() {
$("#hashtag").val($("#editor").htmlcode());
var str = $("#editor").htmlcode();
str = str.replace(/\n/g, '<br>');
if(!str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([a-zA-Z0-9]+)/g)) {
if(!str.match(/#([a-zA-Z0-9]+)#/g)) {
str = str.replace(/#([a-zA-Z0-9]+)/g,'<span class="hashtag2">#$1</span>');
}else{
str = str.replace(/#([a-zA-Z0-9]+)#([a-zA-Z0-9]+)/g,'<span class="hashtag2">#$1</span>');
}
}
$("#editor").htmlcode(str);
}
you can check a working code here on jsfiddle.
http://jsfiddle.net/4kj7d6mh/2/
You can type your text and use the editor, and when you want to higlight the hastag you click the button. If you want that to happen automatically you have to change this line:
$('#btn').click(function () { report() });
And attach the function to the keypress for example (experiment a bit)

Setting A Limit On Input Field Creation?

I haven't found nothing on this topic so I though I quickly ask here.
Anyway I am creating a feature which allow users to add new admins to there clan and to make it easier the user can add a new input field that is all working fine ;)
But what I want is to only allow the user to add a maxim of 5 admins at one time to save server resources as at the moment they can have as many as they want.
How could I archive this?
(The code is below)
<form>
<input type="text" />
</form>
<button id="addFields">Add another field
</button>
//JQUERY SIDE BELOW
$(function ($) {
$('body').on("click", '#addFields', function () {
$('form').append('<input type="text" />')
})
})(jQuery)
client side you can do in this way
$(function ($) {
$('body').on("click", '#addFields', function () {
if ($("form > input:text").length < 5) {
$('form').append('<input type="text" />');
}
else{
alert('can't add more admins');
}
});
})(jQuery);
but in this way you are blocking only to add maximum 5 admins at the same time.
in your server side you should do something like this (a more robust solution) (SQL)
SET #admins= (SELECT COUNT(IdUSerAdmin) FROM Users where IdAdmin= #YouAdminUser)
IF(#admins < 5)
BEGIN
INSERT INTO USERS ....
END
What #Vote to Close said is right, you'll need to stop this on both the server and client side. On the client side, you could do this:
$(function ($) {
var MAX_LIMIT = 5;
$('body').on("click", '#addFields', function () {
if ($("form > input[type='text']").length < MAX_LIMIT) {
$('form').append('<input type="text" />');
}
});
})(jQuery);
$(function ($) {
var totalFieldsAdded = 0;
var totalFieldsAllowed = 5;
$('body').on("click", '#addFields', function () {
if(totalFieldsAdded < totalFieldsAllowed){
$('form').append('<input type="text" />');
totalFieldsAdded++;
}
})
})(jQuery)

Categories

Resources