santa
santa

Reputation: 12512

Enable button if at least one select option

I have a form with 3 select elements. Each one, by default, has option "na" and submit button is disabled. I need to enable the button when at least one of these three selectors has any other option but "na"

I am trying to write a function so that I can check for options on page load as well:

JS

function myFunction() {
    bt   = $(".b");
    bt.attr("disabled", false).removeClass("disabledB");

    if ($(".mySelect").val(":not(na)").length > 0) {
        bt.attr("disabled", true).addClass("disabledB");
        return false;
    }
}

HTML

<table>
<tr>
  <td>
    <select class="mySelect">
      <option value="na"></option>
      <option value="1">value 1</option>
      <option value="2">value 2</option>
    </select> 

    <select class="mySelect">
      <option value="na"></option>
      <option value="3">value 3</option>
      <option value="4">value 4</option>
    </select> 
  </td>
</tr>
<tr>
  <td>
    <input type="button" class="b" value="click me">
  </td>
</tr>
</table>

Not sure what I am doing wrong.

Upvotes: 1

Views: 1993

Answers (4)

John W
John W

Reputation: 1512

RepWhoringPeeHaa is right. Passing a string into $().val() means that you are attempting to set the value. $().val() cannot take a selector. I think what you want to do is use

$('.mySelect option[value!=na]:selected').length == 0

in place of

$(".mySelect").val(":not(na)").length > 0

Upvotes: 1

iambriansreed
iambriansreed

Reputation: 22241

Change:

if ($(".mySelect").val(":not(na)").length > 0) {
    bt.attr("disabled", true).addClass("disabledB");
    return false;
}

To:

if ($(".mySelect option[value!='na']:selected").size() > 0) {
    bt.attr("disabled", true).addClass("disabledB");
    return false;
}

Upvotes: 2

Elias Zamaria
Elias Zamaria

Reputation: 101083

Maybe replace if ($(".mySelect").val(":not(na)").length > 0) with if ($(".mySelect").filter(function() { return $(this).val() !== "na"; }).length > 0)

Upvotes: -1

NuNn DaDdY
NuNn DaDdY

Reputation: 2992

This may help

$("select").change(function() {
    if ($("option:selected").not("option[value=na]"){
       $("input[type=button]").removeAttr("disabled");
    }
});

Here are a couple of articles for reference

http://api.jquery.com/selected-selector/

http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_disable.2Fenable_a_form_element.3F

Upvotes: 0

Related Questions