Do not search if the search field is empty (Wordpress) - javascript

I have this basic Wordpress search form, I don't want users to be able to search if they leave the search field blank, preferably with javascript, how is this done?

Many ways lead to Rome... But here is one solution.
So, say your search form input field has and id called query and you want to disable the submit button until the user has entered at least 1 character.
$('#query').keyup(function () {
if ($(this).val() == '') {
$('#submit').prop('disabled', true);
} else {
$('#submit').prop('disabled', false);
}
}).keyup();
See this fiddle: https://jsfiddle.net/fxqsc86s/

(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#search').attr('disabled', 'disabled');
} else {
$('#search').removeAttr('disabled');
}
});
})();
and remember to disable the button by default:
<input type="submit" id="search" value="Search" disabled="disabled" />
Answer taken from previous stack overflow question: Disabling submit button until all fields have values

You can also do it like this.
It will check either your TextBox is empty
if ($('#TextBoxId').val() === '') {
// Your coding will go here.
}

Related

using only javascript to prompt user to choose at least one checkbox

Hello I have a HTML form which already prompts users to fill empty fields. And this is the script that I am using:
<!-- Script to prompt users to fill in the empty fields -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("To continue, you must correctly fill in the missing fields.");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
});
</script>
This script works flawlesly and it brings up a nice prompt that looks like this:
It works for all the input text fields, but I need another script that will (a) check if at least one checkbox you can see at the bottom of the form is checked, and (b) will bring up a prompt which is styled the same way as the one above.
I looked at other posts and wrote the below script. I referenced checkboxes by their IDs and somehow used the function function(e) from the above script. Well it won't work for me but I must be close...
<!-- Script which prompts user to check at least one checkbox -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
if (
document.getElementById("linux-c-arm-checkbox").checked == false &&
document.getElementById("linux-eda-cad-checkbox").checked == false &&
document.getElementById("linux-blender-checkbox").checked == false &&
document.getElementById("linux-photo-checkbox").checked == false &&
document.getElementById("linux-audio-checkbox").checked == false &&
document.getElementById("linux-latex-checkbox").checked == false &&
document.getElementById("linux-desktop-checkbox").checked == false &&
document.getElementById("linux-office-checkbox").checked == false
){
function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please choose at least one checkbox.");
}
}
}
});
</script>
Can anyone help me solve this by using javascript without JQuery?
Though there is no way you can put required attribute on a checkbox group and do the validation for atleast one selection, here is a workaround solution. Do the changes accordingly on your HTML.
It takes a hidden textbox as the placeholder of the selected checkbox group. If atleast one is selected the hidden field will also have the value.
function setAccount() {
if (document.querySelectorAll('input[name="gender"]:checked').length > 0)
document.querySelector("#socialPlaceholder").value = document.querySelector('input[name="gender"]:checked').value;
else
document.querySelector("#socialPlaceholder").value = "";
}
function invalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Please select at least one account');
} else {
textbox.setCustomValidity('');
}
}
<form target="_blank">
<b>Accounts</b>
<input type="text" id="socialPlaceholder" required value="" style="width:0px;height:0px;position: relative;left:-30px;opacity: 0;" oninvalid="invalidMsg(this)"/><br/>
<label>Facebook<input type="checkbox" name="gender" value="facebook" onClick="setAccount()"/></label>
<label>Twitter<input type="checkbox" name="gender" value="twitter" onClick="setAccount()"/></label>
<label>Google Plus<input type="checkbox" name="gender" value="google_plus" onClick="setAccount()"/></label>
<label>Instagram<input type="checkbox" name="gender" value="instagram" onClick="setAccount()"/></label>
</br>
</br>
<input type="submit" value="Submit" />
<br/><br/>
NOTE: Submit without selecting any account to see the validation message
</form>
Your e is null, because you use self executing function inside if and does not pass any event for it.
Try changing e.target to document.getElementById("linux-office-checkbox") or other not-checked element.
In jQuery I would check if any checkbox is selected by doing $('.checkboxClass:checked').length > 0

jquery.validate - button disabled until valid email

I am using https://jqueryvalidation.org/ to validate my form on the frontend. The basic "if field is empty - validate" works OK.
But I'd like to the submit button to be initially disabled until a valid email address has been entered. I'd like the button to become enabled as soon as the field becomes valid (on keypress).
So basically I just need to remove the 'btn-disabled' class once its valid.
I'm struggling with the jQuery to add this function/method. Would be grateful if someone can help out.
Heres a slightly simplifed version: http://codepen.io/dagford/pen/kXJpEZ
$(document).ready(function(){
$("#reset-form").validate({
rules: {
emailaddress: {
required: true,
email: true
}
},
messages: {
email: "Please enter a valid email address"
}
});
});
you can check if the form is valid after entering the email address. Keep you button disabled by default and remove the disabled attribute once you validate the form.
$("#emailaddress").on("blur", function(){
if($("#reset-form").valid())
{
$("#btn-reset").removeAttr("disabled");
}
});
Code Pen : http://codepen.io/anon/pen/YWLjKX?editors=1010
You have attr for this
$('#button1, #button2').attr("disabled", true);
Check this :
<script type="text/javascript">
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') { // write your code for valid email here
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
</script>

A short way of cheking multiple blank text fields jQuery

I need to check if there are blank input text fields in my < form >. Instead of doing this multiple times
$.trim($('#myMessage').val()) == '' || $.trim($('#myage').val()) == '' .//so on...
What is the best way to check multiple blank text fields?
use:
if($('input:text[value=""]').length);
try
$("form input[type=text]").filter(function () {
return $.trim(this.value) != "";
}).length;
Note: You have to use any form id or class instead of form
Here is the code ,
// Validate form fields in Sign up form
$(".signup-form").submit(function(){
var isFormValid = true;
$(".signup-form .required input:text").each(function(){ // Note the :text
if ($.trim($(this).val()).length == 0){
$(this).parent().addClass("highlight");
isFormValid = false;
} else {
$(this).parent().removeClass("highlight");
}
});
if (!isFormValid) alert("Please fill in all the required fields (highlighted in red)");
return isFormValid;
});

How do I use javascript to prevent form submission because of empty fields?

How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}

javascript: prevent submit if all text fields are empty?

i am using this javascript to disable my form submit button until a user has typed in the textarea field. once the textarea is populated the submit button is no longer disabled.
however, whilst this is working for a single text area i now want to find a way to make this work so that if i had four text input fields then to keep the submit button disabled until all of them are NOT empty/populated with text.
heres what im using at the moment:
<form action=\"includes/welcomestats.php\" method=\"post\" id=\"form1\" onSubmit=\"if (this.display_name.value == '') {return false;}\">
<input type=\"text\" name=\"display_name\" id=\"display_name\" maxlength=\"30\" placeholder=\"Display Name\">
<input type=\"submit\" class=\"welcome-submit2\" name=\"submit\" value=\"Next ->\" id=\"submit\"/>
</form>
<script>
$(function(){
$("#submit").submit(function(e){
if($("#display_name").val()==""))
{
e.preventDefault();
}
});
});
</script>
but now i am adding more text input fields to my form, so i need the script to keep my submit button disabled until all the text fields are populated, can anyone help me please?
i want to add these text fields to my form:
<input type=\"text\" name=\"public_email\" id=\"public_email\" maxlength=\"50\" placeholder=\"Email Address\">
<input type=\"text\" name=\"phone\" id=\"phone\" maxlength=\"30\" placeholder=\"Phone Number\">
<input type=\"text\" name=\"age\" id=\"age\" maxlength=\"2\" placeholder=\"Display Age\">
You could use .filter method to get all the empty input element, then check the length.
if ($('#form1 input').filter(function(){return $(this).val().length == 0;}).length > 0) {
e.preventDefault();
}
Try using:
<script>
$(function(){
$('form input').each(function(){
if($(this).is(':empty')){
$('form #submit').preventDefault();
}
});
});
</script>
Use this: http://jsfiddle.net/qKG5F/641/
<input type="submit" id="register" value="Register" disabled="disabled" />
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
})()
You'll need the OR operator - ||
So if display_name is empty OR public_email is empty etc...
$(function(){
$("#submit").submit(function(e){
if($("#display_name").val()=="" || $("#public_email").val()=="" || $("#phone").val()=="" || $("#age").val()=="")
{
e.preventDefault();
}
});
});
Give all of your text fields you want to include in this validation a class class="required" or something along those lines, then you can do this
var empty = $('.required').filter(function(){ return $(this).val() == "" }).length;
if(empty === 0){
//Enable your submit button all text fields have a value
}
Try this function:
function checkInputs(form) {
var inputs, all,
status = true;
if (form && form instanceof jQuery && form.length) {
inputs = form.find("input[type=text]");
all = inputs.length;
while (all--) {
if (!inputs[all].value) {
status = false;
break;
}
}
return status;
}
}
And demo here: http://jsbin.com/afukir/1/edit
EDIT: I've added instanceof to make sure that this function will only proceed if the form is actually a jQuery object.

Categories