We help IT Professionals succeed at work.

How do I Enable submit button only if listbox has items

212 Views
Last Modified: 2017-04-17
initially i have the submit disabled so users cannot submit an empty list. Is there way with my existing code to detect if a list has items and enable the submit button. However if a user removes items then make it false .

I am using jquery to populate a listbox which a contributor helped me with and wodering if that could be modified to check for items in a list and enable the submit button.

Thanks

php

<?php
	$conn = mysql_connect("localhost","root","");
	mysql_select_db("sample",$conn); 
	$result = mysql_query("SELECT * FROM boxes where department = '{$_GET['dept']}' ORDER BY custref ASC");
?>
								
	<select name="boxdest[]" id="boxdest" size="7" multiple="multiple">

<?php
	$i=0;
	while($row = mysql_fetch_array($result)) {
?>
	<option value="<?php echo $row["custref"];?>"><?php echo $row["custref"];?></option>
<?php
	$i++;
	}
?>
	</select>
	<span style="display: inline-block; width: 70px; height: 82px; padding-left: 10px; padding-right: 10px; vertical-align: top;margin-top:35px;">
          <button class="btn btn-primary switch-item" data-src="boxdest" data-dst="boxdest2">&gt;</button>
    	  <button class="btn btn-primary switch-item" data-dst="boxdest" data-src="boxdest2">&lt;</button>
	  </span>
	  <select name="boxdest2[]" id="boxdest2" size="7" multiple="multiple"></select>

Open in new window


jquery

<script>
		$(function () {
			$('.switch-item').click(function (e) {
				e.preventDefault();
				var src = $(this).data('src');
				var dst = $(this).data('dst');
				var sel = $('#' + src + ' option:selected').detach();
				$('#' + dst).append(sel);
				
			});
			
			$('form').submit(function () {
				$('#boxdest2 option').prop({
					selected: true
				});
			});
			
		});
	</script>

Open in new window

Comment
Watch Question

Most Valuable Expert 2011
Author of the Year 2014

Commented:
Not an answer, just a note.  You must  validate this information in the server-side script, as well.  The client side JavaScript is just for human convenience.  The server side validation is to protect your data model from attack and damage.
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Here's the other script that I posted last night for your other question.  I modified it slightly to add the steps that disable and enable the submit control.  

Line 39 disables the submit control on page load.
Line 66 enables the submit control when information is moved in to the "#rite" selection(s)
Line 74 disables the submit control if the "rite" selections are emptied

Please see: https://iconoun.com/demo/temp_peter_cooper.php
<?php // demo/temp_peter_cooper.php
/**
 * https://www.experts-exchange.com/questions/29016352/How-do-I-Enable-submit-button-only-if-listbox-has-items.html
 * https://www.experts-exchange.com/questions/29016222/Why-is-my-POST-not-going-to-results-page.html
 */
error_reporting(E_ALL);

// MAKE SURE THAT PHP WORKS WITH UTF-8
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');


// USE PHP (AND MAYBE MySQL) TO CREATE VARIABLES FOR OUR HTML
$options = <<<EOD
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Tre</option>
<option value="4">For</option>
EOD;


// CREATE OUR WEB PAGE IN HTML5 FORMAT, USING HEREDOC SYNTAX
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<style type="text/css">
/* STYLE SHEET HERE */
</style>

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){

    $("#submitme").attr('disabled', 'disabled');

    var initialList = $('#left > option').map(function(){
        return this.value;
    }).get();

    function moveSelections(source, destination) {
        var selected = $(source + ' > option:selected');
        $(destination).append(selected.clone());
        selected.remove();

        var list = $(destination + ' > option').clone().sort(function (a, b){
            if (initialList.indexOf(a.value) < initialList.indexOf(b.value)){
                return -1;
            }

            if (initialList.indexOf(a.value) > initialList.indexOf(b.value)){
                return 1;
            }
            return 0;
        });

        $(destination).empty().append(list);
    }

    $('#moverite').click(function(){
        moveSelections('#left', '#rite');
        $("#submitme").removeAttr('disabled');
    });

    $('#moveleft').click(function(){
        moveSelections('#rite', '#left');
        var values = $("#rite > option").map(function(){
            return $(this).val();
        }).get();
        if (!values.length) $("#submitme").attr('disabled', 'disabled');
    });

    $('#submitme').click(function(e){
        e.preventDefault();
        var values = $("#rite > option").map(function(){
            return $(this).val();
        }).get();

        $.post("request_reflector.php", {q:values}, function(response){
            $("#output").html(response);
        });
    });

});
</script>

<title>HTML5 Page With jQuery in UTF-8 Encoding</title>
</head>
<body>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<form action="request_reflector.php" method="post">

<select id="left" multiple="multiple">
$options
</select>

<input type="button" id="moverite" value="Move >>>" />
<input type="button" id="moveleft" value="Move <<<" />

<select id="rite" multiple="multiple">
</select>

<br clear="all" />
<input type="submit" id="submitme" value="Go" />
</form>

<div id="output" />

</body>
</html>
HTML5;


// RENDER THE WEB PAGE
echo $htm;

Open in new window

CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008

Commented:
However if a user removes items then make it false
My guess is you meant:
However if a user removes all the items from the second list then make it false

Based on what you posted, try:
$('.switch-item').click(function (e) {
				e.preventDefault();
				var src = $(this).data('src');
				var dst = $(this).data('dst');
				var sel = $('#' + src + ' option:selected').detach();
				$('#' + dst).append(sel);

				/* if you have <button id="submit_button">...</button> */
				$( '#submit_button' ).prop("disabled", $('#boxdest2 option').length==0)
			});

Open in new window

Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.