Change the HTML attribute in the option with JQUERY

Asked

Viewed 347 times

2

I’m trying to change the value of the select with the option to "disabled" but only when the user clicks the input field.

See the image to understand better: formulario com o select option

I want to exactly leave disabled the first "option" only when the user clicks on the field, I’m trying it, but not for sure, I’m starting to see Jquery Now.

<select id="" class="form-input" placeholder="Categoria: *">
    <option value="categoria" id="#cat">Categoria: *</option>
    <option value="buracos nas ruas">Buracos nas ruas</option>
    <option value="esgoto a ceu aberto">Esgoto a céu aberto</option>
    <option value="lixo em local proibido">Lixo em local proibido</option>
    <option value="falta de iluminação">Falta de iluminação</option>
    <option value="outros">Outros</option>
</select>


$('label select option').click(function(){
    $('#cat').html('<option  disabled >Categoria: *</option>');
});

If anyone can help me, I’d really appreciate it.

1 answer

1

You’re doing it wrong. The first option you can leave with value="" and put the id="cat" (who is also wrong: id="#cat") and name="categoria" in the select, being like this:

<select id="cat" name="categoria" class="form-input">
    <option value="">Categoria: *</option>
    <option value="buracos nas ruas">Buracos nas ruas</option>
    <option value="esgoto a ceu aberto">Esgoto a céu aberto</option>
    <option value="lixo em local proibido">Lixo em local proibido</option>
    <option value="falta de iluminação">Falta de iluminação</option>
    <option value="outros">Outros</option>
</select>

That one placeholder="Categoria: *" you don’t need it either. The first option is that will play the role of "placeholder".

When it comes to disabling the first option by clicking on select, can do it this way:

// seleciono o select com id="cat"
// com dois eventos: focus e blur
$('#cat').on('focus blur', function(e){
    $('option:first', this) // selecione a primeira option
    .prop('disabled', e.type == 'focus' ? true : false);
    // desabilito se o evento for focus
    // habilito se o evento for blur
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cat" name="categoria" class="form-input" placeholder="Categoria: *">
    <option value="">Categoria: *</option>
    <option value="buracos nas ruas">Buracos nas ruas</option>
    <option value="esgoto a ceu aberto">Esgoto a céu aberto</option>
    <option value="lixo em local proibido">Lixo em local proibido</option>
    <option value="falta de iluminação">Falta de iluminação</option>
    <option value="outros">Outros</option>
</select>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.