Setting A Limit On Input Field Creation? - javascript

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)

Related

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.

How can I auto refresh my search results using a marker?

I will post the code here, but basically I have a check box and every time I search I want to refresh the search area when i check and uncheck the marker. How can I go about to do this..
<script type="text/javascript">
jQuery(document).ready(function ($) {
jQuery('#allProgram').change(function () {
var elemnt
jQuery('form#AdvancedSearch').find('#allProgram').get(0);
if (jQuery(this).prop('checked')) {
jQuery(elemnt).val('
}
else {
jQuery(elemnt).val('False');
}
});
Man, I wrote a little code to solve your problem. You can test in this URL: http://jsfiddle.net/xxfn1xpx/
HTML:
<input type="text" id="search">
JavaScript:
var checkbox = $('input[name="languages"]');
var search = $('#search');
checkbox.on('change', function() {
result = [];
checkbox.each(function() {
if($(this).is(':checked')) { result.push($(this).val()); }
});
search.val(result.join(' '));
});
I hope I have helped you. Let me know if it help you ;)

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)

Asking user confirmation before redirect to a clicked link

I have a long kind wizard form, like a survey in my site. I want to write a jQuery Function so that when the user click accidentally any link on the page ( except preview and next buttons of the wizard ), it is asked first: are you sure you want to proceed? then it is redirected to the link he clicked, if he click cancel, nothing happens..
So far What i have done is to each link of the page except (next & previw) i have added a class link_ridirect so i can grab all the anchor links. and stop redirecting.
jQuery function is as follow!
<script type="text/javascript">
<!-- HERE IS THE SEARCH FILTER -->
//<![CDATA[
var GLOBAL_NAMESPACE = {};
$(document).ready(function(){
GLOBAL_NAMESPACE.value_changed = true;
});
$(document).ready(function () {
$('.link_redirect').bind('click',function (e) {
e.preventDefault();
if (GLOBAL_NAMESPACE.value_changed){
var res = confirm('you have unsaved changes. Do you want to continue?');
if(res){
window.location.href = $(this).attr('href');
}else{
console.log('stay on same page...');
}
}
});
});
//]]>
</script>
So what i want to do is how can i declare a Global variable to keep track of all field state. So if a field changes, to make it true and call the prevent function.
How about doing this:
$('a').click(function(){return confirm("are you sure?");});
Place it at the bottom of your html, or in the onload of your page, or in the document ready as you suggested in your OP.
edit
If you only want to do this if your variable changesDetected is true, then do it like this:
$('a').click(function(){return !changesDetected || confirm("are you sure?");});
It looks like you have code to interrupt default A-tag clicks already, so the crux of this is to detect when a field has changed such that you want to ask if they want to save before navigating away ?
Here's a JSFiddle Detect Field Changes :
It adds an onchange event to all editable fields whcih sets the global stae to true if something changed.
If the user enters a field then exits without changing, no change is detected.
function setup() {
// bind the change event to all editable fields. Runs on load(or doc ready)
$("input,select").bind("change",function(e) {
GLOBAL_NAMESPACE.value_changed = true;
});
};
you need to use beforeunload event. This event handled when you go out from page.
$(this).on("beforeunload", function () {
return 'are you sure';
});
if you need, that event called not for preview button and next, you can unbind this event handler.
$('#myPreviewButtonId').click(function()
{
console.log('preview clicked');
$(this).unbind("beforeunload");
});
(function($) {
$.fn.checkFileType = function(options) {
var defaults = {
allowedExtensions: [],
success: function() {},
error: function() {}
};
options = $.extend(defaults, options);
return this.each(function() {
$(this).on('change', function() {
var value = $(this).val(),
file = value.toLowerCase(),
extension = file.substring(file.lastIndexOf('.') + 1);
if ($.inArray(extension, options.allowedExtensions) == -1) {
options.error();
$(this).focus();
} else {
options.success();
}
});
});
};
})(jQuery);
$(function() {
$('#image').checkFileType({
allowedExtensions: ['jpg', 'jpeg'],
success: function() {
alert('Success');
},
error: function() {
alert('Error');
}
});
});
label {
display: block;
font-weight: bold;
margin-bottom: 0.5em;
}
<form action="#" method="post" enctype="multipart/form-data">
<div>
<label for="image">Upload image (JPEG only)</label>
<input type="file" name="image" id="image" />
</div>
</form>
You must prevent the default action on a if result of confirm function is false
$(document).ready(function () {
$(".deleteJob").on("click", function (e) {
if (!confirm("Are you Sure want to delete!")) {
e.preventDefault();
}
});
});

Separate 4 digits with : sign using regex

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/

Categories

Resources