Disable submit button until textarea ihas more than 100 chars - php

How can I disable the submit button until the chars of a textarea are more than 100 chars?
This is a code used to check if the user has selected to upload an image. Please inform me how should I name my textarea and guide me through the installation of it.
$(function() {
$('form').submit(function() {
if(!$("form input[type=file]").val()) {
alert('You must select a file!');
return false;
}
});
});

First of, make the submit button disabled, eg.
<input type="submit" disabled="disabled" id="submitid" />
Next you should write a function that will count the length of the textarea while the user is writing, this could be done by using the keyup function in jQuery or onkeyup in plain Javascript.
Example in jQuery:
$("#textareaid").keyup(function () {
if((this).val().length > 100) {
$("#submitid").removeAttr('disabled');
} else {
$("#submitid").attr("disabled", "disabled");
}
});
Note: code not tested.
SetInterval approach:
setInterval(function () {
if($("#textareaId").val().length > 100) {
$("#submitid").removeAttr("disabled");
} else {
$("#submitid").attr("disabled", "disabled");
}
}, 500); //Runs every 0.5s
Full size example:
<form>
<textarea id="textareaId"></textarea>
<input type="submit" id="submitId" disabled="disabled" />
</form>
<script type="text/javascript">
setInterval(function () {
if($("#textareaId").val().length > 100) {
$("#submitId").removeAttr("disabled");
} else {
$("#submitId").attr("disabled", "disabled");
}
}, 500); //Runs every 0.5s
</script>

You can either update the status of the submit button every time the data within the text area is changed, however this can be problematic as each browser has different events for textareas (in javascript)
A common way to do it is by setting an interval to check the submit box, then based on that decide the boolean value for the button. For instance
window.setInterval(function(){ $('#submitBtn').disabled = $("#textArea").val().length < 100 }, 100);
(Code not tested)

Users much prefer it if the number of characters in textarea is validated on submit. If it's less than 100, cancel the submit and give the user an error message saying why. Presumably there's a hint on the page so the user should know of the 100 character criterion and how many characters they've entered.
If you really want the button disabled, then disable it using script when the page loads. Use a key-up listener to count the characters in the textarea and enable the submit button if there's more than 100. You may need to listed to other events too so if the user changes the text by dragging or paste, then the submit button's disabled property is updated appropriately.

Building on Minitech's rather terse answer:
$(function() {
$('form').submit(function() {
if(!$("form input[type=file]").val()) {
alert('You must select a file!');
return false;
}
if($("#theTextArea").val().length <= 100) {
alert("You must enter more than 100 characters!");
return false;
}
});
});
Just replace theTextArea with the id of the specific textarea you want to test

Related

Bootstrap alert won't close after initial appearance

This is a very difficult problem to explain and demo, basically I am using a mixture of PHP, Smarty, Ajax and Bootstrap.
I have a smarty template with an Ajax form in it (this works), a PHP backend which adds the form details into a database (this also works), on success or failure an alert is shown, this alert is from the Bootstrap CSS, it is written to the page as follows.
$('form').append('<div class="alert alert-success alert-dismissible" role="alert">' + data.message + '×</div>');
The alert does display in the page, and the alert does close! However, for example if I or the user should want to use the form again for example, to say add another record to the database, the alert does show, but this time it never closes! So if I add another 10 records and click the submit button after each one as normal I have 10 alert boxes under the form that never close.
<script type="text/javascript">
window.setTimeout(function() {
$(".alert").fadeTo(1000, 0).slideUp(1000, function() {
$(this).hide();
});
}, 5000);
</script>
Does anyone have an idea as to what I could do instead that would work perhaps?
The below code closes the alert, but there is some inconsistency as to when the alert closes.
$(document).ready(function() {
$('form').submit(function(event) {
// snip
var alertTimer1 = window.setInterval(function() {
if (typeof alertTimer2 === 'undefined') {
var alertTimer2 = window.setTimeout(function() {
$('#alert').find('.alert').fadeTo(1000, 0).slideUp(1000, function() {
$(this).remove();
window.clearInterval(alertTimer1);
window.clearTimeout(alertTimer2);
});
}, 5000);
}
}, 100);
}
}
setTimeout function only execute once where setInterval checks on a regular time interval. For example: https://codepen.io/anon/pen/VGPYXB
The better solution could be when you adding alert message set setTimeout function after adding message or use delay function like this https://codepen.io/anon/pen/XPpJGe.
Initializing alert with $('.alert').alert()
Close it with $('.alert').alert('close') or $('.alert').alert('dispose')
Add the code lines within setTimeout() to delay event like so:
setTimeout(() => {
$('.alert').alert('close')
}, 10000)
Bootstrap 3.3 Documentation - Alerts
Bootstrap 4.0 Documentation - Alerts
use bootstrap's alert class. It will help you close the alert box elegantly.

Check if form fields have values on page load and if so, show labels?

I have a form where small labels are displayed above each field, once the user adds a value to that field.
This for is sometimes loaded with some of the fields being pre-populated.
How would i check on page load if any of the form fields have a value and if so, have the label visible?
Here's my current code for displaying labels once a field has a value:
$('.form-control').blur(function() {
if( $(this).val() ) {
$(this).prev().show();
}
});
on page load try this:
$('.form-control').each(function() {
if( $(this).val() ) {
$(this).prev().show();
}
});
$(document).ready(function(){
$('.form-control').each(function(){
if($(this).val() != ''){
$(this).prev().show();
}
});
});
On document ready, for each .form-control, if the input's value is not blank, do whatever code you would to show the label.
Using focusout Event wouldn't be much of an overkill, would it?
<script type="text/javascript">
(function ($) {
$(document).ready(function (e) {
// ALTHOUGH BLUR IS OK, ONE COULD SIMPLY BIND THE .form-control CLASSES TO THE focusout EVENT
// THIS ENSURES THAT THERE IS A HIGHER LIKELIHOOD THAT THE FIELD IN QUESTION ONCE HAD FOCUS
// WHICH MAY IMPLY THAT THE USER ALSO INTERACTED WITH THE FIELD IN SOME WAY...
$('.form-control').each(function(elem){
var objElem = $(this);
objElem.focusout(function(evt) {
if ($(this).val()) {
// NOW, YOU SHOULD KNOW WHICH METHOD TO USE TO TRAVERSE THE DOM
// AND GET AT THE LABEL....
// IN YOUR CASE IT SEEMS TO BE THE PREVIOUS ELEMENT BEFORE THE FORM-FIELD.
$(this).prev().show();
}
});
});
});
})(jQuery);
</script>

In PHP how can I detect when a user is deleting text from an input text field

<form action="" method="POST">
<input type="text" name="phonenumber" value="" />
<form>
If there is something written in the input text field and the user start to delete the string meaning the last letter of the string I want to do something.
So something like this:
if(user deletes last letter of isset($_POST['phonenumber'])){
//do something
}
I tried to use strlen() with -1 but did not seem to work. Anyone have any ideas?
Thank you!
You should use javascript to do something when user is deleting char.
One way is to listen to 'keyup' event of the text input. E.g.:
<script>
$(":text[name=phonenumber]").on('keyup', function(event){
if (event.keyCode == 8){ // means BACKSPACE pressed
// do something
}
});
</script>
you can get it by using javascript. on every keyup you have to count the textbox value by id if it is decreasing from the max count means user is deleting some text..
you should use javascript with event keyup ,
jQuery(function($) {
$('input[name=phonenumber]').on('keyup', function(e) {
if(e.keyCode == 46)
{
$.ajax({
type: 'POST',
url : 'url',
data :{'phonenumber': $('input[name=phonenumber]').val()},});
}
});
});

Javascript duplicate ids

Hello guys J have problem at Javascript. This is the code,
function reply_click(clicked_id) {
var la = <? php echo json_encode($logOptions_id); ?> ;
var mood = clicked_id;
$.post('msg.php', {
myne: la,
mood: mood
}, function (data) {
$('#nov').html(data);
});
$('#postDiv').on('keydown', '#textarea', function (e) {
if ((e.which == 13) && !event.shiftKey) {
var textarea = $("#textarea").val();
$.post('pst.php', {
mibe: la,
voot: mood,
pst: textarea
}, function (data) {
var textarea = $("#textarea").val('');
});
}
});
}
The problem is when I clicked on item I get clicked_id, after post message, its ok, but then once again I clicking the item, I get second id, and after post enter button it post in to database difference id from first item and second, seems duplicating values, how many times I click on different items , getting different ids and this problem is spamming my DB.
Every time you click the button, you add another keydown binding to #textarea. So if you click the button 5 times, then when you press Enter the keydown binding will be run 5 times.
You should move $('#postDiv').on('keydown', '#textarea', ...) outside the function, and just do it once in the document ready handler.

2Cannot press return to submit form and run JS action

This has got to be easier than I'm making it. I ahve a form that has an onclick action, it runs js that submits the form value to another page. How do I allow users to press return to perform the same action? I've tried some onkeypress stuff, but nothing has worked. Below is the form, and the js being run.
Thanks!
**updated code to reflect more of what I am trying to do..
<script type="text/javascript">
function getQueryValue(name) {
var match = (new RegExp('[?&;]' + name + '=([^&;#]*)')).exec(document.URL);
return match ? unescape(match[1]) : null;
}
var ext = "&ext="+getQueryValue('ext');
</script>
<script src="prototype.js"></script>
<script type="text/javascript">
function checkSubmit(e)
{
if(e && e.keyCode == 13) // if key is enter
{
doSubmit(); // call your submit function
}
}
</script>
</head>
<body>
<div id="dialNumber_form">
<form id="dialer" style="margin-bottom:0;">
<input id="numberBox" name="outnumber" onKeyUp="checkSubmit(event)" type="text">
<input id="submitButton" onsubmit="dosubmit()" type="button"/>
</form>
<div class="clear"></div>
</div>
<div id="success">
</div>
<script type="text/javascript">
function dosubmit( ) {
var par = $('dialer').serialize();
var url = par + ext;
new Ajax.Updater('success', 'dial.php', { method: 'post' , parameters: url , evalScripts: true } );
$('dialer').reset();
}
</script>
</body>
dial.php is taking the number you enter in the field, checking that it's valid, and sending it to our PBX to be dialed. This works, assuming you click the submit button. If you press return (even with the updated code, as recommended below), the page refreshes, and the contents of the outnumber box are posted as GET URL variable, rather than being sent to the dosubmit action. When the form works, you see it stay as it was originally built (dialout.htm?ext={extension number})
Thanks for all the responses. Let me try some of your suggestions, and I'll get back to you.
Not sure I'm clear in what I need to accomplish. This entire thing is being run in an iframe that is passed URL variables. I have no control over that piece, so I need to work with what I've got. When a user opens it, the URL would look something like .../dialout.htm?ext=1234. The extension is used, along with the number entered into the outnumber box, to place a call (system dials extension first, then outnumber). They should be passed to dial.php for processing, and if everything is good, a success response is sent back with the results (and the call is made). This works great if the dial button is clicked. The page does not refresh, and after a short delay, the success box pops up and a call is placed. If enter is pressed, the form refreshes, and the URL changes to .../dialout.htm?outnumber=<number>. I want enter to do what clicking the dial button does. Nothing i've tried here really works for that (unless I'm just really slow..). Any ideas?
You should make your submit button <input type="submit" id="submitButton" etc> then attach an onsubmit handler. jQuery:
$("#dialer").submit(function() {
var result = doMyStuff();
if (result > 10) {
return false; // prevent the submit
}
else {
return true; // allow the submit to happen
}
});
See the jQuery .submit() docs.
Returning false prevents the submit from occurring, true allows it. (I normally wouldn't put a "return false else return true" (return (result<=10);) but wanted to make the true/false sumbit control explicit)
When using AJAX to do the submit you'd want to return false so the normal submit is suppressed.
Update:
Returning false to stop default event processing is, these days, mostly deprecated. Using preventDefault() is generally preferred. This would change my example to be:
$("#dialer").submit(function(event) {
var result = doMyStuff();
if (result > 10) {
event.preventDefault(); // prevent the form submit
}
});
The keyDown / keyUp listener should be on the input not the submit button
<input id="numberBox" name="outnumber" onKeyUp="checkSubmit(event)" type="text">
function checkSubmit(e)
{
if(e && e.keyCode == 13) // if key is enter
{
doSubmit(); // call your submit function
}
}
Working example : http://jsfiddle.net/sVnMy/
This will listen to key presses on the input field and when the enter key is pressed it will submit the form

Categories