Johnny Johnny - 4 months ago 11
PHP Question

Disabling a submit button using JQuery if a value has not been selected from a specific dropdown

I am trying to disable a submit button if a value from a specific dropdown has not been selected. The code for the dropdown and button looks like this:

<li>
<select name="names" id="names">
<option value="">Constituency</option>
<!-- populates the drop down with names -->
<?php foreach ($cons as $constituency): ?>
<option value="<?php htmlout($constituency['ids']); ?>">
<?php htmlout($constituency['names']); ?>
</option>
<?php endforeach; ?>
<?php if (isset($selectError)): ?>
<p><?php htmlout($selectError); ?></p>
<?php endif; ?>
</select>
</li>

<li><input type="hidden" name="action" value="search"></li>
<li><input type="submit" value="SEARCH" class="button search" id="jsbutton" disabled="disabled"></li>


So the dropdown has an id of 'names' and the button has an id of 'jsbutton' and is set to 'disabled' .

I then try to target it with the following JQuery but the button remains disabled regardless:

$(document).ready(function() {

if ($('#names').val() = '')
{
$('#jsbutton').attr('disabled', 'disabled');
}
else
{
$('#jsbutton').removeAttr('disabled');
}
});


So what I am trying to do is:


  • Check if value has been selected from dropdpwn.

  • IF it hasn't then leave button disabled.

  • ELSE a value has been selected from the dropdown and therefore the button should be enabled.



Any help on this is appreciated.

PHP TO POPULATE THE DROPDOWN:

try
{
$cons_result = $pdo->query("SELECT id, name
FROM constituency
ORDER BY name");
}
catch (PDOException $e)
{
$error = 'Error fetching constituencies from database!' . $e->getMessage();
include 'error.html.php';
exit();
}


foreach ($cons_result as $rows)
{
$cons[] = array('ids' => $rows['id'], 'names' => $rows['name']);
}

include 'searchform.html.php';
}

Answer
$(document).ready(function() {
     $("#names").change(function () {
          var str = "";
          if ($("#names option:selected").val()=='')
            {

                $('#jsbutton').attr('disabled', 'disabled');  
            }
            else
            {

                $('#jsbutton').removeAttr('disabled');
            }
        });
});