0

I have a php loop that echos multiple <select> elements as part of an online ordering system where the user can select the quantity of a certain item.

The button that executes the form runs a php script that inserts the values into my database, however, I need to be able to ignore the values that are equal to "0".

By creating an onClick event (JS function) on the submit button, I execute this code:

$('#quantityForm').find(':select').each(function(){
    if($(this).val() == "0"){
        $(this).attr('disabled', 'disabled');
    }
})

Everything seems to work fine except the code that sets the <select> element as disabled, as my php script attempts to get all of the "0" values.

Is there something I am doing wrong?

Additional code:

<form id="quantityForm" method="get">
    <?php get_items($example); ?>
    <button onClick="checkQuantity()" id='basket' type='submit' name='submit'><i class='fas fa-shopping-basket'></i></button>
</form>
  • Are you wanting to disable the select, or the option that has a value of 0? Because the select will only have a value of 0 once that option is selected – Taplar Jun 12 '18 at 14:15
  • 2
    `:select` isn't a thing. `select` is. it's an exact tag name. `:input` is a jquery pseudo selector for all types of form inputs. – Taplar Jun 12 '18 at 14:16
  • @Taplar I am wanting to disable the select so the form does not submit it to my php script. 0 is selected by default :) – Christian Smith Jun 12 '18 at 14:17
  • Ahh, ok, so yeah. Change `:select` to `select` – Taplar Jun 12 '18 at 14:18
  • You should remove the select's `name` attribute when the option with `value="0"` is selected, that way your form will ignore the select input. – Barskey Jun 12 '18 at 14:19
  • you should use prop instead of attr() cf https://stackoverflow.com/questions/5874652/prop-vs-attr – R. Martin Jun 12 '18 at 14:24
  • @Taplar That fixed it! Thank you very much. :) – Christian Smith Jun 12 '18 at 14:32

2 Answers2

1

You could remove the select's name attribute when the option with value="0" is selected, that way your form will ignore the select input.

$(document).on('change', 'select', function() {
    if ($(this).val() == 0) {
        $(this).attr('name', '');
    }
    else {
        $(this).attr('name', '<name>');
    }
});
Barskey
  • 423
  • 2
  • 5
  • 18
1
$('#quantityForm')
    //find all the select elements in the form
    .find('select')
    //filter and return only those that have a value of 0
    .filter(function(){
        return this.value === '0';
    })
    //make them disabled
    .prop('disabled', true);
Taplar
  • 24,788
  • 4
  • 22
  • 35