Disable submit button until all hidden inputs have a value - javascript

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
});

Related

How to automatically submit form if input field value exists?

I have the following form on my site. It's simple, one search input field and one submit button:
<form id="search-form" name="search-form" onsubmit="return search()">
<input type="search" id="query" class="search-field" value="<?php echo $searchQuery;?>">
<input type="submit" name="search-btn" id="search-btn" value="">
</form>
As you can see, in the search field (id=query) I have a php which sometimes inserts value into his field.
What I want to do is following:
If $searchQuery doesn't exist (or in other words, if value of search
field id=query is empty, allow user to click on the search button
manually.
If $searchQuery exist, auto submit the the form (simulate click on
the search button.
Any solution will help, JavaScript, jQuery or in PHP. I just need to figure out how to auto submit this form when PHP variable $searchQuery exists.
I believe you are asking specifically on initial page load. Use jQuery:
$(document).ready(function() {
if ($('#query').val() !== '') {
$('#search-form').submit();
}
});
You would need to just look to see if the value is populated and submit the form if it is.
jQuery Version:
$( function() {
if ( $( '#query' ).val() !== '' ) {
$( '#search-form' ).submit();
}
});
Fiddle: https://jsfiddle.net/fe9m8pk3/
Javascript Version:
function ready( fn ) {
if ( document.attachEvent ? document.readyState === 'complete' : document.readyState !== 'loading' ) {
fn();
} else {
document.addEventListener( 'DOMContentLoaded', fn );
}
}
ready( function() {
if ( document.getElementById( 'query' ).value != '' ) {
document.getElementById( 'search-form' ).submit();
}
});
Fiddle: https://jsfiddle.net/qeo25yu1/
<script type="javascript/text">
var query = document.getElementById('query');
if(query.value != ''){
//do your submit
}
function yoursubmitfunctionname(){
//do your submit
}
query.addEventListener('change',yoursubmitfunctionname);
</script>
This code will submit form if character length minimum fullfiled using Jquery:
$(document).ready(function ()
{
var minimum_character = 7;
$('#query').on('propertychange input', function (e)
{
var valueChanged = false;
if(e.type=='propertychange')
{
valueChanged = e.originalEvent.propertyName=='value';
}
else
{
valueChanged = true;
}
if(valueChanged)
{
str_length = $('#query').val().length;
if(str_length == minimum_character)
{
$("#search-form").submit();
}
}
});
});

Disable form submit button input=text and input=checkbox with jquery

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?

Execute code when textboxes have data

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." );
});

How to enter all multi-selection options into database

I have multi-selection functionality similar to this (see link): http://jsfiddle.net/eUDRV/341/.
HTML code:
<section class="container" >
<div>
<select id="list" name="list"size="15">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
<div>
<br><br><br>
<input type="button" id="button_left" value="<--"/>
<input type="button" id="button_right" value="-->" />
</div>
<div>
<select id="selected_values" size="15"></select>
<input name="selected_values" type="hidden"/>
</div>
jQuery/Javascript code:
$(document).ready(function () {
$("#button_right").click(function () {
var selectedItem = $("#list option:selected");
var added = false;
$("#selected_values > option").each(function() {
if ($(this).text() > $(selectedItem).text()) {
$(selectedItem).insertBefore($(this));
added = true;
return false;
}
});
if(!added) $(selectedItem).appendTo($("#selected_values"));
updateHiddenField();
});
$("#button_left").click(function () {
var selectedItem = $("#selected_values option:selected"), activeValues;
var added = false;
$("#list > option").each(function() {
if ($(this).text() > $(selectedItem).text()) {
$(selectedItem).insertBefore($(this));
added = true;
return false;
}
});
if(!added) $(selectedItem).appendTo($("#list"));
updateHiddenField();
});
function updateHiddenField () {
$('input[name="selected_values"]').val(
$.map($('#selected_values option:selected').toArray(), function (e) {
return e.value;
})
);
}
});
PHP code:
if(!empty($_POST['selected_values'])) {
$_POST['selected_values'] = explode(',', $_POST['selected_values']);
foreach($_POST['selected_values'] as $x) {
$query = "INSERT INTO $table (id1, id2) VALUES ($id1Value, $x)";
db_query($query);
My goal is to iterate through all of the values that are moved into the left column and enter them into a database using PHP. I'm able to get this functionality to work, however, I'm having the exact same issue as seen referenced here: how can I get all options in a multi-options select using PHP?. I'm accessing the values using $_POST["leftValues"] but if the user clicks on one of the options, only that one will be entered into the database. Unfortunately, the accepted solution isn't working for me.
$("form:has(#leftValues)").on('submit', function () {
$("#leftValues option").prop('selected', true);
});
Can someone please explain to me how I can get this solution to work for me or an alternative way of ensuring $_POST["leftValues"] will contain all the options instead of only the selected/highlighted? Any response is greatly appreciated.
You could add a hidden field and update that whenever the lists change.
You'd need to update your html:
<div>
<select id="leftValues" size="5" multiple></select>
<input name="leftValues" type="hidden" />
</div>
and add a function to do the updating:
function updateHiddenField () {
$('input[name="leftValues[]"]').val(
$.map($('#leftValues option:selected').toArray(), function (e) {
return e.value;
})
);
}
And call it in each of your click handlers:
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
updateHiddenField();
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected"), activeValues;
$("#rightValues").append(selectedItem);
updateHiddenField();
});
Finally, you can do this in your PHP to get what you originally expected:
$_POST['leftValues'] = explode(',', $_POST['leftValues']);
Finally got it to work. I edited the submit callback, as the original solution suggested.
Added an id to my form tag:
<form id="form" method="post">
When the form is submitted, select/highlight all options in the selected_values list:
$(#form).submit(function () {
$("#selected_values > option").each(function () {
$(this).attr('selected', 'selected');
});
return true;
});

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