Reputation: 85
I have i simple jquery function to disable a Button if the selected dropdown value is blank. But it wont work and i'm not sure why?
Here's my HTML:
<form action="{% url 'select_controller' id=i.ID %}" method="post">
{% csrf_token %}
<td>
<select class="form-control" name="controller" id="select_controller">
{% if i.proposal_status == "Changes needed" %}
<option value={{ i.ID_fk }}> {{ i.ID_fk.last_name }}, {{ i.ID_fk.first_name }}</option>
{% else %}
<option value='blank'> -</option>
{% for controller in list_controller %}
<option value={{ controller }}> {{ controller.last_name }}, {{ controller.first_name }}</option>
{% endfor %}
{% endif %}
</select>
</td>
<td>
{% if count_controller < 2 %}
<button id="button" class="btn btn-primary" type="submit" value="Submit" > Send </button>
{% else %}
Only two regs
{% endif %}
</td>
</form>
And this is my jQuery:
$("select").on('change',function(){
if($(this).find('option:selected').text()=="-")
$("#button").attr('disabled',true)
else
$("#button").attr('disabled',false)
});
I'm new to Javascript/jQuery but i think there is only one little thing i forgot
Upvotes: 0
Views: 1233
Reputation: 574
We may also use:
$('#button').prop('disabled',true);
Some explanation on .prop()
versus .attr()
usage here.
Upvotes: 0
Reputation: 549
Why are you comparing the text of selected option, just compare its value, this'll be much simpler.
$("select").on('change',function(){
if($(this).val()=="blank")
$("#button").attr('disabled',true)
else
$("#button").attr('disabled',false)
});
But Please make sure that you have disabled button
on page load
.
There is two way to do this working. First, you can disable button
on page load
in jquery. Second, on page load
get the value of select
and check that if it's value is blank
then disable the button
.
Upvotes: 1
Reputation: 3675
Your options text content is actually -
, notice the two spaces infront of the dash. The jQuery is reading those spaces and not counting -
the same as -
. Remove those preceding spaces and it should now work.
$("select").on('change', function() {
if ($(this).find('option:selected').text() == "-")
$("#button").attr('disabled', true)
else
$("#button").attr('disabled', false)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="{% url 'select_controller' id=i.ID %}" method="post">
<td>
<select class="form-control" name="controller" id="select_controller">
<option value="test">test</option>
<option value='blank'>-</option>
<option value="testing">testing</option>
</select>
</td>
<td>
<button id="button" class="btn btn-primary" type="submit" value="Submit">Send</button>
</td>
</form>
Upvotes: 0