Go to the first option after clicking the button

0

I have the following HTML:

<select class="estados" name="estado">
    <option class="op1" value="">1</option>
    <option class="op2" value="">1</option>
    <option class="op3" value="">1</option>
</select>
<input type="reset" class="bt" value="refazer"/>

Let's say I selected 3% with%, when I click on option op3 I want it to let the 1st option input class="bt" be checked.

Do I have to use Jquery's selected ?

    
asked by anonymous 28.01.2015 / 12:25

4 answers

3

If you already know the value, you can set it directly by val() .

$("input.bt").on("click", function () {
    // no seu exemplo você não colocou nenhum value
    // nas options, mas aqui iria o value desejado
    $("select[name=estado]").val("valorNaOpcao1");
});

If you want to always select the first one, this may be the case.

$("input.bt").on("click", function () {
    var $select = $("select[name=estado]");
    var $firstOption = $select.find("option:first-child");
    $select.val($firstOption.val());
});

or

$("input.bt").on("click", function () {
    $("select[name=estado]").val($("select[name=estado] option:first-child").val());
});
    
28.01.2015 / 12:41
1

You can use the methods attr and removeAttr .

Like this:

$(".bt").click = function () {
  $(".op1").attr("selected", "selected");
  $(".op2").removeAttr("selected");
  $(".op3").removeAttr("selected");
};

And to help differentiate the selected option, do so:

<select class="estados" name="estado">
  <option class="op1" value="">1</option>
  <option class="op2" value="">2</option> <- Alteração do valor dentro da tag
  <option class="op3" value="">3</option> <- Alteração do valor dentro da tag
</select>
    
28.01.2015 / 12:34
1

Just use the prop () function to set the option as checked when you click the button.

$(".bt").click(function() {
  $(".op1").prop('selected', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectclass="estados" name="estado">
    <option class="op1" value="">1</option>
    <option class="op2" value="">2</option>
    <option class="op3" value="">3</option>
</select>
<input type="reset" class="bt" value="refazer"/>
    
28.01.2015 / 12:38
1

If you want to reset, that is to return to the initial value you can do this:

jsFiddle: link

$(".bt").on("click", function () {
    $("select.estados option").prop('selected', function() {
        return this.defaultSelected;
    });
});

If you want to force the first one you can only do this:

jsFiddle: link

$(".bt").on("click", function () {
  $("select.estados option").each(function(i){
      $(this).removeAttr("selected");
      if (i == 0) this.selected = true; // onde o "i" é o index desse select, começando em zero
    });
});
    
28.01.2015 / 12:39