MariaL MariaL - 4 months ago 13
Javascript Question

Hide option if its value is equal to another option

I'm trying to write some code to hide an

<option>
if its value is equal to the value of the first (which is dynamic and retrieved with php)
This is the code:

<select onChange="this.form.submit()" name="cart[<?php echo $_item->getId() ?>][qty]" class="input-text qty qtySelect" >
<option value="<?php echo $this->getQty() ?>" name="cart[<?php echo $_item->getId() ?>][qty]" class="input-text qty qtySelected" ><?php echo $this->getQty() ?></option>
<option value="1" name="cart[<?php echo $_item->getId() ?>][qty]" data-qty="1" class="input-text qty notSelected" label="1" ><span>1</span></option>
<option value="2" name="cart[<?php echo $_item->getId() ?>][qty]" data-qty="2" class="input-text qty notSelected" label="2" >2</option>
<option value="3" name="cart[<?php echo $_item->getId() ?>][qty]" data-qty="3" class="input-text qty notSelected" label="3">3</option>
</select>


I've tried to do it like this:

<script>
$j('.qtySelect').change(function(){
if(('.qtySelected').val() == ('.notSelected').val())
{
$j('.notSelected').hide();
}
});
</script>


But this didn't work. Any ideas how this can be achieved?

Answer

It will hide all options which are duplicated, Try:

$(".qtySelect option").each(function(){
  $(this).siblings("[value='"+ this.value+"']").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select name="cart[0][qty]" class="input-text qty qtySelect" >
                 <option value="1" name="cart[1[qty]" class="input-text qty qtySelected" >1</option>
                 <option value="1" name="cart[1][qty]" data-qty="1" class="input-text qty notSelected" label="1" ><span>1</span></option>
                 <option value="2" name="cart[3[qty]" data-qty="2" class="input-text qty notSelected" label="2" >2</option>
                 <option value="3" name="cart[4][qty]" data-qty="3" class="input-text qty notSelected" label="3">3</option>
    </select>

Comments