I have a form with three inputs ([type=text], multiple input[type=checkbox] and a disabled submit button).
I want the submit button to be enabled if a user has filled in all three text-inputs and has selected at least one of the checkboxes.
I found this fiddle which works great on all three text-inputs, but I'd like to add the additional condition that at least one checkbox must be selected:
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=password]');
function checkEmpty() {
// filter over the empty inputs
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
fiddle
Add class="checkbox" in the checkboxes then modify checkEmpty() to this:
function checkEmpty() {
var text= $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
var checkbox = false;
if ($(".checkbox:checked").length > 0) {
checkbox = true;
}
if(text == true && checkbox == true){
return true;
}else{
return false;
}
}
Then add the event on click for the checkboxes which is:
$(".checkbox").on("click", function(){
$submit.prop("disabled", !checkEmpty());
});
Hey just add input[type=checkbox] only in jquery part, here is your desired output, try below code:
Index.html
<form method="POST" action="">
User Name: <input name="Username" type="text" size="14" maxlength="14" /><br />
hobbies:<input type="checkbox" name="cricket">Cricket<input type="checkbox" name="football">football<input type="checkbox" name="hockey">hockey<br>
<input type="submit" value="Login" name="Submit" id="loggy">
</form>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=checkbox]');
function checkEmpty() {
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur();
});
</script>
Ok i have a serious problem now.
I'm using wordpress and added:
<?php wp_head(); ?>
<?php wp_footer(); ?>
To my header.php and footer.php, cause i need them so a plugin is getting loaded.
Since i added them the working solution from Stephan Sutter isn't working anymore. The submit button is still disabled if i fill in all required forms. If i remove them it works again, but i need them for the plugin.
I think it is because the plugin adds input text to the page. Is there any way i can use the code frm Stephan for a defined form ID=#addmovie-form?
Related
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
In my (gravityform) I have two fields,a radio button or checkbox and a numeric field .
i'd like to pass a value (yes or not) to the radio button, based on the numeric field, so if i fill this with a number less than a default value for example 10 , i get the checkbox of radio button selected with "yes" or "not".
No matters if this is possible prior or after submission.
Thanks very much.
Use an event called "keyup" according to which you can change values of the radio button. Try the following code :
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.js" integrity="sha256-laXWtGydpwqJ8JA+X9x2miwmaiKhn8tVmOVEigRNtP4=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$("#numbervalue").on("propertychange change keyup", function() {
var val = $("#numbervalue").val();
if (val > 10) {
$("#one").prop("checked", false);
$("#two").prop("checked", true);
} else {
$("#one").prop("checked", true);
$("#two").prop("checked", false);
}
});
});
</script>
</head>
<body>
<form action="">
Number:
<br>
<input type="number" name="numbervalue" id="numbervalue" value="10">
<br>
<br>Value is more than 10 ?
<br>
<input type="radio" name="truth" id="one" value="0" checked>No
<br>
<input type="radio" name="truth" id="two" value="1">Yes
<br>
</form>
</body>
</html>
Here's a very basic demo for what you are trying to do:
DEMO
The basic idea is that you look at the value in the input field and check or uncheck the radio button accordingly.
Ok thanks, this worked, awesome!!
<script>
$(document).ready(function() {
$("#input_1_38").on("propertychange change keyup", function() {
var val = $("#input_1_38").val();
if (val > 6575) {
$("#choice_1_49_0").prop("checked", false);
$("#choice_1_49_1").prop("checked", true);
} else {
$("#choice_1_49_0").prop("checked", true);
$("#choice_1_49_1").prop("checked", false);
}
});
});
</script>
You should register an event handler for the numeric input.
Pure JS solution:
var radioYes = document.getElementById("choice_1_49_0"),
radioNo = document.getElementById("choice_1_49_1"),
valueToCheck = 10;
document.getElementById("input_1_38").addEventListener("change", function() {
if (+this.value > valueToCheck)
radioYes.checked = true;
else
radioNo.checked = true;
}, false);
JSFiddle
EDIT: Updated code according to your markup.
I have a simple form with hidden inputs and I'm trying to check whether each hidden input has a value. If all hidden inputs have a value than disable or enable the submit button. The inputs are being filled once the user clicks on an image via jquery. Ive tried multiple ways and it seems like I'm missing something....
<form method="post" action="test.php">
<div class="selections" id="accordion">
<h3>title<div class='status'>Pending</div></h3>
<div class='select-form'>
<div class='images'>
<img src='images/vote.jpg' data-value='data-value'>
<br/><span>title</span><br/>description
</div>
<input type='hidden' class='image-value' name='1' value=''>
</div>
<div class='select-form'>
<div class='images'>
<img src='images/vote.jpg' data-value='data-value2'>
<br/><span>title</span><br/>description
</div>
<input type='hidden' class='image-value2' name='2' value=''>
</div>
</div>
<input id="submit_button" type="submit" class="submit" value="SUBMIT">
</form>
the javascript goes as follows:
$( document ).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=hidden]');
function checkEmpty() {
// filter over the empty inputs
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
any ideas?
You could just call the checkEmpty() on img.click(), and from that function handle the disabled state.
Try it out here: JSFiddle (click the images)
$( document ).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=hidden]');
function checkEmpty() {
var res = true;
$inputs.each( function(i,v){
if(v.value == ""){
res = false;
return false;
}
});
$submit.prop("disabled", !res);
}
$("img").click( function(){
$(this).parent().parent().find("input[type=hidden]").val("sdf");
checkEmpty();
});
checkEmpty(); //set disabled onload
});
Your trim function isn't behaving as you accept, remove it like here :
function checkEmpty() {
// filter over the empty inputs
return inputs.filter(function() {
return !(this.value);
}).length === 0;
}
Put this inside of the blur function to find out if all hidden inputs have a non empty value.
var empty=false;
$('input[type=hidden]').each(function(){
if($(this).val()==""){
empty=true;
}
});
if(empty){
//DISABLE SUBMIT
}
You're using $ in your JavaScript variables when you shouldn't be. Working fiddle: http://jsfiddle.net/keliix06/2f3cv2pk/
$( document ).ready(function() {
var submit = $("input[type=submit]"),
inputs = $('input[type=hidden]');
function checkEmpty() {
// filter over the empty inputs
return inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
inputs.on('blur', function() {
submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
I have a project which I have to calculate the coordenates between two points. The first coordenates are calculated once the user enters in three text boxes the street, province and city.
How can I execute the code I have in PHP once the user fills out all three boxes and not before?
<form name="form" action="" method="post">
<input type="text" name="provincia" id="provincia">
<input type="text" name="municipio" id="municipio">
<input type="text" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
This is the form the user has to fill in. Once the user writes in all three (without mattering the order) I have php code which Im not sure if it can execute once these boxes have values.
What should I have to use to accomplish this? Ajax? Jquery? Javascript?
Not really sure,
thanks.
are you looking for this?
$(document).ready(function () {
var flag = false;
$("input[type=text]").change(function () {
flag = true;
$("input[type=text]").each(function () {
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
alert(values);
});
});
edit
<form name="form" action="" method="post">
<input type="text" class="tobeChecked" name="provincia" id="provincia">
<input type="text" class="tobeChecked" name="municipio" id="municipio">
<input type="text" class="tobeChecked" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
$(document).ready(function () {
var flag = false;
$(".tobeChecked").change(function () {
var values = "";
flag = true;
$(".tobeChecked").each(function () {
values += $(this).val().trim() + "+";
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
});
});
Create a function to validate the required field for those three text boxes and once all are filled with values execute your script:
$('#provincia,#municipio,#calle').blur(function(){
if($('#provincia').val() !="" && $('#municipio').val() !="" && $('#calle').val() !=""){
// Do your process here
}
});
You can use jquery validate plugin to validate these 3 input fields on the client side itself, In that way, the user cannot submit the form until he completely fills the input fields.
Give your Button an ID like:
<input type="submit" id="button" value="¡Buscar!"/>
Then you can do this in JQuery:
$("#button").click(function(){
//Get the value of the fields
var textfield1 = document.getElementById("provincia").value;
var textfield2 = document.getElementById("municipio").value;
var textfield3 = document.getElementById("calle").value;
//Check if Values are filled
if ( !textfield1.match(/\S/) || !textfield2.match(/\S/) || !textfield3.match(/\S/))
{
//execute your script
}
I hope it helps.
use jquery .change() function
$( "#provincia" ).change(function() {
//you can do something here
alert( "Handler for .change() called." );
});
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.