How to impose a required textbox in javascript - javascript

I have a problem with my chat.
Indeed, I have a text input with the required value.
When I click on Send, it returns empty instead of stopped sending...
Can you help me please ?
<script>
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
$.post("chat-post.php", {
text: clientmsg
});
$("#usermsg").attr('required', true);
loadLog;
return false;
});
</script>

you could validate the input string like this if(clientmsg.trim()) .Better add the required=true in your html code
<input type='text' required="true">
And use with trim() they will remove the unwanted space from string
<script>
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
if(clientmsg.trim()){
$.post("chat-post.php", {
text: clientmsg
});
loadLog;
}
return false;
});
</script>

Basically you need to add a condition before sending post request if the value of that message input is empty. Please check below :
<script>
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
// This is the additional condition
if(clientmsg != '' || clientmsg != null){
$.post("chat-post.php", {
text: clientmsg
});
}
else{
alert('Please enter the message!');
}
$("#usermsg").attr('required', true);
loadLog;
return false;
});
</script>

In order for the required attribute to work, you need to have the input inside a form.
<form>
<input required type="text" />
</form>
I think there is simply no need to set the required attribute every time you click the button. You only need to do it once, so why not simply add the required attribute in the html?
Even if you don't want to add it in the HTML, just add it once.
<script>
$("#usermsg").attr('required', true); // Add the attribute required to the input
// Do the AJAX function after you submit the form.
// Before submitting, it will have to be validated, so you don't even have to validate it in JS. Just native HTML5
$("form").submit(function() {
// do the rest here
}
</script>

Related

one of the two input fields is required

I have two input fields one is file the other is textarea
<input class="input_field" type="file" name="title" />
<textarea class="input_field" name="info"></textarea>
User has to either upload a file or type text. If the user leaves blank both of the inputs, it should say like "choose a file or type info" if he/she fills both, it is ok.
My JQuery:
$(function(){
$(".input_field").prop('required',true);
});
I have this code. How can we implement something like if else condition to make it required one of the fields?
See this fiddle https://jsfiddle.net/LEZ4r/652/
I modified your code to each all the elements with a class of input_field when the form is submitted.
$(function(){
$('form').submit(function (e) {
var failed = false;
$(".input_field").each(function() {
if (!$(this).val()) {
failed = true;
}
});
console.log(failed);
if (failed === true) {
e.preventDefault();
}
});
});
Based on your question, there are only two possible conditions:
if either one field or both fields are filled, user passes validation
if no fields are filled, user fails validation
This can be easily done by checking for the value of either input. As long as one is not empty, user passes the test. This if/else condition can be written as:
if($('input[type="file"].input_field').val() || $('textarea.input_field').val()) {
// Passed validation
} else {
// Failed validation
}
A simple pattern to check for errors is to create an error flag, which will be raised when one or more validation checks have failed. You evaluate this error flag at the end of the script before manual form submission:
$(function(){
$('form').on('submit', function(e) {
e.preventDefault();
// Perform validation
var error = false;
if($('input[type="file"].input_field').val() || $('textarea.input_field').val()) {
alert('Passed validation');
error = false;
} else {
alert('Please fill up one field');
error = true;
}
// Check error flag before submission
if(!error) $(this)[0].submit();
});
});
See working fiddle here: http://jsfiddle.net/teddyrised/LEZ4r/653/
Check inside your form If atleast one is done break the loop and go for submit else return false
$(function(){
$('form').on('submit',function(e){
var doneOnce = false;
$(this).children().each(function(){
if($(this).val()){
doneOnce = true;
return false;//return false will break the .each loop
}
});
alert(doneOnce)
if(!doneOnce){
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="input_field" type="file" name="title" />
<textarea class="input_field" name="info"></textarea>
<input type=submit />
</form>
You can write codes in Javascript to validate form. You have to make an onclick or onsubmit function, and the function will check whether any of the input field is empty. You can write something like the following code:
<script>
function validateForm() {
var fstname=document.getElementById("fname").value;
var lstname=document.getElementById("lname").value;
if(fstname===null || fstname===""){
alert("Plese choose a file.");
return false;
}
else if(lstname===null || lstname===""){
alert("Plese type file info.");
return false;
}
else{
return confirm("Your file: "+fstname+" and it of type "+lstname);
}
}
<body>
<form action="text.php" name="myForm" onsubmit="return validateForm()">
First Name: <input type="file" id="fname" name="FirstName">
Last Name: <input type=text" id="lname" name="LastName"><br/>
<input type="submit" value="Submit">
<form>
</body>

Check if textbox contains text, if it does then send

I have this email form, with "Sender, "Subject" and "Message".
But i haven't linked it to make sure they have written something, so if someone press the "Send" button without typing anyting, i get a blank email. So i want it to abort the email sending if the textbox is empty, and send it if it contains any text.
code for the send button:
<input type="submit" name="submit" value="Submit" class="submit-button" />
ID for the textbox is: textbox_text
You can use jquery to validate the form like this-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
Sender
<input type="text">
<br/>Subject
<input type="text">
<br/>Message
<input type="text" id="txtMessage">
<br/>
<input type="submit" value="Send" name="btnSend">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("input[name=btnSend]").click(function() {
var msg = $("#txtMessage").val();
if (msg == "") {
alert("Please enter the message");
return false;
}
});
});
</script>
Java Script function
<script type="text/javascript">
function IsEmpty()
{
if(document.forms['frm'].textbox_text.value == "")
{
alert('Message body is empty');
return false;
}
return true;
}
</script>
HTML
<form name="frm">
<input type="submit" name="submit" onclick="return IsEmpty();" value="Submit" class="submit-button" />
</form>
EDIT Check textbox2 in if condition
if(document.forms['frm'].textbox1.value == "" && document.forms['frm'].textbox2.value == "")
I dont know this is your exact answer but it will helps you to validate:
$('#checkSubmit').click(function(){
var chec=$("#textContent").val();
if(chec=="")
alert("Please add your content");
else
alert("successfully submitted");
});
check out this fiddle:
http://jsfiddle.net/0t3oovoa/
You need to check that on server side (with php) and you can also check it on client side(Javascript).
Client side test is good if you want the user to get fast response, but you still need to check it on server side because javascript on your website can ALWAYS be changed by user.
You could also just add "required" on your input elements.
for server side check with php:
<?php
//Check if variables exist
if(isset($_POST['sender']) && isset($_POST['subject']) && isset($_POST['message'])){
//Check if sender value is empty
if(empty($_POST['sender'])){
//If empty, go back to form.Display error with $_GET['error'] in your form page
header('location: backToFormPage.php?error=send');
}
//...
}
//Variables doesn't exist
else{
//Redirect to page or other action
}
?>
You can achieve it two ways:
1. Client Side( Which i recommend) use the form validation to validate the form data if it is empty tell them to fill it. You chose the submit button to trigger validation that is not recommended instead validation is triggered on form submission or on change of input elements(for real-time validation). Anyways below is an example for validation using the click event on submit button.
var validateTextBox = function(textBox) {
var val = textBox.value;
if(val=="") { // Check for empty textbox
return false;
}
return true;
}
documnet.querySelector('#SubmitButton').onclick(function () {
var textbox = document.querySelector("#SubjectORMessage").value;
if(validateTextBox(textbox)){
// Do something to let page know that form is valid
} else {
// Let the user know that he has done something wrong
alert("Please fill the content");
}
})
2. Server Side if unfortunately empty data is send to the server, then use server side validation (Server side validation requires a little more thing to do at more than one place, i.e., html, php/python/perl)

Add validation to HTML5 required fields

I am using HTML5's required attribute on my input elements and select boxes and PHP for validation.
How can I show an alert if the required fields are not filled in? I tried using onsubmit() but the form is processed anyway and no alert is shown.
If the user's browser supports html5, he cant submit the form if not all the required fields have been written into.
Generally, you can prevent a form from submitting in jQuery like so:
$('#yourformselector').submit(function(event) {
$(this).find('[required="required"]').each(function() {
if (!$(this).val().length) {
event.preventDefault();
return false;
}
});
});
If you are using a modern/newer web browser, your default browser alerts should automatically display.
Or try:
$(document).ready(function() {
$('form').submit(function() {
var incomplete = $('form :input').filter(function() {
return $(this).val() == '';
});
//if incomplete contains any elements, the form has not been filled
if(incomplete.length) {
alert('please fill out the form');
//to prevent submission of the form
return false;
}
});
});
You may use checkValidity(), it will try to validate with attributes like pattern, min, max, required, etc. Follow this link to go deeper here
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
alert('invalid input')
} else {
alert('valid input')
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>

Prevent action attribute from running php script with javascript [duplicate]

This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.

How not to grab default value of inputbox

I am grabbing the value of input box and passing to the URL as querystring. I dont want to grab the default value "Enter Keywords(address....) which is controlled to show or hide by the following:
//**onClick and OnLostFocus (focus and blur) events on textareas and input textboxes**
$('input[type="text"], textarea').focus(function () {
defaultText = $(this).val();
$(this).val('');
});
$('input[type="text"], textarea').blur(function () {
if ($(this).val() == "") {
$(this).val(defaultText);
}
});
<input name="KeywordBox" class="BasicSearchInputBox" type="text" size="300" value="Enter Keywords (address,city and state OR zipcode)"/>
How not to grab the default text but just user input?? in jquery?
I usually add some default class name to the input field, then clear it when the user types. That way I can tell if the default "watermark" text is there, or user data.
The proper way to do this would be to use placeholder and fallback for older browsers.
For your current problem you can just check for that default text when you grab the value. Something like:
$('form').submit(function(){
if (~$('input').val().indexOf(defaultText)) {
// Not found, do your ajax stuff
}
});
The code you have above doesn't really do default values (placeholder). If someone first types 'anything' into the field, then clears the value from the field, your code will reset it to 'anything' instead of 'Enter Keywords...'
You need a plugin like http://archive.plugins.jquery.com/project/defaultvalue
<input placeholder="Enter a username…" type="text">
<input placeholder="…and a password" type="password">
<script>
$(' [placeholder] ').defaultValue();
</script>
If you really want to write it on your own, the simplest steps are
Add a placeholder property in the input field
onfocus: clear input.value if input.value equals input.placeholder
onblur: set input.value to input.placeholder if input.value is empty
You can do it with something like:
function togglePrompt() {
if (this.value == this.defaultValue) {
this.value = '';
} else if (this.value == '') {
this.value = this.defaultValue;
}
}
window.onload = function() {
var el = document.getElementById('inp0');
el.onfocus = togglePrompt;
el.onblur = togglePrompt;
}
<input value="Enter text..." id="inp0">

Categories